context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security; using System.Threading.Tasks; namespace System.ServiceModel { public abstract class ChannelFactory : CommunicationObject, IChannelFactory, IDisposable { private string _configurationName; private IChannelFactory _innerFactory; private ServiceEndpoint _serviceEndpoint; private ClientCredentials _readOnlyClientCredentials; private object _openLock = new object(); //Overload for activation DuplexChannelFactory protected ChannelFactory() : base() { TraceUtility.SetEtwProviderId(); this.TraceOpenAndClose = true; } public ClientCredentials Credentials { get { if (this.Endpoint == null) return null; if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening) { return EnsureCredentials(this.Endpoint); } else { if (_readOnlyClientCredentials == null) { ClientCredentials c = new ClientCredentials(); c.MakeReadOnly(); _readOnlyClientCredentials = c; } return _readOnlyClientCredentials; } } } protected override TimeSpan DefaultCloseTimeout { get { if (this.Endpoint != null && this.Endpoint.Binding != null) { return this.Endpoint.Binding.CloseTimeout; } else { return ServiceDefaults.CloseTimeout; } } } protected override TimeSpan DefaultOpenTimeout { get { if (this.Endpoint != null && this.Endpoint.Binding != null) { return this.Endpoint.Binding.OpenTimeout; } else { return ServiceDefaults.OpenTimeout; } } } public ServiceEndpoint Endpoint { get { return _serviceEndpoint; } } internal IChannelFactory InnerFactory { get { return _innerFactory; } } // This boolean is used to determine if we should read ahead by a single // Message for IDuplexSessionChannels in order to detect null and // autoclose the underlying channel in that case. // Currently only accessed from the Send activity. [Fx.Tag.FriendAccessAllowed("System.ServiceModel.Activities")] internal bool UseActiveAutoClose { get; set; } protected internal void EnsureOpened() { base.ThrowIfDisposed(); if (this.State != CommunicationState.Opened) { lock (_openLock) { if (this.State != CommunicationState.Opened) { this.Open(); } } } } // configurationName can be: // 1. null: don't bind any per-endpoint config (load common behaviors only) // 2. "*" (wildcard): match any endpoint config provided there's exactly 1 // 3. anything else (including ""): match the endpoint config with the same name protected virtual void ApplyConfiguration(string configurationName) { // This method is in the public contract but is not supported on CORECLR or NETNATIVE if (!String.IsNullOrEmpty(configurationName)) { throw ExceptionHelper.PlatformNotSupported(); } } protected abstract ServiceEndpoint CreateDescription(); internal EndpointAddress CreateEndpointAddress(ServiceEndpoint endpoint) { if (endpoint.Address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryEndpointAddressUri)); } return endpoint.Address; } protected virtual IChannelFactory CreateFactory() { if (this.Endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryCannotCreateFactoryWithoutDescription)); } if (this.Endpoint.Binding == null) { if (_configurationName != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxChannelFactoryNoBindingFoundInConfig1, _configurationName))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryNoBindingFoundInConfigOrCode)); } } return ServiceChannelFactory.BuildChannelFactory(this.Endpoint, this.UseActiveAutoClose); } void IDisposable.Dispose() { this.Close(); } private void EnsureSecurityCredentialsManager(ServiceEndpoint endpoint) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); if (endpoint.Behaviors.Find<SecurityCredentialsManager>() == null) { endpoint.Behaviors.Add(new ClientCredentials()); } } private ClientCredentials EnsureCredentials(ServiceEndpoint endpoint) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); ClientCredentials c = endpoint.Behaviors.Find<ClientCredentials>(); if (c == null) { c = new ClientCredentials(); endpoint.Behaviors.Add(c); } return c; } public T GetProperty<T>() where T : class { if (_innerFactory != null) { return _innerFactory.GetProperty<T>(); } else { return null; } } internal bool HasDuplexOperations() { OperationDescriptionCollection operations = this.Endpoint.Contract.Operations; for (int i = 0; i < operations.Count; i++) { OperationDescription operation = operations[i]; if (operation.IsServerInitiated()) { return true; } } return false; } protected void InitializeEndpoint(string configurationName, EndpointAddress address) { _serviceEndpoint = this.CreateDescription(); ServiceEndpoint serviceEndpointFromConfig = null; // Project N and K do not support System.Configuration, but this method is part of Windows Store contract. // The configurationName==null path occurs in normal use. if (configurationName != null) { throw ExceptionHelper.PlatformNotSupported(); // serviceEndpointFromConfig = ConfigLoader.LookupEndpoint(configurationName, address, this.serviceEndpoint.Contract); } if (serviceEndpointFromConfig != null) { _serviceEndpoint = serviceEndpointFromConfig; } else { if (address != null) { this.Endpoint.Address = address; } ApplyConfiguration(configurationName); } _configurationName = configurationName; EnsureSecurityCredentialsManager(_serviceEndpoint); } protected void InitializeEndpoint(ServiceEndpoint endpoint) { if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } _serviceEndpoint = endpoint; ApplyConfiguration(null); EnsureSecurityCredentialsManager(_serviceEndpoint); } protected void InitializeEndpoint(Binding binding, EndpointAddress address) { _serviceEndpoint = this.CreateDescription(); if (binding != null) { this.Endpoint.Binding = binding; } if (address != null) { this.Endpoint.Address = address; } ApplyConfiguration(null); EnsureSecurityCredentialsManager(_serviceEndpoint); } protected override void OnOpened() { // if a client credentials has been configured cache a readonly snapshot of it if (this.Endpoint != null) { ClientCredentials credentials = this.Endpoint.Behaviors.Find<ClientCredentials>(); if (credentials != null) { ClientCredentials credentialsCopy = credentials.Clone(); credentialsCopy.MakeReadOnly(); _readOnlyClientCredentials = credentialsCopy; } } base.OnOpened(); } protected override void OnAbort() { if (_innerFactory != null) { _innerFactory.Abort(); } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state); } protected override void OnEndClose(IAsyncResult result) { CommunicationObjectInternal.OnEnd(result); } internal protected override async Task OnCloseAsync(TimeSpan timeout) { if (_innerFactory != null) { IAsyncChannelFactory asyncFactory = _innerFactory as IAsyncChannelFactory; if (asyncFactory != null) { await asyncFactory.CloseAsync(timeout); } else { _innerFactory.Close(timeout); } } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state); } protected override void OnEndOpen(IAsyncResult result) { CommunicationObjectInternal.OnEnd(result); } protected internal override async Task OnOpenAsync(TimeSpan timeout) { if (_innerFactory != null) { IAsyncChannelFactory asyncFactory = _innerFactory as IAsyncChannelFactory; if (asyncFactory != null) { await asyncFactory.OpenAsync(timeout); } else { _innerFactory.Open(timeout); } } } protected override void OnClose(TimeSpan timeout) { if (_innerFactory != null) { _innerFactory.Close(timeout); } } protected override void OnOpen(TimeSpan timeout) { _innerFactory.Open(timeout); } protected override void OnOpening() { base.OnOpening(); _innerFactory = CreateFactory(); if (WcfEventSource.Instance.ChannelFactoryCreatedIsEnabled()) { WcfEventSource.Instance.ChannelFactoryCreated(this); } if (_innerFactory == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.InnerChannelFactoryWasNotSet)); } } public class ChannelFactory<TChannel> : ChannelFactory, IChannelFactory<TChannel> { private InstanceContext _callbackInstance; private Type _channelType; private TypeLoader _typeLoader; private Type _callbackType; //Overload for activation DuplexChannelFactory protected ChannelFactory(Type channelType) : base() { if (channelType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelType"); } if (!channelType.IsInterface()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryTypeMustBeInterface)); } _channelType = channelType; } // TChannel provides ContractDescription public ChannelFactory() : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } this.InitializeEndpoint((string)null, null); } } // TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding public ChannelFactory(string endpointConfigurationName) : this(endpointConfigurationName, null) { } // TChannel provides ContractDescription, attr/config [TChannel,name] provides Binding, provide Address explicitly public ChannelFactory(string endpointConfigurationName, EndpointAddress remoteAddress) : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } if (endpointConfigurationName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); } this.InitializeEndpoint(endpointConfigurationName, remoteAddress); } } // TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding public ChannelFactory(Binding binding) : this(binding, (EndpointAddress)null) { } public ChannelFactory(Binding binding, String remoteAddress) : this(binding, new EndpointAddress(remoteAddress)) { } // TChannel provides ContractDescription, provide Address,Binding explicitly public ChannelFactory(Binding binding, EndpointAddress remoteAddress) : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } if (binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding"); } this.InitializeEndpoint(binding, remoteAddress); } } // provide ContractDescription,Address,Binding explicitly public ChannelFactory(ServiceEndpoint endpoint) : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } this.InitializeEndpoint(endpoint); } } internal InstanceContext CallbackInstance { get { return _callbackInstance; } set { _callbackInstance = value; } } internal Type CallbackType { get { return _callbackType; } set { _callbackType = value; } } internal ServiceChannelFactory ServiceChannelFactory { get { return (ServiceChannelFactory)InnerFactory; } } internal TypeLoader TypeLoader { get { if (_typeLoader == null) { _typeLoader = new TypeLoader(); } return _typeLoader; } } public TChannel CreateChannel(EndpointAddress address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } return CreateChannel(address, address.Uri); } public virtual TChannel CreateChannel(EndpointAddress address, Uri via) { bool traceOpenAndClose = this.TraceOpenAndClose; try { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } if (this.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxCreateNonDuplexChannel1, this.Endpoint.Contract.Name))); } EnsureOpened(); return (TChannel)this.ServiceChannelFactory.CreateChannel<TChannel>(address, via); } finally { this.TraceOpenAndClose = traceOpenAndClose; } } public TChannel CreateChannel() { return CreateChannel(this.CreateEndpointAddress(this.Endpoint), null); } protected override ServiceEndpoint CreateDescription() { ContractDescription contractDescription = this.TypeLoader.LoadContractDescription(_channelType); ServiceEndpoint endpoint = new ServiceEndpoint(contractDescription); ReflectOnCallbackInstance(endpoint); this.TypeLoader.AddBehaviorsSFx(endpoint, _channelType); return endpoint; } private void ReflectOnCallbackInstance(ServiceEndpoint endpoint) { if (_callbackType != null) { if (endpoint.Contract.CallbackContractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SfxCallbackTypeCannotBeNull, endpoint.Contract.ContractType.FullName))); } this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, _callbackType); } else if (this.CallbackInstance != null && this.CallbackInstance.UserObject != null) { if (endpoint.Contract.CallbackContractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SfxCallbackTypeCannotBeNull, endpoint.Contract.ContractType.FullName))); } object implementation = this.CallbackInstance.UserObject; Type implementationType = implementation.GetType(); this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, implementationType); IEndpointBehavior channelBehavior = implementation as IEndpointBehavior; if (channelBehavior != null) { endpoint.Behaviors.Add(channelBehavior); } IContractBehavior contractBehavior = implementation as IContractBehavior; if (contractBehavior != null) { endpoint.Contract.Behaviors.Add(contractBehavior); } } } //Static funtions to create channels protected static TChannel CreateChannel(String endpointConfigurationName) { ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(endpointConfigurationName); if (channelFactory.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name))); } TChannel channel = channelFactory.CreateChannel(); SetFactoryToAutoClose(channel); return channel; } public static TChannel CreateChannel(Binding binding, EndpointAddress endpointAddress) { ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(binding, endpointAddress); if (channelFactory.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name))); } TChannel channel = channelFactory.CreateChannel(); SetFactoryToAutoClose(channel); return channel; } public static TChannel CreateChannel(Binding binding, EndpointAddress endpointAddress, Uri via) { ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(binding); if (channelFactory.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name))); } TChannel channel = channelFactory.CreateChannel(endpointAddress, via); SetFactoryToAutoClose(channel); return channel; } internal static void SetFactoryToAutoClose(TChannel channel) { //Set the Channel to auto close its ChannelFactory. ServiceChannel serviceChannel = ServiceChannelFactory.GetServiceChannel(channel); serviceChannel.CloseFactory = true; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // LastQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Linq.Parallel { /// <summary> /// Last tries to discover the last element in the source, optionally matching a /// predicate. All partitions search in parallel, publish the greatest index for a /// candidate match, and reach a barrier. Only the partition that "wins" the race, /// i.e. who found the candidate with the largest index, will yield an element. /// /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class LastQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource> { private readonly Func<TSource, bool>? _predicate; // The optional predicate used during the search. private readonly bool _prematureMergeNeeded; // Whether to prematurely merge the input of this operator. //--------------------------------------------------------------------------------------- // Initializes a new last operator. // // Arguments: // child - the child whose data we will reverse // internal LastQueryOperator(IEnumerable<TSource> child, Func<TSource, bool>? predicate) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); _predicate = predicate; _prematureMergeNeeded = Child.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { QueryResults<TSource> childQueryResults = Child.Open(settings, false); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings) { // If the index is not at least increasing, we need to reindex. if (_prematureMergeNeeded) { PartitionedStream<TSource, int> intKeyStream = ExecuteAndCollectResults(inputStream, inputStream.PartitionCount, Child.OutputOrdered, preferStriping, settings).GetPartitionedStream(); WrapHelper<int>(intKeyStream, recipient, settings); } else { WrapHelper<TKey>(inputStream, recipient, settings); } } private void WrapHelper<TKey>(PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // Generate the shared data. LastQueryOperatorState<TKey> operatorState = new LastQueryOperatorState<TKey>(); CountdownEvent sharedBarrier = new CountdownEvent(partitionCount); PartitionedStream<TSource, int> outputStream = new PartitionedStream<TSource, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new LastQueryOperatorEnumerator<TKey>( inputStream[i], _predicate, operatorState, sharedBarrier, settings.CancellationState.MergedCancellationToken, inputStream.KeyComparer, i); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // [ExcludeFromCodeCoverage] internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { Debug.Fail("This method should never be called as fallback to sequential is handled in ParallelEnumerable.First()."); throw new NotSupportedException(); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the last operation. // private class LastQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, int> { private readonly QueryOperatorEnumerator<TSource, TKey> _source; // The data source to enumerate. private readonly Func<TSource, bool>? _predicate; // The optional predicate used during the search. private bool _alreadySearched; // Set once the enumerator has performed the search. private readonly int _partitionId; // ID of this partition // Data shared among partitions. private readonly LastQueryOperatorState<TKey> _operatorState; // The current last candidate and its partition id. private readonly CountdownEvent _sharedBarrier; // Shared barrier, signaled when partitions find their 1st element. private readonly CancellationToken _cancellationToken; // Token used to cancel this operator. private readonly IComparer<TKey> _keyComparer; // Comparer for the order keys //--------------------------------------------------------------------------------------- // Instantiates a new enumerator. // internal LastQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TKey> source, Func<TSource, bool>? predicate, LastQueryOperatorState<TKey> operatorState, CountdownEvent sharedBarrier, CancellationToken cancelToken, IComparer<TKey> keyComparer, int partitionId) { Debug.Assert(source != null); Debug.Assert(operatorState != null); Debug.Assert(sharedBarrier != null); Debug.Assert(keyComparer != null); _source = source; _predicate = predicate; _operatorState = operatorState; _sharedBarrier = sharedBarrier; _cancellationToken = cancelToken; _keyComparer = keyComparer; _partitionId = partitionId; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TSource currentElement, ref int currentKey) { Debug.Assert(_source != null); if (_alreadySearched) { return false; } // Look for the greatest element. TSource candidate = default(TSource)!; TKey candidateKey = default(TKey)!; bool candidateFound = false; try { int loopCount = 0; //counter to help with cancellation TSource value = default(TSource)!; TKey key = default(TKey)!; while (_source.MoveNext(ref value!, ref key)) { if ((loopCount & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // If the predicate is null or the current element satisfies it, we will remember // it as the current partition's candidate for the last element, and move on. if (_predicate == null || _predicate(value)) { candidate = value; candidateKey = key; candidateFound = true; } loopCount++; } // If we found a candidate element, try to publish it, so long as it's greater. if (candidateFound) { lock (_operatorState) { if (_operatorState._partitionId == -1 || _keyComparer.Compare(candidateKey, _operatorState._key) > 0) { _operatorState._partitionId = _partitionId; _operatorState._key = candidateKey; } } } } finally { // No matter whether we exit due to an exception or normal completion, we must ensure // that we signal other partitions that we have completed. Otherwise, we can cause deadlocks. _sharedBarrier.Signal(); } _alreadySearched = true; // Only if we have a candidate do we wait. if (_partitionId == _operatorState._partitionId) { _sharedBarrier.Wait(_cancellationToken); // Now re-read the shared index. If it's the same as ours, we won and return true. if (_operatorState._partitionId == _partitionId) { currentElement = candidate; currentKey = 0; // 1st (and only) element, so we hardcode the output index to 0. return true; } } // If we got here, we didn't win. Return false. return false; } protected override void Dispose(bool disposing) { _source.Dispose(); } } private class LastQueryOperatorState<TKey> { internal TKey _key = default!; internal int _partitionId = -1; } } }
/* * UUnit system from UnityCommunity * Heavily modified * 0.4 release by pboechat * http://wiki.unity3d.com/index.php?title=UUnit * http://creativecommons.org/licenses/by-sa/3.0/ */ using System; using System.Collections.Generic; namespace PlayFab.UUnit { public enum UUnitActiveState { PENDING, // Not started ACTIVE, // Currently testing READY, // An answer is sent by the http thread, but the main thread hasn't finalized the test yet COMPLETE, // Test is finalized and recorded ABORTED // todo }; public class UUnitTestContext { public const float DefaultFloatPrecision = 0.0001f; public const double DefaultDoublePrecision = 0.000001; public UUnitActiveState ActiveState; public UUnitFinishState FinishState; public readonly Action<UUnitTestContext> TestDelegate; public readonly UUnitTestCase TestInstance; public DateTime StartTime; public DateTime EndTime; public string TestResultMsg; public readonly string Name; public UUnitTestContext(UUnitTestCase testInstance, Action<UUnitTestContext> testDelegate, string name) { TestInstance = testInstance; TestDelegate = testDelegate; ActiveState = UUnitActiveState.PENDING; Name = name; } internal void EndTest(UUnitFinishState finishState, string resultMsg) { EndTime = DateTime.UtcNow; TestResultMsg = resultMsg; FinishState = finishState; ActiveState = UUnitActiveState.READY; } public void Skip(string message = "") { EndTime = DateTime.UtcNow; EndTest(UUnitFinishState.SKIPPED, message); throw new UUnitSkipException(message); } public void Fail(string message = null) { if (string.IsNullOrEmpty(message)) message = "fail"; EndTest(UUnitFinishState.FAILED, message); throw new UUnitAssertException(message); } public void True(bool boolean, string message = null) { if (boolean) return; if (string.IsNullOrEmpty(message)) message = "Expected: true, Actual: false"; Fail(message); } public void False(bool boolean, string message = null) { if (!boolean) return; if (string.IsNullOrEmpty(message)) message = "Expected: false, Actual: true"; Fail(message); } public void NotNull(object something, string message = null) { if (something != null) return; // Success if (string.IsNullOrEmpty(message)) message = "Null object"; Fail(message); } public void IsNull(object something, string message = null) { if (something == null) return; if (string.IsNullOrEmpty(message)) message = "Not null object"; Fail(message); } public void StringEquals(string wanted, string got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void SbyteEquals(sbyte? wanted, sbyte? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ByteEquals(byte? wanted, byte? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ShortEquals(short? wanted, short? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void UshortEquals(ushort? wanted, ushort? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void IntEquals(int? wanted, int? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void UintEquals(uint? wanted, uint? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void LongEquals(long? wanted, long? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ULongEquals(ulong? wanted, ulong? got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void FloatEquals(float? wanted, float? got, float precision = DefaultFloatPrecision, string message = null) { if (wanted == null && got == null) return; if (wanted != null && got != null && Math.Abs(wanted.Value - got.Value) < precision) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void DoubleEquals(double? wanted, double? got, double precision = DefaultDoublePrecision, string message = null) { if (wanted == null && got == null) return; if (wanted != null && got != null && Math.Abs(wanted.Value - got.Value) < precision) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ObjEquals(object wanted, object got, string message = null) { if (wanted == null && got == null) return; if (wanted != null && got != null && wanted.Equals(got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void SequenceEquals<T>(IEnumerable<T> wanted, IEnumerable<T> got, string message = null) { var wEnum = wanted.GetEnumerator(); var gEnum = got.GetEnumerator(); bool wNext, gNext; var count = 0; while (true) { wNext = wEnum.MoveNext(); gNext = gEnum.MoveNext(); if (wNext != gNext) Fail(message); if (!wNext) break; count++; ObjEquals(wEnum.Current, gEnum.Current, "Element at " + count + ": " + message); } } } }
#region File Description //----------------------------------------------------------------------------- // MenuScreen.cs // // XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace Pickture { /// <summary> /// Base class for screens that contain a menu of options. The user can /// move up and down to select an entry, or cancel to back out of the screen. /// </summary> abstract class MenuScreen : GameScreen { #region Fields List<MenuEntry> menuEntries = new List<MenuEntry>(); int selectedEntry = 0; string menuTitle; #endregion #region Properties /// <summary> /// Gets the list of menu entries, so derived classes can add /// or change the menu contents. /// </summary> protected IList<MenuEntry> MenuEntries { get { return menuEntries; } } protected int SelectedEntry { get { return selectedEntry; } } #endregion #region Initialization /// <summary> /// Constructor. /// </summary> public MenuScreen(string menuTitle) { this.menuTitle = menuTitle; TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); } #endregion #region Handle Input /// <summary> /// Responds to user input, changing the selected entry and accepting /// or cancelling the menu. /// </summary> public override void HandleInput(InputState input) { // Move to the previous menu entry? if (input.MenuUp) { selectedEntry--; if (selectedEntry < 0) selectedEntry = menuEntries.Count - 1; } // Move to the next menu entry? if (input.MenuDown) { selectedEntry++; if (selectedEntry >= menuEntries.Count) selectedEntry = 0; } // Accept or cancel the menu? if (input.MenuSelect) { OnSelectEntry(selectedEntry); } else if (input.MenuCancel) { OnCancel(); } } /// <summary> /// Handler for when the user has chosen a menu entry. /// </summary> protected virtual void OnSelectEntry(int entryIndex) { menuEntries[selectedEntry].OnSelectEntry(); } /// <summary> /// Handler for when the user has cancelled the menu. /// </summary> protected virtual void OnCancel() { ExitScreen(); } /// <summary> /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler. /// </summary> protected void OnCancel(object sender, EventArgs e) { OnCancel(); } #endregion #region Update and Draw /// <summary> /// Updates the menu. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // Update each nested MenuEntry object. for (int i = 0; i < menuEntries.Count; i++) { bool isSelected = IsActive && (i == selectedEntry); menuEntries[i].Update(this, isSelected, gameTime); } } /// <summary> /// Draws the menu. /// </summary> public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; Vector2 position = new Vector2(100, 150); // Make the menu slide into place during transitions, using a // power curve to make things look more interesting (this makes // the movement slow down as it nears the end). float transitionOffset = (float)Math.Pow(TransitionPosition, 2); if (ScreenState == ScreenState.TransitionOn) position.X -= transitionOffset * 256; else position.X += transitionOffset * 512; spriteBatch.Begin(); // Draw each menu entry in turn. for (int i = 0; i < menuEntries.Count; i++) { MenuEntry menuEntry = menuEntries[i]; bool isSelected = IsActive && (i == selectedEntry); menuEntry.Draw(this, position, isSelected, gameTime); position.Y += menuEntry.GetHeight(this); } // Draw the menu title. Vector2 titlePosition = new Vector2(426, 80); Vector2 titleOrigin = font.MeasureString(menuTitle) / 2; Color titleColor = new Color(192, 192, 192, TransitionAlpha); float titleScale = 1.25f; titlePosition.Y -= transitionOffset * 100; spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0, titleOrigin, titleScale, SpriteEffects.None, 0); spriteBatch.End(); } #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. /*============================================================ ** ** ** ** ** ** CustomAttributeBuilder is a helper class to help building custom attribute. ** ** ===========================================================*/ using System.Buffers.Binary; using System.IO; using System.Text; using System.Diagnostics; namespace System.Reflection.Emit { public class CustomAttributeBuilder { // public constructor to form the custom attribute with constructor and constructor // parameters. public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs) { InitCustomAttributeBuilder(con, constructorArgs, Array.Empty<PropertyInfo>(), Array.Empty<object>(), Array.Empty<FieldInfo>(), Array.Empty<object>()); } // public constructor to form the custom attribute with constructor, constructor // parameters and named properties. public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues) { InitCustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, Array.Empty<FieldInfo>(), Array.Empty<object>()); } // public constructor to form the custom attribute with constructor and constructor // parameters. public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, FieldInfo[] namedFields, object[] fieldValues) { InitCustomAttributeBuilder(con, constructorArgs, Array.Empty<PropertyInfo>(), Array.Empty<object>(), namedFields, fieldValues); } // public constructor to form the custom attribute with constructor and constructor // parameters. public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { InitCustomAttributeBuilder(con, constructorArgs, namedProperties, propertyValues, namedFields, fieldValues); } // Check that a type is suitable for use in a custom attribute. private bool ValidateType(Type t) { if (t.IsPrimitive) { return t != typeof(IntPtr) && t != typeof(UIntPtr); } if (t == typeof(string) || t == typeof(Type)) { return true; } if (t.IsEnum) { switch (Type.GetTypeCode(Enum.GetUnderlyingType(t))) { case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return true; default: return false; } } if (t.IsArray) { if (t.GetArrayRank() != 1) return false; return ValidateType(t.GetElementType()!); } return t == typeof(object); } internal void InitCustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, PropertyInfo[] namedProperties, object[] propertyValues, FieldInfo[] namedFields, object[] fieldValues) { if (con == null) throw new ArgumentNullException(nameof(con)); if (constructorArgs == null) throw new ArgumentNullException(nameof(constructorArgs)); if (namedProperties == null) throw new ArgumentNullException(nameof(namedProperties)); if (propertyValues == null) throw new ArgumentNullException(nameof(propertyValues)); if (namedFields == null) throw new ArgumentNullException(nameof(namedFields)); if (fieldValues == null) throw new ArgumentNullException(nameof(fieldValues)); if (namedProperties.Length != propertyValues.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedProperties, propertyValues"); if (namedFields.Length != fieldValues.Length) throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedFields, fieldValues"); if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static || (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) throw new ArgumentException(SR.Argument_BadConstructor); if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard) throw new ArgumentException(SR.Argument_BadConstructorCallConv); // Cache information used elsewhere. m_con = con; m_constructorArgs = new object?[constructorArgs.Length]; Array.Copy(constructorArgs, 0, m_constructorArgs, 0, constructorArgs.Length); Type[] paramTypes; int i; // Get the types of the constructor's formal parameters. paramTypes = con.GetParameterTypes(); // Since we're guaranteed a non-var calling convention, the number of arguments must equal the number of parameters. if (paramTypes.Length != constructorArgs.Length) throw new ArgumentException(SR.Argument_BadParameterCountsForConstructor); // Verify that the constructor has a valid signature (custom attributes only support a subset of our type system). for (i = 0; i < paramTypes.Length; i++) if (!ValidateType(paramTypes[i])) throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute); // Now verify that the types of the actual parameters are compatible with the types of the formal parameters. for (i = 0; i < paramTypes.Length; i++) { object? constructorArg = constructorArgs[i]; if (constructorArg == null) { if (paramTypes[i].IsValueType) { throw new ArgumentNullException($"{nameof(constructorArgs)}[{i}]"); } continue; } VerifyTypeAndPassedObjectType(paramTypes[i], constructorArg.GetType(), $"{nameof(constructorArgs)}[{i}]"); } // Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it. MemoryStream stream = new MemoryStream(); BinaryWriter writer = new BinaryWriter(stream); // Write the blob protocol version (currently 1). writer.Write((ushort)1); // Now emit the constructor argument values (no need for types, they're inferred from the constructor signature). for (i = 0; i < constructorArgs.Length; i++) EmitValue(writer, paramTypes[i], constructorArgs[i]); // Next a short with the count of properties and fields. writer.Write((ushort)(namedProperties.Length + namedFields.Length)); // Emit all the property sets. for (i = 0; i < namedProperties.Length; i++) { // Validate the property. PropertyInfo property = namedProperties[i]; if (property == null) throw new ArgumentNullException("namedProperties[" + i + "]"); // Allow null for non-primitive types only. Type propType = property.PropertyType; object propertyValue = propertyValues[i]; if (propertyValue == null && propType.IsValueType) throw new ArgumentNullException("propertyValues[" + i + "]"); // Validate property type. if (!ValidateType(propType)) throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute); // Property has to be writable. if (!property.CanWrite) throw new ArgumentException(SR.Argument_NotAWritableProperty); // Property has to be from the same class or base class as ConstructorInfo. if (property.DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) && !con.DeclaringType!.IsSubclassOf(property.DeclaringType!)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases // separately. if (!TypeBuilder.IsTypeEqual(property.DeclaringType, con.DeclaringType)) { // IsSubclassOf is overloaded to do the right thing if // the constructor is a TypeBuilder, but we still need // to deal with the case where the property's declaring // type is one. if (!(property.DeclaringType is TypeBuilder) || !con.DeclaringType.IsSubclassOf(((TypeBuilder)property.DeclaringType).BakedRuntimeType)) throw new ArgumentException(SR.Argument_BadPropertyForConstructorBuilder); } } // Make sure the property's type can take the given value. // Note that there will be no coersion. if (propertyValue != null) { VerifyTypeAndPassedObjectType(propType, propertyValue.GetType(), $"{nameof(propertyValues)}[{i}]"); } // First a byte indicating that this is a property. writer.Write((byte)CustomAttributeEncoding.Property); // Emit the property type, name and value. EmitType(writer, propType); EmitString(writer, namedProperties[i].Name); EmitValue(writer, propType, propertyValue); } // Emit all the field sets. for (i = 0; i < namedFields.Length; i++) { // Validate the field. FieldInfo namedField = namedFields[i]; if (namedField == null) throw new ArgumentNullException("namedFields[" + i + "]"); // Allow null for non-primitive types only. Type fldType = namedField.FieldType; object fieldValue = fieldValues[i]; if (fieldValue == null && fldType.IsValueType) throw new ArgumentNullException("fieldValues[" + i + "]"); // Validate field type. if (!ValidateType(fldType)) throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute); // Field has to be from the same class or base class as ConstructorInfo. if (namedField.DeclaringType != con.DeclaringType && (!(con.DeclaringType is TypeBuilderInstantiation)) && !con.DeclaringType!.IsSubclassOf(namedField.DeclaringType!)) { // Might have failed check because one type is a XXXBuilder // and the other is not. Deal with these special cases // separately. if (!TypeBuilder.IsTypeEqual(namedField.DeclaringType, con.DeclaringType)) { // IsSubclassOf is overloaded to do the right thing if // the constructor is a TypeBuilder, but we still need // to deal with the case where the field's declaring // type is one. if (!(namedField.DeclaringType is TypeBuilder) || !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType!).BakedRuntimeType)) throw new ArgumentException(SR.Argument_BadFieldForConstructorBuilder); } } // Make sure the field's type can take the given value. // Note that there will be no coersion. if (fieldValue != null) { VerifyTypeAndPassedObjectType(fldType, fieldValue.GetType(), $"{nameof(fieldValues)}[{i}]"); } // First a byte indicating that this is a field. writer.Write((byte)CustomAttributeEncoding.Field); // Emit the field type, name and value. EmitType(writer, fldType); EmitString(writer, namedField.Name); EmitValue(writer, fldType, fieldValue); } // Create the blob array. m_blob = ((MemoryStream)writer.BaseStream).ToArray(); } private static void VerifyTypeAndPassedObjectType(Type type, Type passedType, string paramName) { if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type)) { throw new ArgumentException(SR.Argument_ConstantDoesntMatch); } if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr)) { throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, passedType), paramName); } } private static void EmitType(BinaryWriter writer, Type type) { if (type.IsPrimitive) { switch (Type.GetTypeCode(type)) { case TypeCode.SByte: writer.Write((byte)CustomAttributeEncoding.SByte); break; case TypeCode.Byte: writer.Write((byte)CustomAttributeEncoding.Byte); break; case TypeCode.Char: writer.Write((byte)CustomAttributeEncoding.Char); break; case TypeCode.Boolean: writer.Write((byte)CustomAttributeEncoding.Boolean); break; case TypeCode.Int16: writer.Write((byte)CustomAttributeEncoding.Int16); break; case TypeCode.UInt16: writer.Write((byte)CustomAttributeEncoding.UInt16); break; case TypeCode.Int32: writer.Write((byte)CustomAttributeEncoding.Int32); break; case TypeCode.UInt32: writer.Write((byte)CustomAttributeEncoding.UInt32); break; case TypeCode.Int64: writer.Write((byte)CustomAttributeEncoding.Int64); break; case TypeCode.UInt64: writer.Write((byte)CustomAttributeEncoding.UInt64); break; case TypeCode.Single: writer.Write((byte)CustomAttributeEncoding.Float); break; case TypeCode.Double: writer.Write((byte)CustomAttributeEncoding.Double); break; default: Debug.Fail("Invalid primitive type"); break; } } else if (type.IsEnum) { writer.Write((byte)CustomAttributeEncoding.Enum); EmitString(writer, type.AssemblyQualifiedName!); } else if (type == typeof(string)) { writer.Write((byte)CustomAttributeEncoding.String); } else if (type == typeof(Type)) { writer.Write((byte)CustomAttributeEncoding.Type); } else if (type.IsArray) { writer.Write((byte)CustomAttributeEncoding.Array); EmitType(writer, type.GetElementType()!); } else { // Tagged object case. writer.Write((byte)CustomAttributeEncoding.Object); } } private static void EmitString(BinaryWriter writer, string str) { // Strings are emitted with a length prefix in a compressed format (1, 2 or 4 bytes) as used internally by metadata. byte[] utf8Str = Encoding.UTF8.GetBytes(str); uint length = (uint)utf8Str.Length; if (length <= 0x7f) { writer.Write((byte)length); } else if (length <= 0x3fff) { writer.Write(BinaryPrimitives.ReverseEndianness((short)(length | 0x80_00))); } else { writer.Write(BinaryPrimitives.ReverseEndianness(length | 0xC0_00_00_00)); } writer.Write(utf8Str); } private static void EmitValue(BinaryWriter writer, Type type, object? value) { if (type.IsEnum) { switch (Type.GetTypeCode(Enum.GetUnderlyingType(type))) { case TypeCode.SByte: writer.Write((sbyte)value!); break; case TypeCode.Byte: writer.Write((byte)value!); break; case TypeCode.Int16: writer.Write((short)value!); break; case TypeCode.UInt16: writer.Write((ushort)value!); break; case TypeCode.Int32: writer.Write((int)value!); break; case TypeCode.UInt32: writer.Write((uint)value!); break; case TypeCode.Int64: writer.Write((long)value!); break; case TypeCode.UInt64: writer.Write((ulong)value!); break; default: Debug.Fail("Invalid enum base type"); break; } } else if (type == typeof(string)) { if (value == null) writer.Write((byte)0xff); else EmitString(writer, (string)value); } else if (type == typeof(Type)) { if (value == null) writer.Write((byte)0xff); else { string? typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName); if (typeName == null) throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeForCA, value.GetType())); EmitString(writer, typeName); } } else if (type.IsArray) { if (value == null) writer.Write((uint)0xffffffff); else { Array a = (Array)value; Type et = type.GetElementType()!; writer.Write(a.Length); for (int i = 0; i < a.Length; i++) EmitValue(writer, et, a.GetValue(i)); } } else if (type.IsPrimitive) { switch (Type.GetTypeCode(type)) { case TypeCode.SByte: writer.Write((sbyte)value!); break; case TypeCode.Byte: writer.Write((byte)value!); break; case TypeCode.Char: writer.Write(Convert.ToUInt16((char)value!)); break; case TypeCode.Boolean: writer.Write((byte)((bool)value! ? 1 : 0)); break; case TypeCode.Int16: writer.Write((short)value!); break; case TypeCode.UInt16: writer.Write((ushort)value!); break; case TypeCode.Int32: writer.Write((int)value!); break; case TypeCode.UInt32: writer.Write((uint)value!); break; case TypeCode.Int64: writer.Write((long)value!); break; case TypeCode.UInt64: writer.Write((ulong)value!); break; case TypeCode.Single: writer.Write((float)value!); break; case TypeCode.Double: writer.Write((double)value!); break; default: Debug.Fail("Invalid primitive type"); break; } } else if (type == typeof(object)) { // Tagged object case. Type instances aren't actually Type, they're some subclass (such as RuntimeType or // TypeBuilder), so we need to canonicalize this case back to Type. If we have a null value we follow the convention // used by C# and emit a null typed as a string (it doesn't really matter what type we pick as long as it's a // reference type). Type ot = value == null ? typeof(string) : value is Type ? typeof(Type) : value.GetType(); // value cannot be a "System.Object" object. // If we allow this we will get into an infinite recursion if (ot == typeof(object)) throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, ot)); EmitType(writer, ot); EmitValue(writer, ot, value); } else { string typename = "null"; if (value != null) typename = value.GetType().ToString(); throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, typename)); } } // return the byte interpretation of the custom attribute internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner) { CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false); } /// <summary> /// Call this function with toDisk=1, after on disk module has been snapped. /// </summary> internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk) { TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk, typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType); } internal ConstructorInfo m_con = null!; internal object?[] m_constructorArgs = null!; internal byte[] m_blob = null!; } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Metadata { #region Namespaces using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Data.Edm; using Microsoft.Data.Edm.Library; using Microsoft.Data.Edm.Validation; #endregion Namespaces /// <summary> /// Class with utility methods for dealing with OData metadata that are shared with the OData.Query project. /// </summary> internal static class MetadataUtilsCommon { /// <summary> /// Checks whether a type reference refers to an OData primitive type (i.e., a primitive, non-stream type). /// </summary> /// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param> /// <returns>true if the <paramref name="typeReference"/> is an OData primitive type reference; otherwise false.</returns> internal static bool IsODataPrimitiveTypeKind(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference"); ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition"); return typeReference.Definition.IsODataPrimitiveTypeKind(); } /// <summary> /// Checks whether a type refers to an OData primitive type (i.e., a primitive, non-stream type). /// </summary> /// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param> /// <returns>true if the <paramref name="type"/> is an OData primitive type; otherwise false.</returns> internal static bool IsODataPrimitiveTypeKind(this IEdmType type) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(type, "type"); EdmTypeKind typeKind = type.TypeKind; if (typeKind != EdmTypeKind.Primitive) { return false; } // also make sure it is not a stream return !type.IsStream(); } /// <summary> /// Checks whether a type reference refers to an OData complex type. /// </summary> /// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param> /// <returns>true if the <paramref name="typeReference"/> is an OData complex type reference; otherwise false.</returns> internal static bool IsODataComplexTypeKind(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference"); ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition"); return typeReference.Definition.IsODataComplexTypeKind(); } /// <summary> /// Checks whether a type refers to an OData complex type. /// </summary> /// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param> /// <returns>true if the <paramref name="type"/> is an OData complex type; otherwise false.</returns> internal static bool IsODataComplexTypeKind(this IEdmType type) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(type, "type"); return type.TypeKind == EdmTypeKind.Complex; } /// <summary> /// Checks whether a type reference refers to an OData entity type. /// </summary> /// <param name="typeReference">The (non-null) <see cref="IEdmTypeReference"/> to check.</param> /// <returns>true if the <paramref name="typeReference"/> is an OData entity type reference; otherwise false.</returns> internal static bool IsODataEntityTypeKind(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference"); ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition"); return typeReference.Definition.IsODataEntityTypeKind(); } /// <summary> /// Checks whether a type refers to an OData entity type. /// </summary> /// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param> /// <returns>true if the <paramref name="type"/> is an OData entity type; otherwise false.</returns> internal static bool IsODataEntityTypeKind(this IEdmType type) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(type, "type"); return type.TypeKind == EdmTypeKind.Entity; } /// <summary> /// Checks whether a type reference is considered a value type in OData. /// </summary> /// <param name="typeReference">The <see cref="IEdmTypeReference"/> to check.</param> /// <returns>true if the <paramref name="typeReference"/> is considered a value type; otherwise false.</returns> /// <remarks> /// The notion of value type in the OData space is driven by the IDSMP requirements where /// Clr types denote the primitive types. /// </remarks> internal static bool IsODataValueType(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); IEdmPrimitiveTypeReference primitiveTypeReference = typeReference.AsPrimitiveOrNull(); if (primitiveTypeReference == null) { return false; } switch (primitiveTypeReference.PrimitiveKind()) { case EdmPrimitiveTypeKind.Boolean: case EdmPrimitiveTypeKind.Byte: case EdmPrimitiveTypeKind.DateTime: case EdmPrimitiveTypeKind.DateTimeOffset: case EdmPrimitiveTypeKind.Decimal: case EdmPrimitiveTypeKind.Double: case EdmPrimitiveTypeKind.Guid: case EdmPrimitiveTypeKind.Int16: case EdmPrimitiveTypeKind.Int32: case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.SByte: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Time: return true; default: return false; } } /// <summary> /// Checks whether a type reference refers to a OData collection value type of non-entity elements. /// </summary> /// <param name="typeReference">The (non-null) <see cref="IEdmType"/> to check.</param> /// <returns>true if the <paramref name="typeReference"/> is a non-entity OData collection value type; otherwise false.</returns> internal static bool IsNonEntityODataCollectionTypeKind(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference"); ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition"); return typeReference.Definition.IsNonEntityODataCollectionTypeKind(); } /// <summary> /// Checks whether a type refers to a OData collection value type of non-entity elements. /// </summary> /// <param name="type">The (non-null) <see cref="IEdmType"/> to check.</param> /// <returns>true if the <paramref name="type"/> is a non-entity OData collection value type; otherwise false.</returns> internal static bool IsNonEntityODataCollectionTypeKind(this IEdmType type) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(type != null, "type != null"); IEdmCollectionType collectionType = type as IEdmCollectionType; // Return false if this is not a collection type, or if it's a collection of entity types (i.e., a navigation property) if (collectionType == null || (collectionType.ElementType != null && collectionType.ElementType.TypeKind() == EdmTypeKind.Entity)) { return false; } Debug.Assert(collectionType.TypeKind == EdmTypeKind.Collection, "Expected collection type kind."); return true; } /// <summary> /// Gets the full name of the definition referred to by the type reference. /// </summary> /// <param name="typeReference">The type reference to get the full name for.</param> /// <returns>The full name of this <paramref name="typeReference"/>.</returns> /// <remarks> /// Note that this method is different from the EdmLib FullName extension method in that it also returns /// names for collection types. For EdmLib, collection types are functions and thus don't have a full name. /// The name/string they use in CSDL is just shorthand for them. /// </remarks> internal static string ODataFullName(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); ExceptionUtils.CheckArgumentNotNull(typeReference, "typeReference"); ExceptionUtils.CheckArgumentNotNull(typeReference.Definition, "typeReference.Definition"); return typeReference.Definition.ODataFullName(); } /// <summary> /// Gets the full name of the type. /// </summary> /// <param name="type">The type to get the full name for.</param> /// <returns>The full name of the <paramref name="type"/>.</returns> /// <remarks> /// Note that this method is different from the EdmLib FullName extension method in that it also returns /// names for collection types. For EdmLib, collection types are functions and thus don't have a full name. /// The name/string they use in CSDL is just shorthand for them. /// </remarks> internal static string ODataFullName(this IEdmType type) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(type != null, "type != null"); // Handle collection type names here since for EdmLib collection values are functions // that do not have a full name IEdmCollectionType collectionType = type as IEdmCollectionType; if (collectionType != null) { string elementTypeName = collectionType.ElementType.ODataFullName(); if (elementTypeName == null) { return null; } return "Collection(" + elementTypeName + ")"; } var namedDefinition = type as IEdmSchemaElement; return namedDefinition != null ? namedDefinition.FullName() : null; } /// <summary> /// Casts an <see cref="IEdmTypeReference"/> to a <see cref="IEdmPrimitiveTypeReference"/> or returns null if this is not supported. /// </summary> /// <param name="typeReference">The type reference to convert.</param> /// <returns>An <see cref="IEdmPrimitiveTypeReference"/> instance or null if the <paramref name="typeReference"/> cannot be converted.</returns> internal static IEdmPrimitiveTypeReference AsPrimitiveOrNull(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); if (typeReference == null) { return null; } return typeReference.TypeKind() == EdmTypeKind.Primitive ? typeReference.AsPrimitive() : null; } /// <summary> /// Casts an <see cref="IEdmTypeReference"/> to a <see cref="IEdmComplexTypeReference"/> or returns null if this is not supported. /// </summary> /// <param name="typeReference">The type reference to convert.</param> /// <returns>An <see cref="IEdmComplexTypeReference"/> instance or null if the <paramref name="typeReference"/> cannot be converted.</returns> internal static IEdmEntityTypeReference AsEntityOrNull(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); if (typeReference == null) { return null; } return typeReference.TypeKind() == EdmTypeKind.Entity ? typeReference.AsEntity() : null; } /// <summary> /// Casts an <see cref="IEdmTypeReference"/> to a <see cref="IEdmStructuredTypeReference"/> or returns null if this is not supported. /// </summary> /// <param name="typeReference">The type reference to convert.</param> /// <returns>An <see cref="IEdmStructuredTypeReference"/> instance or null if the <paramref name="typeReference"/> cannot be converted.</returns> internal static IEdmStructuredTypeReference AsStructuredOrNull(this IEdmTypeReference typeReference) { DebugUtils.CheckNoExternalCallers(); if (typeReference == null) { return null; } return typeReference.IsStructured() ? typeReference.AsStructured() : null; } /// <summary> /// Determines if a <paramref name="sourcePrimitiveType"/> is convertibale according to OData rules to the /// <paramref name="targetPrimitiveType"/>. /// </summary> /// <param name="sourcePrimitiveType">The type which is to be converted.</param> /// <param name="targetPrimitiveType">The type to which we want to convert.</param> /// <returns>true if the source type is convertible to the target type; otherwise false.</returns> internal static bool CanConvertPrimitiveTypeTo( IEdmPrimitiveType sourcePrimitiveType, IEdmPrimitiveType targetPrimitiveType) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(sourcePrimitiveType != null, "sourcePrimitiveType != null"); Debug.Assert(targetPrimitiveType != null, "targetPrimitiveType != null"); EdmPrimitiveTypeKind sourcePrimitiveKind = sourcePrimitiveType.PrimitiveKind; EdmPrimitiveTypeKind targetPrimitiveKind = targetPrimitiveType.PrimitiveKind; switch (sourcePrimitiveKind) { case EdmPrimitiveTypeKind.SByte: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.SByte: case EdmPrimitiveTypeKind.Int16: case EdmPrimitiveTypeKind.Int32: case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Double: case EdmPrimitiveTypeKind.Decimal: return true; } break; case EdmPrimitiveTypeKind.Byte: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Byte: case EdmPrimitiveTypeKind.Int16: case EdmPrimitiveTypeKind.Int32: case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Double: case EdmPrimitiveTypeKind.Decimal: return true; } break; case EdmPrimitiveTypeKind.Int16: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Int16: case EdmPrimitiveTypeKind.Int32: case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Double: case EdmPrimitiveTypeKind.Decimal: return true; } break; case EdmPrimitiveTypeKind.Int32: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Int32: case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Double: case EdmPrimitiveTypeKind.Decimal: return true; } break; case EdmPrimitiveTypeKind.Int64: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Int64: case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Double: case EdmPrimitiveTypeKind.Decimal: return true; } break; case EdmPrimitiveTypeKind.Single: switch (targetPrimitiveKind) { case EdmPrimitiveTypeKind.Single: case EdmPrimitiveTypeKind.Double: return true; } break; default: if (sourcePrimitiveKind == targetPrimitiveKind) { return true; } break; } return false; } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace tk2dEditor.SpriteAnimationEditor { public class TimelineEditor { // State public class State { int _selectedFrame = -1, _selectedTrigger = -1; public enum Type { None, // All pending actions MoveHandle, // Actions Action, Move, Resize } public int selectedFrame { get { return _selectedFrame; } set { ResetSelection(); _selectedFrame = value; } } public Type type = Type.None; public int activeFrame = -1; public int insertMarker = -1; public List<tk2dSpriteAnimationFrame> backupFrames = new List<tk2dSpriteAnimationFrame>(); public int selectedTrigger { get { return _selectedTrigger; } set { ResetSelection(); _selectedTrigger = value; } } public int movingTrigger = -1; public Vector2 frameSelectionOffset = Vector2.zero; public void Reset() { ResetSelection(); ResetState(); } public void ResetSelection() { _selectedFrame = -1; _selectedTrigger = -1; } public void ResetState() { activeFrame = -1; type = Type.None; backupFrames.Clear(); movingTrigger = -1; insertMarker = -1; frameSelectionOffset.Set(0, 0); } } State state = new State(); public State CurrentState { get { return state; } } void Repaint() { HandleUtility.Repaint(); } // Internal int clipLeftHeaderSpace = 16; int clipHeight = 80; int clipHeightScrollBar = 94; Vector2 clipScrollbar = Vector2.zero; // Trigger rects and selection utility Rect GetRectForTrigger(Rect triggerRect, int frame) { return new Rect(triggerRect.x + clipLeftHeaderSpace + frameWidth * frame - 3, triggerRect.y + 1, 5, 14); } int GetRoundedSelectedTrigger(Rect triggerRect, Vector2 mousePosition) { return (int)Mathf.Round((mousePosition.x - triggerRect.x - clipLeftHeaderSpace) / frameWidth); } int GetSelectedTrigger(Rect triggerRect, Vector2 mousePosition) { int rounded = GetRoundedSelectedTrigger(triggerRect, mousePosition); Rect r = GetRectForTrigger(triggerRect, rounded); return r.Contains(mousePosition) ? rounded : -1; } // Framegroup rect Vector2 GetInsertMarkerPositionForFrameGroup(Rect fgRect, int frameGroup, List<ClipEditor.FrameGroup> frameGroups) { int frame = (frameGroup >= frameGroups.Count) ? ( frameGroups[frameGroups.Count - 1].startFrame + frameGroups[frameGroups.Count - 1].frames.Count ) : frameGroups[frameGroup].startFrame; return new Vector2(fgRect.x + clipLeftHeaderSpace + frameWidth * frame, fgRect.y); } Rect GetRectForFrame(Rect fgRect, int frame, int numFrames) { return new Rect(fgRect.x + clipLeftHeaderSpace + frameWidth * frame, fgRect.y, numFrames * frameWidth, fgRect.height); } Rect GetRectForFrameGroup(Rect fgRect, ClipEditor.FrameGroup frameGroup) { return new Rect(fgRect.x + clipLeftHeaderSpace + frameWidth * frameGroup.startFrame, fgRect.y, frameGroup.frames.Count * frameWidth, fgRect.height); } int GetSelectedFrame(Rect fgRect, Vector2 mousePosition) { return (int)Mathf.Floor((mousePosition.x - fgRect.x - clipLeftHeaderSpace) / frameWidth); } int GetSelectedFrameGroup(Rect fgRect, Vector2 mousePosition, List<ClipEditor.FrameGroup> frameGroups, bool insert) { int frame = GetSelectedFrame(fgRect, mousePosition); int currrentFrameGroup = 0; int newSel = insert ? frameGroups.Count : -1; foreach (ClipEditor.FrameGroup fg in frameGroups) { if (frame >= fg.startFrame && frame < fg.startFrame + fg.frames.Count) newSel = currrentFrameGroup; ++currrentFrameGroup; } return newSel; } Rect GetResizeRectFromFrameRect(Rect r) { int resizeHandleSize = (frameWidth < 15) ? 3 : 10; return new Rect(r.x + r.width - 1 - resizeHandleSize, r.y, resizeHandleSize, r.height); } // Frame width int frameWidth { get { if (tk2dPreferences.inst.animFrameWidth == -1) return 80; else return Mathf.Clamp(tk2dPreferences.inst.animFrameWidth, minFrameWidth, maxFrameWidth); } set { tk2dPreferences.inst.animFrameWidth = value; } } const int minFrameWidth = 10; const int maxFrameWidth = 100; public void Reset() { state.Reset(); } public void Draw(int windowWidth, tk2dSpriteAnimationClip clip, List<ClipEditor.FrameGroup> frameGroups, float clipTimeMarker) { int space = clipLeftHeaderSpace; int requiredWidth = space + (clip.frames.Length + 1) * frameWidth; int clipHeightTotal = (requiredWidth > windowWidth) ? clipHeightScrollBar : clipHeight; clipScrollbar = GUILayout.BeginScrollView(clipScrollbar, GUILayout.Height(clipHeightTotal), GUILayout.ExpandWidth(true)); GUILayout.BeginVertical(); // Draw timeline axis GUILayout.Box("", EditorStyles.toolbar, GUILayout.ExpandWidth(true)); Rect timelineRect = GUILayoutUtility.GetLastRect(); DrawAxis(clip, new Rect(timelineRect.x + space, timelineRect.y, timelineRect.width - space, timelineRect.height), frameWidth); // Draw background and derive trigger rect GUILayout.Box("", tk2dEditorSkin.Anim_BG, GUILayout.ExpandWidth(true), GUILayout.Height(16)); Rect triggerRect = GUILayoutUtility.GetLastRect(); // Trigger helpbox Rect triggerHelpBox = new Rect(triggerRect.x, triggerRect.y, triggerRect.height, triggerRect.height); if (GUIUtility.hotControl == 0 && triggerHelpBox.Contains(Event.current.mousePosition)) GUI.Label(new Rect(triggerHelpBox.x, triggerHelpBox.y, 150, triggerHelpBox.height), "Double click to add triggers", EditorStyles.whiteMiniLabel); else GUI.Label(triggerHelpBox, "?", EditorStyles.whiteMiniLabel); // Control IDs int triggerControlId = "tk2d.DrawClip.Triggers".GetHashCode(); int frameGroupControlId = "tk2d.DrawClip.FrameGroups".GetHashCode(); // Draw triggers DrawTriggers(triggerControlId, triggerRect, clip); // Draw frames GUILayout.BeginHorizontal(); int framesWidth = clipLeftHeaderSpace + (clip.frames.Length + 1) * frameWidth; Rect frameGroupRect = GUILayoutUtility.GetRect(framesWidth, 1, GUILayout.ExpandHeight(true)); DrawFrameGroups(frameGroupControlId, frameGroupRect, clip, frameGroups, clipTimeMarker); GUILayout.EndHorizontal(); GUILayout.EndVertical(); if (Event.current.type == EventType.ScrollWheel && (Event.current.alt || Event.current.control)) { frameWidth = Mathf.Clamp((int)(Event.current.delta.y + frameWidth), minFrameWidth, maxFrameWidth); Repaint(); } GUILayout.EndScrollView(); Rect scrollRect = GUILayoutUtility.GetLastRect(); DrawFrameGroupsOverlay(frameGroupControlId, new Rect(scrollRect.x + frameGroupRect.x, scrollRect.y + frameGroupRect.y, frameGroupRect.width, frameGroupRect.height), clip, frameGroups, clipTimeMarker); } // Internal draw void DrawAxis(tk2dSpriteAnimationClip clip, Rect r, int widthPerTick) { if (Event.current.type == EventType.Repaint) { float minWidthPerTick = 50; int ticksPerStep = (int)Mathf.Ceil(minWidthPerTick / widthPerTick); float t = 0.0f; float x = r.x; while (x < r.x + r.width) { GUI.Label(new Rect(x, r.y, r.width, r.height), t.ToString("0.00"), EditorStyles.miniLabel); x += widthPerTick * ticksPerStep; t += ticksPerStep / clip.fps; } } } void DrawFrameGroups(int controlId, Rect frameGroupRect, tk2dSpriteAnimationClip clip, List<ClipEditor.FrameGroup> frameGroups, float clipTimeMarker) { bool singleFrameMode = clip.wrapMode == tk2dSpriteAnimationClip.WrapMode.Single; // Initialize startframe in framegroups int numFrames = 0; foreach (ClipEditor.FrameGroup fg in frameGroups) { fg.startFrame = numFrames; numFrames += fg.frames.Count; } // Draw frames int currrentFrameGroup = 0; foreach (ClipEditor.FrameGroup fg in frameGroups) { Rect r = GetRectForFrameGroup(frameGroupRect, fg); DrawFrameGroupEx(r, clip, fg, /* highlighted: */ currrentFrameGroup == state.selectedFrame, /* showTime: */ currrentFrameGroup == state.selectedFrame, /* playHighlight: */ clipTimeMarker >= fg.startFrame && clipTimeMarker < fg.startFrame + fg.frames.Count); if (!singleFrameMode) EditorGUIUtility.AddCursorRect(GetResizeRectFromFrameRect(r), MouseCursor.ResizeHorizontal); currrentFrameGroup++; } // Add frame button if ((int)state.type < (int)State.Type.Action) { Rect addFrameButonRect = GetRectForFrame(frameGroupRect, clip.frames.Length, 1); addFrameButonRect = new Rect(addFrameButonRect.x + addFrameButonRect.width * 0.25f, addFrameButonRect.y + addFrameButonRect.height * 0.25f, addFrameButonRect.height * 0.5f, addFrameButonRect.height * 0.5f); if (!singleFrameMode && GUI.Button(addFrameButonRect, "+")) { frameGroups.Add(AnimOperatorUtil.NewFrameGroup(frameGroups, frameGroups.Count - 1)); ClipEditor.RecalculateFrames(clip, frameGroups); state.selectedFrame = frameGroups.Count - 1; Repaint(); } } // Draw insert marker if (GUIUtility.hotControl == controlId && state.type == State.Type.Move && state.activeFrame != -1 && state.insertMarker != -1) { Vector2 v = GetInsertMarkerPositionForFrameGroup(frameGroupRect, state.insertMarker, frameGroups); GUI.color = Color.green; GUI.Box(new Rect(v.x, v.y, 2, frameGroupRect.height), "", tk2dEditorSkin.WhiteBox); GUI.color = Color.white; } // Keyboard shortcuts Event ev = Event.current; if (ev.type == EventType.KeyDown && GUIUtility.keyboardControl == 0 && state.type == State.Type.None && state.selectedFrame != -1) { int newFrame = state.selectedFrame; switch (ev.keyCode) { case KeyCode.LeftArrow: case KeyCode.Comma: newFrame--; break; case KeyCode.RightArrow: case KeyCode.Period: newFrame++; break; case KeyCode.Home: newFrame = 0; break; case KeyCode.End: newFrame = frameGroups.Count - 1; break; case KeyCode.Escape: state.selectedFrame = -1; Repaint(); ev.Use(); break; } if (ev.type != EventType.Used && frameGroups.Count > 0) { newFrame = Mathf.Clamp(newFrame, 0, frameGroups.Count - 1); if (newFrame != state.selectedFrame) { state.selectedFrame = newFrame; Repaint(); ev.Use(); } } } if (state.selectedFrame != -1 && (GUIUtility.hotControl == controlId || (GUIUtility.keyboardControl == 0 && state.type == State.Type.None))) { if (ev.type == EventType.KeyDown && (ev.keyCode == KeyCode.Delete || ev.keyCode == KeyCode.Backspace)) { frameGroups.RemoveAt(state.selectedFrame); ClipEditor.RecalculateFrames(clip, frameGroups); GUIUtility.hotControl = 0; state.Reset(); Repaint(); ev.Use(); } } if (ev.type == EventType.MouseDown || GUIUtility.hotControl == controlId) { switch (ev.GetTypeForControl(controlId)) { case EventType.MouseDown: if (frameGroupRect.Contains(ev.mousePosition)) { int frameGroup = GetSelectedFrameGroup(frameGroupRect, ev.mousePosition, frameGroups, false); if (frameGroup != state.selectedFrame) { Repaint(); state.selectedFrame = frameGroup; } if (frameGroup != -1) { Rect r = GetRectForFrameGroup(frameGroupRect, frameGroups[frameGroup]); Rect resizeRect = GetResizeRectFromFrameRect(r); state.frameSelectionOffset = ev.mousePosition - new Vector2(r.x, 0); state.type = resizeRect.Contains(ev.mousePosition) ? State.Type.Resize : State.Type.MoveHandle; if (state.type == State.Type.Resize) { if (singleFrameMode) { state.ResetState(); // disallow resize in single frame mode } else { state.backupFrames = new List<tk2dSpriteAnimationFrame>(frameGroups[frameGroup].frames); // make a backup of frames for triggers state.activeFrame = frameGroup; state.insertMarker = state.activeFrame; } } else { state.activeFrame = frameGroup; state.insertMarker = state.activeFrame; } } GUIUtility.hotControl = controlId; } GUIUtility.keyboardControl = 0; break; case EventType.MouseDrag: { switch (state.type) { case State.Type.MoveHandle: case State.Type.Move: { state.type = State.Type.Move; state.insertMarker = GetSelectedFrameGroup(frameGroupRect, ev.mousePosition, frameGroups, true); } break; case State.Type.Resize: { int frame = GetSelectedFrame(frameGroupRect, ev.mousePosition + new Vector2(frameWidth * 0.5f, 0.0f)); ClipEditor.FrameGroup fg = frameGroups[state.activeFrame]; int frameCount = Mathf.Max(1, frame - fg.startFrame); bool changed = frameCount != fg.frames.Count; if (changed) { fg.frames = new List<tk2dSpriteAnimationFrame>(state.backupFrames); fg.SetFrameCount(frameCount); Repaint(); ClipEditor.RecalculateFrames(clip, frameGroups); } } break; } } break; case EventType.MouseUp: switch (state.type) { case State.Type.Move: { int finalInsertMarker = (state.insertMarker > state.activeFrame) ? (state.insertMarker - 1) : state.insertMarker; if (state.activeFrame != finalInsertMarker) { ClipEditor.FrameGroup tmpFrameGroup = frameGroups[state.activeFrame]; frameGroups.RemoveAt(state.activeFrame); frameGroups.Insert(finalInsertMarker, tmpFrameGroup); state.selectedFrame = finalInsertMarker; ClipEditor.RecalculateFrames(clip, frameGroups); Repaint(); } } break; } if (state.type != State.Type.None) Repaint(); state.ResetState(); GUIUtility.keyboardControl = 0; GUIUtility.hotControl = 0; break; } } if (clipTimeMarker >= 0.0f) { float x = clipLeftHeaderSpace + frameWidth * clipTimeMarker; GUI.color = Color.red; GUI.Box(new Rect(frameGroupRect.x + x, frameGroupRect.y, 2, frameGroupRect.height), "", tk2dEditorSkin.WhiteBox); GUI.color = Color.white; } } void DrawFrameGroupsOverlay(int controlId, Rect frameGroupRect, tk2dSpriteAnimationClip clip, List<ClipEditor.FrameGroup> frameGroups, float clipTimeMarker) { // Draw moving frame if active if (GUIUtility.hotControl == controlId && state.type == State.Type.Move && state.activeFrame != -1) { GUI.color = new Color(0.8f,0.8f,0.8f,0.9f); ClipEditor.FrameGroup fg = frameGroups[state.activeFrame]; DrawFrameGroup(new Rect(Event.current.mousePosition.x - state.frameSelectionOffset.x, frameGroupRect.y - frameGroupRect.height, frameWidth * fg.frames.Count, frameGroupRect.height), clip, fg); GUI.color = Color.white; Repaint(); } } void DrawTriggers(int controlId, Rect triggerRect, tk2dSpriteAnimationClip clip) { // Draw triggers GUI.color = (state.movingTrigger != -1) ? new Color(1,1,1,0.25f) : Color.white; for (int i = 0; i < clip.frames.Length; ++i) { Rect r = GetRectForTrigger(triggerRect, i); if (clip.frames[i].triggerEvent) { if (state.selectedTrigger == i) GUI.Box(r, " ", tk2dEditorSkin.Anim_TriggerSelected); else GUI.Box(r, " ", tk2dEditorSkin.Anim_Trigger); } } if (state.movingTrigger != -1) { GUI.color = Color.white; Rect r = GetRectForTrigger(triggerRect, state.movingTrigger); GUI.Box(r, " ", tk2dEditorSkin.Anim_TriggerSelected); } Event ev = Event.current; // Keyboard if (state.selectedTrigger != -1 && (GUIUtility.hotControl == controlId || GUIUtility.keyboardControl == 0) && ev.type == EventType.KeyDown) { switch (ev.keyCode) { case KeyCode.Escape: GUIUtility.hotControl = 0; state.Reset(); Repaint(); ev.Use(); break; case KeyCode.Delete: case KeyCode.Backspace: clip.frames[state.selectedTrigger].ClearTrigger(); GUIUtility.hotControl = 0; state.Reset(); Repaint(); ev.Use(); break; } } // Process trigger input if (ev.type == EventType.MouseDown || GUIUtility.hotControl == controlId) { switch (ev.GetTypeForControl(controlId)) { case EventType.MouseDown: if (triggerRect.Contains(ev.mousePosition) && ev.button == 0) { int selectedTrigger = GetSelectedTrigger(triggerRect, ev.mousePosition); int selectedTriggerRegion = GetRoundedSelectedTrigger(triggerRect, ev.mousePosition); bool startDrag = state.selectedTrigger == selectedTriggerRegion; if (ev.clickCount == 1) { if (startDrag && selectedTriggerRegion == state.selectedTrigger) { GUIUtility.hotControl = controlId; } else if (selectedTrigger >= 0 && selectedTrigger < clip.frames.Length && clip.frames[selectedTrigger].triggerEvent) { state.selectedTrigger = selectedTrigger; Repaint(); GUIUtility.hotControl = controlId; } } // Double click on an empty area if (GUIUtility.hotControl == 0 && ev.clickCount == 2 && selectedTriggerRegion >= 0 && selectedTriggerRegion < clip.frames.Length && !clip.frames[selectedTriggerRegion].triggerEvent) { clip.frames[selectedTriggerRegion].triggerEvent = true; state.selectedTrigger = selectedTriggerRegion; Repaint(); } GUIUtility.keyboardControl = 0; } break; case EventType.MouseDrag: { int selectedTrigger = Mathf.Clamp( GetRoundedSelectedTrigger(triggerRect, ev.mousePosition), 0, clip.frames.Length - 1); if (state.movingTrigger != selectedTrigger) { state.movingTrigger = selectedTrigger; Repaint(); } } break; case EventType.MouseUp: if (state.movingTrigger != -1 && state.movingTrigger != state.selectedTrigger) { tk2dSpriteAnimationFrame source = clip.frames[state.selectedTrigger]; tk2dSpriteAnimationFrame dest = clip.frames[state.movingTrigger]; dest.CopyTriggerFrom(source); source.ClearTrigger(); state.selectedTrigger = state.movingTrigger; } Repaint(); state.ResetState(); GUIUtility.hotControl = 0; break; } } } void DrawFrameGroup(Rect r, tk2dSpriteAnimationClip clip, ClipEditor.FrameGroup fg) { DrawFrameGroupEx(r, clip, fg, false, false, false); } void DrawFrameGroupEx(Rect r, tk2dSpriteAnimationClip clip, ClipEditor.FrameGroup fg, bool highlighted, bool showTime, bool playHighlight) { if (highlighted && playHighlight) GUI.color = new Color(1.0f, 0.8f, 1.0f, 1.0f); else if (playHighlight) GUI.color = new Color(1.0f, 0.8f, 0.8f, 1.0f); else if (highlighted) GUI.color = new Color(0.8f, 0.8f, 1.0f, 1.0f); tk2dSpriteCollectionData sc = fg.spriteCollection; int spriteId = fg.spriteId; string name = sc.inst.spriteDefinitions[spriteId].name; string label = name; if (showTime) { string numFrames = (fg.frames.Count == 1) ? "1 frame" : (fg.frames.Count.ToString() + " frames"); string time = (fg.frames.Count / clip.fps).ToString("0.000") + "s"; label = label + "\n" + numFrames + "\n" + time; } GUI.Label(r, label, "button"); if (highlighted || playHighlight) GUI.color = Color.white; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System.Windows.Forms; using System.ComponentModel; using Microsoft.WindowsAPICodePack.DirectX.Direct2D1; namespace D2DShapes { public partial class D2DShapesControlWithButtons : UserControl { #region NumberOfShapesToAdd [DefaultValue(1)] public int NumberOfShapesToAdd { get { return (int)numericUpDown1.Value; } set { numericUpDown1.Value = value; } } #endregion #region D2DShapesControlWithButtons() - CTOR public D2DShapesControlWithButtons() { InitializeComponent(); comboBoxRenderMode.SelectedIndex = (int)d2dShapesControl.RenderMode; } #endregion #region Initialize() public void Initialize() { d2dShapesControl.Initialize(); } #endregion #region buttonAdd~ event handlers private void buttonAddLines_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) { AddToTree(d2dShapesControl.AddLine()); } } private void buttonAddRectangles_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) AddToTree(d2dShapesControl.AddRectangle()); } private void buttonAddRoundRects_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) AddToTree(d2dShapesControl.AddRoundRect()); } private void buttonAddEllipses_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) AddToTree(d2dShapesControl.AddEllipse()); } private void buttonAddTexts_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) AddToTree(d2dShapesControl.AddText()); } private void buttonAddBitmaps_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) AddToTree(d2dShapesControl.AddBitmap()); } private void buttonAddGeometries_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) AddToTree(d2dShapesControl.AddGeometry()); } private void buttonAddMeshes_Click(object sender, System.EventArgs e) { for (int i = 0; i < (int)numericUpDown1.Value; i++) AddToTree(d2dShapesControl.AddMesh()); } private void buttonAddGDI_Click(object sender, System.EventArgs e) { AddToTree(d2dShapesControl.AddGDIEllipses((int)numericUpDown1.Value)); } private void buttonAddLayer_Click(object sender, System.EventArgs e) { AddToTree(d2dShapesControl.AddLayer((int)numericUpDown1.Value)); } #endregion #region d2dShapesControl_FpsChanged private void d2dShapesControl_FpsChanged(object sender, System.EventArgs e) { labelFPS.Text = "FPS: " + d2dShapesControl.Fps; } #endregion #region d2dShapesControl_MouseUp private void d2dShapesControl_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { DrawingShape shape = d2dShapesControl.PeelAt(new Point2F(e.Location.X, e.Location.Y)); if (shape != null) RemoveFromTree(shape, treeViewAllShapes.Nodes); } treeViewShapesAtPoint.Nodes.Clear(); treeViewShapesAtPoint.Nodes.Add(d2dShapesControl.GetTreeAt(new Point2F(e.Location.X, e.Location.Y))); treeViewShapesAtPoint.ExpandAll(); if (treeViewShapesAtPoint.Nodes.Count > 0) { TreeNode nodeToSelect = treeViewShapesAtPoint.Nodes[0]; while (nodeToSelect.Nodes.Count > 0) nodeToSelect = nodeToSelect.Nodes[0]; treeViewShapesAtPoint.SelectedNode = nodeToSelect; if (e.Button == MouseButtons.Left) { tabControl1.SelectedTab = tabPageShapes; tabControl2.SelectedTab = tabPageShapesAtPoint; treeViewShapesAtPoint.Focus(); } } } #endregion #region d2dShapesControl_StatsChanged private void d2dShapesControl_StatsChanged(object sender, System.EventArgs e) { textBoxStats.Text = "Stats:" + System.Environment.NewLine + d2dShapesControl.Stats; } #endregion #region buttonClear_Click private void buttonClear_Click(object sender, System.EventArgs e) { d2dShapesControl.ClearShapes(); treeViewAllShapes.Nodes.Clear(); } #endregion #region buttonPeelShape_Click private void buttonPeelShape_Click(object sender, System.EventArgs e) { RemoveFromTree(d2dShapesControl.PeelShape(), treeViewAllShapes.Nodes); } #endregion #region buttonUnpeel_Click private void buttonUnpeel_Click(object sender, System.EventArgs e) { DrawingShape shape = d2dShapesControl.UnpeelShape(); if (shape != null) AddToTree(shape); } #endregion #region comboBoxRenderMode_SelectedIndexChanged private void comboBoxRenderMode_SelectedIndexChanged(object sender, System.EventArgs e) { if (comboBoxRenderMode.SelectedIndex >= 0) { d2dShapesControl.RenderMode = (D2DShapesControl.RenderModes) comboBoxRenderMode.SelectedIndex; labelFPS.Visible = d2dShapesControl.RenderMode == D2DShapesControl.RenderModes.HwndRenderTarget; } } #endregion #region treeViewShapes_AfterSelect private void treeViewShapes_AfterSelect(object sender, TreeViewEventArgs e) { var tree = (TreeView)sender; if (tree.SelectedNode != null && tree.SelectedNode.Tag is DrawingShape) propertyGridShapeInfo.SelectedObject = tree.SelectedNode.Tag; } #endregion #region treeViewShapes_MouseDown private void treeViewShapes_MouseDown(object sender, MouseEventArgs e) { var tree = (TreeView)sender; TreeNode node = tree.HitTest(e.Location).Node; tree.SelectedNode = node; if (e.Button == MouseButtons.Right && node != null) { var shape = node.Tag as DrawingShape; if (shape != null) { RemoveFromTree(shape, treeViewAllShapes.Nodes); RemoveFromTree(shape, treeViewShapesAtPoint.Nodes); d2dShapesControl.PeelShape(shape); } } } #endregion #region AddToTree private void AddToTree(DrawingShape shape) { AddToTreeRecursive(shape, treeViewAllShapes.Nodes); } #endregion #region AddToTreeRecursive private static void AddToTreeRecursive(DrawingShape shape, TreeNodeCollection treeNodeCollection) { var node = new TreeNode(shape.ToString()) { Tag = shape}; node.Expand(); treeNodeCollection.Add(node); if (shape.ChildShapes != null && shape.ChildShapes.Count > 0) foreach (DrawingShape s in shape.ChildShapes) { AddToTreeRecursive(s, node.Nodes); } } #endregion #region RemoveFromTree /// <summary> /// Remove shape from the tree node collection /// </summary> /// <param name="shape"></param> /// <param name="treeNodes"></param> /// <returns>true if removed</returns> private static bool RemoveFromTree(DrawingShape shape, TreeNodeCollection treeNodes) { foreach (TreeNode node in treeNodes) { if (node.Tag == shape) { treeNodes.Remove(node); return true; } if (node.Nodes.Count > 0 && RemoveFromTree(shape, node.Nodes)) return true; } return false; } #endregion #region propertyGridShapeInfo_PropertyValueChanged() private void propertyGridShapeInfo_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { d2dShapesControl.RefreshAll(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Net.ListenerAsyncResult // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // Copyright (c) 2005 Ximian, Inc (http://www.ximian.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Runtime.ExceptionServices; using System.Threading; namespace System.Net { internal class ListenerAsyncResult : IAsyncResult { private ManualResetEvent _handle; private bool _synch; private bool _completed; private AsyncCallback _cb; private object _state; private Exception _exception; private HttpListenerContext _context; private object _locker = new object(); private ListenerAsyncResult _forward; internal bool _endCalled; internal bool _inGet; public ListenerAsyncResult(AsyncCallback cb, object state) { _cb = cb; _state = state; } internal void Complete(Exception exc) { if (_forward != null) { _forward.Complete(exc); return; } _exception = exc; if (_inGet && (exc is ObjectDisposedException)) _exception = new HttpListenerException((int)HttpStatusCode.InternalServerError, SR.net_listener_close); lock (_locker) { _completed = true; if (_handle != null) _handle.Set(); if (_cb != null) ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this); } } private static WaitCallback s_invokeCB = new WaitCallback(InvokeCallback); private static void InvokeCallback(object o) { ListenerAsyncResult ares = (ListenerAsyncResult)o; if (ares._forward != null) { InvokeCallback(ares._forward); return; } try { ares._cb(ares); } catch { } } internal void Complete(HttpListenerContext context) { Complete(context, false); } internal void Complete(HttpListenerContext context, bool synch) { if (_forward != null) { _forward.Complete(context, synch); return; } _synch = synch; _context = context; lock (_locker) { AuthenticationSchemes schemes = context._listener.SelectAuthenticationScheme(context); if ((schemes == AuthenticationSchemes.Basic || context._listener.AuthenticationSchemes == AuthenticationSchemes.Negotiate) && context.Request.Headers["Authorization"] == null) { context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; context.Response.Headers["WWW-Authenticate"] = schemes + " realm=\"" + context._listener.Realm + "\""; context.Response.OutputStream.Close(); IAsyncResult ares = context._listener.BeginGetContext(_cb, _state); _forward = (ListenerAsyncResult)ares; lock (_forward._locker) { if (_handle != null) _forward._handle = _handle; } ListenerAsyncResult next = _forward; for (int i = 0; next._forward != null; i++) { if (i > 20) Complete(new HttpListenerException((int)HttpStatusCode.Unauthorized, SR.net_listener_auth_errors)); next = next._forward; } } else { _completed = true; _synch = false; if (_handle != null) _handle.Set(); if (_cb != null) ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this); } } } internal HttpListenerContext GetContext() { if (_forward != null) { return _forward.GetContext(); } if (_exception != null) { ExceptionDispatchInfo.Capture(_exception).Throw(); } return _context; } public object AsyncState { get { if (_forward != null) return _forward.AsyncState; return _state; } } public WaitHandle AsyncWaitHandle { get { if (_forward != null) return _forward.AsyncWaitHandle; lock (_locker) { if (_handle == null) _handle = new ManualResetEvent(_completed); } return _handle; } } public bool CompletedSynchronously { get { if (_forward != null) return _forward.CompletedSynchronously; return _synch; } } public bool IsCompleted { get { if (_forward != null) return _forward.IsCompleted; lock (_locker) { return _completed; } } } } }
using System; using Mtg.Model; using Nancy; using MongoDB.Driver; using MongoDB.Bson; using MongoDB; using MongoDB.Driver.Builders; using MongoDB.Driver.Linq; using Nancy.ModelBinding; using Nancy.Json; using System.Dynamic; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; namespace Mtg { public class MongoRepository : IRepository { private string Connection { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Mtg.MongoRepository"/> class. /// </summary> /// <param name="connection">Connection.</param> public MongoRepository (string connection) { Connection = connection; } /// <summary> /// Gets the sets. /// </summary> /// <returns>The sets.</returns> /// <param name="setIds">Set identifiers.</param> public async Task<CardSet[]> GetSets (string [] setIds) { List<CardSet> cardset = new List<CardSet> (); var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); setIds = setIds.Select (x => x.ToUpper ()).ToArray(); var collection = database.GetCollection<CardSet> ("card_sets"); var query = Query.In ("_id", new BsonArray(setIds)); var sets = collection.Find (query); foreach (CardSet set in sets) { cardset.Add (set); } return cardset.ToArray (); } /// <summary> /// Gets the cards. /// </summary> /// <returns>The cards.</returns> /// <param name="multiverseIds">Multiverse identifiers.</param> public async Task<Card[]> GetCards (int [] multiverseIds) { var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); var query = Query.In ("_id", new BsonArray(multiverseIds)); var dbcards = collection.Find (query); List<Card> cards = new List<Card> (); foreach(Card c in dbcards) { cards.Add (c); } return cards.ToArray (); } /// <summary> /// Search the specified text. /// </summary> /// <param name="text">Text.</param> public async Task<Card[]> Search (string text) { var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); var query = Query<Card>.Matches (e => e.SearchName, text.ToLower().Replace(" ", "")); MongoCursor<Card> cursor = collection.Find (query); List<Card> cards = new List<Card> (); foreach (Card card in cursor) { cards.Add (card); } return cards.ToArray (); } /// <summary> /// Gets the cards. /// </summary> /// <returns>The cards.</returns> /// <param name="query">Query.</param> public async Task<Card[]> GetCards (dynamic query) { var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); MongoCursor<Card> cursor = null; List<IMongoQuery> queries = new List<IMongoQuery> (); if (query.cardsetid != null) { queries.Add (Query<Card>.EQ (e => e.CardSetId, (string)query.cardsetid)); } if (query.artist != null) { queries.Add (Query<Card>.EQ (e => e.Artist, (string)query.artist)); } if (query.rarity != null) { queries.Add (Query<Card>.EQ (e => e.Rarity, (string)query.rarity)); } if (query.loyalty != null) { queries.Add (Query<Card>.EQ (e => e.Loyalty, (int)query.loyalty)); } if (query.loyalty != null) { queries.Add (Query<Card>.EQ (e => e.Loyalty, (int)query.loyalty)); } if (query.toughness != null) { queries.Add (Query<Card>.EQ (e => e.Toughness, (int)query.toughness)); } if (query.power != null) { queries.Add (Query<Card>.EQ (e => e.Power, (int)query.power)); } if (query.subtype != null) { queries.Add (Query<Card>.EQ (e => e.SubType, (string)query.subtype)); } if (query.cardsetname != null) { queries.Add (Query<Card>.EQ (e => e.CardSetName, (string)query.cardsetname)); } if (query.convertedmanacost != null) { queries.Add (Query<Card>.EQ (e => e.ConvertedManaCost, (int)query.convertedmanacost)); } if (query.setnumber != null) { queries.Add (Query<Card>.EQ (e => e.SetNumber, (int)query.setnumber)); } if (query.manacost != null) { queries.Add (Query<Card>.EQ (e => e.ManaCost, (string)query.manacost)); } if (query.colors != null) { foreach (string color in ((string)query.colors).ToString().Split(',')) { queries.Add (Query<Card>.EQ (e => e.Colors, color)); } } if (query.name != null) { queries.Add (Query<Card>.EQ (e => e.SearchName, ((string)query.name).ToLower().Replace(" ", ""))); } if (query.type != null) { queries.Add (Query<Card>.EQ (e => e.Type, (string)query.type)); } if (query.id != null) { queries.Add (Query<Card>.EQ (e => e.Id, (int)query.id)); } if (queries.Count > 0) { cursor = collection.Find (Query.And (queries)).SetSortOrder ("_id"); } else { cursor = collection.FindAllAs<Card> ().SetSortOrder ("_id"); } if (query.limit != null) { cursor.SetLimit ((int)query.limit); } List<Card> cards = new List<Card> (); foreach (Card card in cursor) { cards.Add (card); } return cards.ToArray (); } /// <summary> /// Gets the cards by set. /// </summary> /// <returns>The cards by set.</returns> /// <param name="setId">Set identifier.</param> /// <param name="start">Start.</param> /// <param name="end">End.</param> public async Task<Card[]> GetCardsBySet (string setId, int start = 0, int end = 0) { List<Card> cards = new List<Card> (); var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); List<IMongoQuery> queries = new List<IMongoQuery> (); if (start > 0) { queries.Add (Query<Card>.GTE (c => c.SetNumber, start)); } if(end > 0) { queries.Add (Query<Card>.LTE (c => c.SetNumber, end)); } queries.Add (Query<Card>.EQ (e => e.CardSetId, (setId).ToUpper ())); //var query = Query<Card>.EQ (e => e.CardSetId, (setId).ToUpper ()); MongoCursor<Card> cursor = collection.Find (Query.And(queries)).SetSortOrder ("setNumber"); foreach (Card card in cursor) { cards.Add (card); } return cards.ToArray (); } /// <summary> /// Gets the card. /// </summary> /// <returns>The card.</returns> /// <param name="id">Identifier.</param> public async Task<Card> GetCard (int id) { var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); var query = Query<Card>.EQ (e => e.Id, id); Card card = collection.FindOne (query); return card; } /// <summary> /// Gets the cards. /// </summary> /// <returns>The cards.</returns> /// <param name="name">Name.</param> public async Task<Card[]> GetCards (string name) { var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); var query = Query<Card>.EQ (e => e.SearchName, name.ToLower().Replace(" ", "")); MongoCursor<Card> cursor = collection.Find (query); List<Card> cards = new List<Card> (); foreach (Card card in cursor) { cards.Add (card); } return cards.ToArray (); } /// <summary> /// Gets the sets. /// </summary> /// <returns>The sets.</returns> public async Task<CardSet[]> GetSets () { List<CardSet> cardset = new List<CardSet> (); var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<CardSet> ("card_sets"); MongoCursor<CardSet> cursor = collection.FindAllAs<CardSet> () .SetSortOrder ("name"); foreach (CardSet set in cursor) { cardset.Add (set); } return cardset.ToArray (); } /// <summary> /// Gets the set. /// </summary> /// <returns>The set.</returns> /// <param name="id">Identifier.</param> public async Task<CardSet> GetSet (string id) { var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<CardSet> ("card_sets"); var query = Query<CardSet>.EQ (e => e.Id, id.ToUpper ()); CardSet cardset = collection.FindOne (query); return cardset; } /// <summary> /// Updates the card fields do not use to update card Rulings. /// </summary> /// <returns>The card.</returns> /// <param name="mvid">Mvid.</param> /// <param name="field">the mongodb field name</param> /// <param name="value">Value.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public async Task<Card> UpdateCardField<T>(int mvid, string field, T value) { var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); var query = Query.EQ ("_id", mvid); var sortBy = SortBy.Descending("_id"); UpdateBuilder update = new UpdateBuilder (); update = Update .Set(field, BsonValue.Create (value)); var result = collection.FindAndModify( query, sortBy, update ); return GetCard (mvid).Result; } /// <summary> /// Updates the card rulings. This method will replace the card rulings with the new card rulings. /// Make sure all rulings are included. /// </summary> /// <returns>The card rulings.</returns> /// <param name="mvid">Mvid.</param> /// <param name="rulings">Rulings.</param> public async Task<Card> UpdateCardRulings (int mvid, Ruling[] rulings) { rulings = rulings.OrderBy (x => x.ReleasedAt).ToArray(); BsonArray newRulings = new BsonArray (); int id = 1; foreach(Ruling rule in rulings) { newRulings.Add (new BsonDocument { {"_id", id}, {"releasedAt", rule.ReleasedAt}, {"rule", rule.Rule} }); ++id; } var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); var query = Query.EQ ("_id", mvid); var sortBy = SortBy.Descending("_id"); var update = Update .Set("rulings", newRulings); var result = collection.FindAndModify( query, sortBy, update ); return GetCard (mvid).Result; } public async Task<Card> UpdateCardFormats (int mvid, Format[] formats) { formats = formats.OrderBy (x => x.Name).ToArray(); BsonArray newFormats = new BsonArray (); int id = 1; foreach(Format format in formats) { newFormats.Add (new BsonDocument { {"_id", id}, {"name", format.Name}, {"legality", format.Legality} }); ++id; } var client = new MongoClient (Connection); var server = client.GetServer (); var database = server.GetDatabase ("mtg"); var collection = database.GetCollection<Card> ("cards"); var query = Query.EQ ("_id", mvid); var sortBy = SortBy.Descending("_id"); var update = Update .Set("formats", newFormats); var result = collection.FindAndModify( query, sortBy, update ); return GetCard (mvid).Result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Net.Sockets.Tests { public class SocketOptionNameTest { private static bool SocketsReuseUnicastPortSupport { get { return Capability.SocketsReuseUnicastPortSupport(); } } private static bool NoSocketsReuseUnicastPortSupport { get { return !Capability.SocketsReuseUnicastPortSupport(); } } [ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))] public void ReuseUnicastPort_CreateSocketGetOption_NoSocketsReuseUnicastPortSupport_Throws() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort)); } [ConditionalFact(nameof(SocketsReuseUnicastPortSupport))] public void ReuseUnicastPort_CreateSocketGetOption_SocketsReuseUnicastPortSupport_OptionIsZero() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort); Assert.Equal(0, optionValue); } [ConditionalFact(nameof(NoSocketsReuseUnicastPortSupport))] public void ReuseUnicastPort_CreateSocketSetOption_NoSocketsReuseUnicastPortSupport_Throws() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Assert.Throws<SocketException>(() => socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1)); } [ConditionalFact(nameof(SocketsReuseUnicastPortSupport))] public void ReuseUnicastPort_CreateSocketSetOptionToZeroAndGetOption_SocketsReuseUnicastPortSupport_OptionIsZero() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 0); int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort); Assert.Equal(0, optionValue); } // TODO: Issue #4887 // The socket option 'ReuseUnicastPost' only works on Windows 10 systems. In addition, setting the option // is a no-op unless specialized network settings using PowerShell configuration are first applied to the // machine. This is currently difficult to test in the CI environment. So, this ests will be disabled for now [ActiveIssue(4887)] public void ReuseUnicastPort_CreateSocketSetOptionToOneAndGetOption_SocketsReuseUnicastPortSupport_OptionIsOne() { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1); int optionValue = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort); Assert.Equal(1, optionValue); } [Fact] public void MulticastOption_CreateSocketSetGetOption_GroupAndInterfaceIndex_SetSucceeds_GetThrows() { int interfaceIndex = 0; IPAddress groupIp = IPAddress.Parse("239.1.2.3"); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(groupIp, interfaceIndex)); Assert.Throws<SocketException>(() => socket.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership)); } } private static bool IsNotOSXOrFedora23() { return !PlatformDetection.IsOSX && !PlatformDetection.IsFedora23; } [ConditionalTheory(nameof(IsNotOSXOrFedora23))] // Receive times out on loopback interface [InlineData(0)] // Any [InlineData(1)] // Loopback public void MulticastInterface_Set_ValidIndex_Succeeds(int interfaceIndex) { IPAddress multicastAddress = IPAddress.Parse("239.1.2.3"); string message = "hello"; int port; using (Socket receiveSocket = CreateBoundUdpSocket(out port), sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { receiveSocket.ReceiveTimeout = 1000; receiveSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex)); sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex)); sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port)); var receiveBuffer = new byte[1024]; int bytesReceived = receiveSocket.Receive(receiveBuffer); string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived); Assert.Equal(receivedMessage, message); } } [Fact] public void MulticastInterface_Set_InvalidIndex_Throws() { int interfaceIndex = 31415; using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { Assert.Throws<SocketException>(() => s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex))); } } [Theory] [InlineData(false)] [InlineData(true)] public void FailedConnect_GetSocketOption_SocketOptionNameError(bool simpleGet) { using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { Blocking = false }) { // Fail a Connect using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { server.Bind(new IPEndPoint(IPAddress.Loopback, 0)); // bind but don't listen Assert.ThrowsAny<Exception>(() => client.Connect(server.LocalEndPoint)); } // Verify via Select that there's an error const int FailedTimeout = 10 * 1000 * 1000; // 10 seconds var errorList = new List<Socket> { client }; Socket.Select(null, null, errorList, FailedTimeout); Assert.Equal(1, errorList.Count); // Get the last error and validate it's what's expected int errorCode; if (simpleGet) { errorCode = (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error); } else { byte[] optionValue = new byte[sizeof(int)]; client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error, optionValue); errorCode = BitConverter.ToInt32(optionValue, 0); } Assert.Equal((int)SocketError.ConnectionRefused, errorCode); // Then get it again if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // The Windows implementation doesn't clear the error code after retrieved. // https://github.com/dotnet/corefx/issues/8464 Assert.Equal(errorCode, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error)); } else { // The Unix implementation matches the getsockopt and MSDN docs and clears the error code as part of retrieval. Assert.Equal((int)SocketError.Success, (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error)); } } } // Create an Udp Socket and binds it to an available port private static Socket CreateBoundUdpSocket(out int localPort) { Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // sending a message will bind the socket to an available port string sendMessage = "dummy message"; int port = 54320; IPAddress multicastAddress = IPAddress.Parse("239.1.1.1"); receiveSocket.SendTo(Encoding.UTF8.GetBytes(sendMessage), new IPEndPoint(multicastAddress, port)); localPort = (receiveSocket.LocalEndPoint as IPEndPoint).Port; return receiveSocket; } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Signum.Engine; using Signum.Entities; using Signum.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.IO; using System.Linq; using System.Linq.Expressions; namespace TestHelper; /// <summary> /// Class for turning strings into documents and getting the diagnostics on them /// All methods are static /// </summary> public abstract partial class DiagnosticVerifier { private static readonly MetadataReference CorlibReference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); private static readonly MetadataReference SystemCoreReference = MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location); private static readonly MetadataReference CSharpSymbolsReference = MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location); private static readonly MetadataReference CodeAnalysisReference = MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location); private static readonly MetadataReference SystemLinqExpression = MetadataReference.CreateFromFile(typeof(Expression).Assembly.Location); private static readonly MetadataReference SystemPrivateCorLib = MetadataReference.CreateFromFile(typeof(Func<>).Assembly.Location); private static readonly MetadataReference SystemRuntimeReference = MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(Func<>).Assembly.Location), "System.Runtime.dll")); private static readonly MetadataReference SystemRuntime = MetadataReference.CreateFromFile(typeof(DateTime).Assembly.Location); private static readonly MetadataReference SystemObjectModel = MetadataReference.CreateFromFile(typeof(INotifyPropertyChanged).Assembly.Location); private static readonly MetadataReference SystemComponentModelTypeConverter = MetadataReference.CreateFromFile(typeof(IDataErrorInfo).Assembly.Location); private static readonly MetadataReference SignumUtilitiesReference = MetadataReference.CreateFromFile(typeof(Csv).Assembly.Location); private static readonly MetadataReference SignumEntitiesReference = MetadataReference.CreateFromFile(typeof(Entity).Assembly.Location); private static readonly MetadataReference SignumEngineReference = MetadataReference.CreateFromFile(typeof(Database).Assembly.Location); internal static string DefaultFilePathPrefix = "Test"; internal static string CSharpDefaultFileExt = "cs"; internal static string VisualBasicDefaultExt = "vb"; internal static string TestProjectName = "TestProject"; #region Get Diagnostics /// <summary> /// Given classes in the form of strings, their language, and an IDiagnosticAnalyzer to apply to it, return the diagnostics found in the string after converting it to a document. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source classes are in</param> /// <param name="analyzer">The analyzer to be run on the sources</param> /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns> private static Diagnostic[] GetSortedDiagnostics(string[] sources, string language, bool assertErrors, DiagnosticAnalyzer analyzer) { var docs = GetDocuments(sources, language); return GetSortedDiagnosticsFromDocuments(analyzer, assertErrors, docs); } /// <summary> /// Given an analyzer and a document to apply it to, run the analyzer and gather an array of diagnostics found in it. /// The returned diagnostics are then ordered by location in the source document. /// </summary> /// <param name="analyzer">The analyzer to run on the documents</param> /// <param name="documents">The Documents that the analyzer will be run on</param> /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns> protected static Diagnostic[] GetSortedDiagnosticsFromDocuments(DiagnosticAnalyzer analyzer, bool assertErrors, Document[] documents) { var projects = new HashSet<Project>(); foreach (var document in documents) { projects.Add(document.Project); } var diagnostics = new List<Diagnostic>(); foreach (var project in projects) { var compilation = project.GetCompilationAsync().Result; if (assertErrors) { var errors = compilation.GetDiagnostics(); if (errors.Any(a => a.Severity == DiagnosticSeverity.Error)) throw new InvalidOperationException("Errors found:\n" + errors.Where(a => a.Severity == DiagnosticSeverity.Error).ToString("\n").Indent(2)); } var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzer)); var diags = compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result; foreach (var diag in diags) { if (diag.Location == Location.None || diag.Location.IsInMetadata) { diagnostics.Add(diag); } else { for (int i = 0; i < documents.Length; i++) { var document = documents[i]; var tree = document.GetSyntaxTreeAsync().Result; if (tree == diag.Location.SourceTree) { diagnostics.Add(diag); } } } } } var results = SortDiagnostics(diagnostics); diagnostics.Clear(); return results; } /// <summary> /// Sort diagnostics by location in source document /// </summary> /// <param name="diagnostics">The list of Diagnostics to be sorted</param> /// <returns>An IEnumerable containing the Diagnostics in order of Location</returns> private static Diagnostic[] SortDiagnostics(IEnumerable<Diagnostic> diagnostics) { return diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); } #endregion #region Set up compilation and documents /// <summary> /// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of it. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant</returns> private static Document[] GetDocuments(string[] sources, string language) { if (language != LanguageNames.CSharp) { throw new ArgumentException("Unsupported Language"); } var project = CreateProject(sources, language); var documents = project.Documents.ToArray(); if (sources.Length != documents.Length) { throw new InvalidOperationException("Amount of sources did not match amount of Documents created"); } return documents; } /// <summary> /// Create a Document from a string through creating a project that contains it. /// </summary> /// <param name="source">Classes in the form of a string</param> /// <param name="language">The language the source code is in</param> /// <returns>A Document created from the source string</returns> protected static Document CreateDocument(string source, string language = LanguageNames.CSharp) { return CreateProject(new[] { source }, language).Documents.First(); } /// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var solution = new AdhocWorkspace() .CurrentSolution .AddProject( projectId, TestProjectName, TestProjectName, language) .WithProjectParseOptions(projectId, new CSharpParseOptions(LanguageVersion.CSharp9)) .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable)) .AddMetadataReference(projectId, CorlibReference) .AddMetadataReference(projectId, SystemCoreReference) .AddMetadataReference(projectId, CSharpSymbolsReference) .AddMetadataReference(projectId, CodeAnalysisReference) .AddMetadataReference(projectId, SystemPrivateCorLib) .AddMetadataReference(projectId, SystemRuntimeReference) .AddMetadataReference(projectId, SystemLinqExpression) .AddMetadataReference(projectId, SystemRuntime) .AddMetadataReference(projectId, SystemObjectModel) .AddMetadataReference(projectId, SystemComponentModelTypeConverter) .AddMetadataReference(projectId, SignumUtilitiesReference) .AddMetadataReference(projectId, SignumEntitiesReference) .AddMetadataReference(projectId, SignumEngineReference); int count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return solution.GetProject(projectId); } #endregion }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using Tharga.Toolkit.Console.Entities; using Tharga.Toolkit.Console.Interfaces; namespace Tharga.Toolkit.Console.Commands.Base { public abstract class QueryParamBase { protected abstract IInputManager InputManager { get; } protected abstract CancellationToken CancellationToken { get; } protected abstract string GetNextParam(IEnumerable<string> param); public string QueryPassword(string paramName, IEnumerable<string> autoParam, string defaultValue = null) { return QueryPassword(paramName, GetNextParam(autoParam), defaultValue); } public string QueryPassword(string paramName, string autoProvideValue = null, string defaultValue = null) { return QueryParam<string>(paramName, autoProvideValue, defaultValue, true); } public T QueryParam<T>(string paramName) { var selection = GenerateSelection<T>(); return QueryParam<T>(paramName, null, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<string> autoParam) { var selection = GenerateSelection<T>(); var autoProvideValue = GetNextParam(autoParam); return QueryParam<T>(paramName, autoProvideValue, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<string> autoParam, IDictionary<T, string> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)); var autoProvideValue = GetNextParam(autoParam); return QueryParam(paramName, autoProvideValue, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<string> autoParam, IEnumerable<KeyValuePair<T,string>> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)); var autoProvideValue = GetNextParam(autoParam); return QueryParam(paramName, autoProvideValue, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<string> autoParam, IEnumerable<(T, string)> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Item1, x.Item2)); var autoProvideValue = GetNextParam(autoParam); return QueryParam(paramName, autoProvideValue, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<string> autoParam, IEnumerable<Tuple<T, string>> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Item1, x.Item2)); var autoProvideValue = GetNextParam(autoParam); return QueryParam(paramName, autoProvideValue, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<string> autoParam, IEnumerable<T> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x, x.ToString())); var autoProvideValue = GetNextParam(autoParam); return QueryParam(paramName, autoProvideValue, selection, true, false); } public T QueryParam<T>(string paramName, IDictionary<T, string> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)); return QueryParam(paramName, null, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<KeyValuePair<T, string>> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)); return QueryParam(paramName, null, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<(T, string)> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Item1, x.Item2)); return QueryParam(paramName, null, selection, true, false); } public T QueryParam<T>(string paramName, IEnumerable<Tuple<T, string>> options) { var selection = options?.Select(x => new CommandTreeNode<T>(x.Item1, x.Item2)); return QueryParam(paramName, null, selection, true, false); } protected T QueryParam<T>(string paramName, string autoProvideValue = null, string defaultValue = null) { return QueryParam<T>(paramName, autoProvideValue, defaultValue, false); } private T QueryParam<T>(string paramName, string autoProvideValue, string defaultValue, bool passwordEntry) { try { string value; if (!string.IsNullOrEmpty(autoProvideValue)) { value = autoProvideValue; } else { if (!string.IsNullOrEmpty(defaultValue)) { //value = QueryParam(paramName, (string)null, new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(defaultValue, defaultValue) }, false); var p1 = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(defaultValue, defaultValue) }; var p2 = p1?.Select(x => new CommandTreeNode<string>(x.Key, x.Value)); value = QueryParam(paramName, (string)null, p2, true, passwordEntry); } else { //value = QueryParam(paramName, (string)null, (List<KeyValuePair<string, string>>)null); value = QueryParam(paramName, (string)null, (IEnumerable<CommandTreeNode<string>>)null, true, passwordEntry); } } var response = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value); return response; } catch (Exception exception) { if (exception.InnerException?.GetType() == typeof(FormatException)) { throw exception.InnerException; } throw; } } //public T QueryParam<T>(string paramName, IEnumerable<string> autoParam, (T, string)[] options) //{ // var selection = options?.Select(x => new CommandTreeNode<T>(x.Item1, x.Item2)); // var autoProvideValue = GetNextParam(autoParam); // return QueryParam(paramName, autoProvideValue, selection, true, false); //} //protected T QueryParam<T>(string paramName, IEnumerable<string> autoParam, IDictionary<T, string> selectionDelegate) //{ // return QueryParam(paramName, GetNextParam(autoParam), selectionDelegate?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)), true, false); //} //protected T QueryParam<T>(string paramName, string autoProvideValue, IDictionary<T, string> selectionDelegate) //{ // return QueryParam(paramName, autoProvideValue, selectionDelegate?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)), true, false); //} //protected T QueryParam<T>(string paramName, IEnumerable<string> autoParam, IEnumerable<KeyValuePair<T, string>> selectionDelegate, bool passwordEntry = false) //{ // return QueryParam<T>(paramName, GetNextParam(autoParam), selectionDelegate?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)), true, passwordEntry); //} //private T QueryParam<T>(string paramName, string autoProvideValue, IEnumerable<KeyValuePair<T, string>> selectionDelegate, bool passwordEntry = false) //{ // return QueryParam(paramName, autoProvideValue, selectionDelegate?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)), true, passwordEntry); //} protected internal T QueryParam<T>(string paramName, string autoProvideValue, IEnumerable<CommandTreeNode<T>> selection, bool allowEscape, bool passwordEntry) { var sel = new CommandTreeNode<T>(selection?.ToArray() ?? new CommandTreeNode<T>[] { }); var q = GetParamByString(autoProvideValue, sel); if (q != null) { return q.Key; } var prompt = paramName + ((!sel.Subs.Any() || paramName == Constants.Prompt) ? string.Empty : " [Tab]"); var response = InputManager.ReadLine(prompt, sel, allowEscape, CancellationToken, passwordEntry ? '*' : (char?)null, null); return response; } private static IEnumerable<CommandTreeNode<T>> GenerateSelection<T>() { var selection = Param.AsOption<T>().ToArray(); return selection?.Select(x => new CommandTreeNode<T>(x.Key, x.Value)); } private static CommandTreeNode<T> GetParamByString<T>(string autoProvideValue, CommandTreeNode<T> selection) { if (!string.IsNullOrEmpty(autoProvideValue)) { var item = selection.Subs.SingleOrDefault(x => string.Compare(x.Value, autoProvideValue, StringComparison.InvariantCultureIgnoreCase) == 0); if (string.Equals(item?.Value, autoProvideValue, StringComparison.CurrentCultureIgnoreCase)) { return item; } item = selection.Subs.SingleOrDefault(x => string.Compare(x.Key.ToString(), autoProvideValue, StringComparison.InvariantCultureIgnoreCase) == 0); if (item != null) { if (item.Key != null && item.Key.ToString() == autoProvideValue) { return item; } } try { var r = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(autoProvideValue); return new CommandTreeNode<T>(r, autoProvideValue); } catch (FormatException exception) { throw new InvalidOperationException("Cannot find provided value in selection.", exception); } } return null; } } }
// Copyright (c) 2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) #if __MonoCS__ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using X11.XKlavier; using SIL.Reporting; using SIL.Keyboarding; using SIL.PlatformUtilities; namespace SIL.Windows.Forms.Keyboarding.Linux { /// <summary> /// Class for handling xkb keyboards on Linux /// </summary> public class XkbKeyboardRetrievingAdaptor : IKeyboardRetrievingAdaptor { private IXklEngine _engine; private static HashSet<string> _knownCultures; public XkbKeyboardRetrievingAdaptor(): this(new XklEngine()) { } /// <summary> /// Initializes a new instance of the <see cref="SIL.Windows.Forms.Keyboarding.Linux.XkbKeyboardRetrievingAdaptor"/> class. /// This overload is used in unit tests. /// </summary> public XkbKeyboardRetrievingAdaptor(IXklEngine engine) { _engine = engine; } private static string GetDescription(XklConfigRegistry.LayoutDescription layout) { return string.Format("{0} - {1} ({2})", layout.Description, layout.Language, layout.Country); } protected virtual void InitLocales() { var configRegistry = XklConfigRegistry.Create(_engine); Dictionary<string, List<XklConfigRegistry.LayoutDescription>> layouts = configRegistry.Layouts; Dictionary<string, XkbKeyboardDescription> curKeyboards = KeyboardController.Instance.Keyboards.OfType<XkbKeyboardDescription>().ToDictionary(kd => kd.Id); for (uint iGroup = 0; iGroup < _engine.GroupNames.Length; iGroup++) { // a group in a xkb keyboard is a keyboard layout. This can be used with // multiple languages - which language is ambigious. Here we just add all // of them. // m_engine.GroupNames are not localized, but the layouts are. Before we try // to compare them we better localize the group name as well, or we won't find // much (FWNX-1388) string groupName = _engine.LocalizedGroupNames[iGroup]; List<XklConfigRegistry.LayoutDescription> layoutList; if (!layouts.TryGetValue(groupName, out layoutList)) { // No language in layouts uses the groupName keyboard layout. Console.WriteLine("WARNING: Couldn't find layout for {0}.", groupName); Logger.WriteEvent("WARNING: Couldn't find layout for {0}.", groupName); continue; } for (int iLayout = 0; iLayout < layoutList.Count; iLayout++) { XklConfigRegistry.LayoutDescription layout = layoutList[iLayout]; AddKeyboardForLayout(curKeyboards, layout, iGroup, SwitchingAdaptor); } } foreach (XkbKeyboardDescription existingKeyboard in curKeyboards.Values) existingKeyboard.SetIsAvailable(false); } internal static void AddKeyboardForLayout(IDictionary<string, XkbKeyboardDescription> curKeyboards, XklConfigRegistry.LayoutDescription layout, uint iGroup, IKeyboardSwitchingAdaptor engine) { string description = GetDescription(layout); CultureInfo culture = null; try { culture = new CultureInfo(layout.LocaleId); } catch (ArgumentException) { // This can happen if the locale is not supported. // TODO: fix mono's list of supported locales. Doesn't support e.g. de-BE. // See mono/tools/locale-builder. } string id = string.Format("{0}_{1}", layout.LocaleId, layout.LayoutId); var inputLanguage = new InputLanguageWrapper(culture, IntPtr.Zero, layout.Language); XkbKeyboardDescription existingKeyboard; if (curKeyboards.TryGetValue(id, out existingKeyboard)) { if (!existingKeyboard.IsAvailable) { existingKeyboard.SetIsAvailable(true); existingKeyboard.SetName(description); existingKeyboard.SetInputLanguage(inputLanguage); existingKeyboard.GroupIndex = (int) iGroup; } curKeyboards.Remove(id); } else { var keyboard = new XkbKeyboardDescription(id, description, layout.LayoutId, layout.LocaleId, true, inputLanguage, engine, (int) iGroup); KeyboardController.Instance.Keyboards.Add(keyboard); } } public IXklEngine XklEngine { get { return _engine; } } /// <summary> /// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...) /// </summary> public KeyboardAdaptorType Type { get { return KeyboardAdaptorType.System; } } public virtual bool IsApplicable { get { return true; } } /// <summary> /// Gets the keyboard adaptor that deals with keyboards that this class retrieves. /// </summary> public IKeyboardSwitchingAdaptor SwitchingAdaptor { get; protected set; } public virtual void Initialize() { SwitchingAdaptor = new XkbKeyboardSwitchingAdaptor(_engine); InitLocales(); } public void UpdateAvailableKeyboards() { InitLocales(); } /// <summary> /// Creates and returns a keyboard definition object based on the layout and locale. /// Note that this method is used when we do NOT have a matching available keyboard. /// Therefore we can presume that the created one is NOT available. /// </summary> public KeyboardDescription CreateKeyboardDefinition(string id) { return CreateKeyboardDefinition(id, SwitchingAdaptor); } internal static XkbKeyboardDescription CreateKeyboardDefinition(string id, IKeyboardSwitchingAdaptor engine) { string[] parts = id.Split('_'); string locale = parts[0]; string layout = parts.Length > 1 ? parts[1] : string.Empty; string realLocale = locale; if (locale == "zh") { realLocale = "zh-CN"; // Mono doesn't support bare "zh" until version 3 sometime } else if (locale == "x040F") { realLocale = "is"; // 0x040F is the numeric code for Icelandic. } // Don't crash if the locale is unknown to the system. (It may be that ibus is not running and // this particular locale and layout refer to an ibus keyboard.) Mark the keyboard description // as missing, but create an English (US) keyboard underneath. if (IsLocaleKnown(realLocale)) return new XkbKeyboardDescription(id, string.Format("{0} ({1})", locale, layout), layout, locale, false, new InputLanguageWrapper(realLocale, IntPtr.Zero, layout), engine, -1); string missingKeyboardFmt = L10NSharp.LocalizationManager.GetString("XkbKeyboardAdaptor.MissingKeyboard", "[Missing] {0} ({1})"); return new XkbKeyboardDescription(id, String.Format(missingKeyboardFmt, locale, layout), layout, locale, false, new InputLanguageWrapper("en", IntPtr.Zero, "US"), engine, -1); } /// <summary> /// Check whether the locale is known to the system. /// </summary> private static bool IsLocaleKnown(string locale) { if (_knownCultures == null) { _knownCultures = new HashSet<string>(); foreach (var ci in CultureInfo.GetCultures(CultureTypes.AllCultures)) _knownCultures.Add(ci.Name); } return _knownCultures.Contains(locale); } public bool CanHandleFormat(KeyboardFormat format) { return format == KeyboardFormat.Unknown; } public virtual string GetKeyboardSetupApplication(out string arguments) { // NOTE: if we get false results (e.g. because the user has installed multiple // desktop environments) we could check for the currently running desktop // (Platform.DesktopEnvironment) and return the matching program arguments = null; // XFCE if (File.Exists("/usr/bin/xfce4-keyboard-settings")) return "/usr/bin/xfce4-keyboard-settings"; // Cinnamon if (File.Exists("/usr/lib/cinnamon-settings/cinnamon-settings.py") && File.Exists("/usr/bin/python")) { arguments = "/usr/lib/cinnamon-settings/cinnamon-settings.py " + (Platform.DesktopEnvironment == "cinnamon" ? "region layouts" // Wasta 12 : "keyboard"); // Wasta 14; return "/usr/bin/python"; } // GNOME if (File.Exists("/usr/bin/gnome-control-center")) { arguments = "region layouts"; return "/usr/bin/gnome-control-center"; } // KDE if (File.Exists("/usr/bin/kcmshell4")) { arguments = "kcm_keyboard"; return "/usr/bin/kcmshell4"; } return null; } public bool IsSecondaryKeyboardSetupApplication { get { return false; } } #region IDisposable & Co. implementation // Region last reviewed: never /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } /// <summary> /// See if the object has been disposed. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Finalizer, in case client doesn't dispose it. /// Force Dispose(false) if not already called (i.e. m_isDisposed is true) /// </summary> /// <remarks> /// In case some clients forget to dispose it directly. /// </remarks> ~XkbKeyboardRetrievingAdaptor() { Dispose(false); // The base class finalizer is called automatically. } /// <summary> /// /// </summary> /// <remarks>Must not be virtual.</remarks> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected virtual void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (IsDisposed) return; if (disposing) { // Dispose managed resources here. if (_engine != null) { _engine.Close(); _engine = null; } } // Dispose unmanaged resources here, whether disposing is true or false. IsDisposed = true; } #endregion IDisposable & Co. implementation } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; using Windows.Web.Http.Headers; using RTHttpMethod = Windows.Web.Http.HttpMethod; using RTHttpRequestMessage = Windows.Web.Http.HttpRequestMessage; using RTHttpResponseMessage = Windows.Web.Http.HttpResponseMessage; using RTHttpBufferContent = Windows.Web.Http.HttpBufferContent; using RTHttpStreamContent = Windows.Web.Http.HttpStreamContent; using RTHttpVersion = Windows.Web.Http.HttpVersion; using RTIHttpContent = Windows.Web.Http.IHttpContent; using RTIInputStream = Windows.Storage.Streams.IInputStream; using RTHttpBaseProtocolFilter = Windows.Web.Http.Filters.HttpBaseProtocolFilter; using RTChainValidationResult = Windows.Security.Cryptography.Certificates.ChainValidationResult; namespace System.Net.Http { internal class HttpHandlerToFilter : HttpMessageHandler { // We need two different WinRT filters because we need to remove credentials during redirection requests // and WinRT doesn't allow changing the filter properties after the first request. private readonly RTHttpBaseProtocolFilter _filter; private Lazy<RTHttpBaseProtocolFilter> _filterWithNoCredentials; private RTHttpBaseProtocolFilter FilterWithNoCredentials => _filterWithNoCredentials.Value; private int _filterMaxVersionSet; private HttpClientHandler _handler; internal HttpHandlerToFilter( RTHttpBaseProtocolFilter filter, HttpClientHandler handler) { if (filter == null) { throw new ArgumentNullException(nameof(filter)); } _filter = filter; _filterMaxVersionSet = 0; _handler = handler; _filterWithNoCredentials = new Lazy<RTHttpBaseProtocolFilter>(InitFilterWithNoCredentials); } internal string RequestMessageLookupKey { get; set; } internal string SavedExceptionDispatchInfoLookupKey { get; set; } protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel) { int redirects = 0; HttpMethod requestHttpMethod; bool skipRequestContentIfPresent = false; HttpResponseMessage response = null; if (request == null) { throw new ArgumentNullException(nameof(request)); } requestHttpMethod = request.Method; while (true) { cancel.ThrowIfCancellationRequested(); if (response != null) { response.Dispose(); response = null; } RTHttpRequestMessage rtRequest = await ConvertRequestAsync( request, requestHttpMethod, skipRequestContentIfPresent).ConfigureAwait(false); RTHttpResponseMessage rtResponse; try { rtResponse = await (redirects > 0 ? FilterWithNoCredentials : _filter).SendRequestAsync(rtRequest).AsTask(cancel).ConfigureAwait(false); } catch (TaskCanceledException) { throw; } catch { if (rtRequest.Properties.TryGetValue(SavedExceptionDispatchInfoLookupKey, out object info)) { ((ExceptionDispatchInfo)info).Throw(); } throw; } response = ConvertResponse(rtResponse); ProcessResponseCookies(response, request.RequestUri); if (!_handler.AllowAutoRedirect) { break; } if (response.StatusCode != HttpStatusCode.MultipleChoices && response.StatusCode != HttpStatusCode.MovedPermanently && response.StatusCode != HttpStatusCode.Redirect && response.StatusCode != HttpStatusCode.RedirectMethod && response.StatusCode != HttpStatusCode.RedirectKeepVerb && response.StatusCode != HttpStatusCode.PermanentRedirect) { break; } redirects++; if (redirects > _handler.MaxAutomaticRedirections) { break; } Uri redirectUri = response.Headers.Location; if (redirectUri == null) { break; } if (!redirectUri.IsAbsoluteUri) { redirectUri = new Uri(request.RequestUri, redirectUri.OriginalString); } if (redirectUri.Scheme != Uri.UriSchemeHttp && redirectUri.Scheme != Uri.UriSchemeHttps) { break; } if (request.RequestUri.Scheme == Uri.UriSchemeHttps && redirectUri.Scheme == Uri.UriSchemeHttp) { break; } // Follow HTTP RFC 7231 rules. In general, 3xx responses // except for 307 and 308 will keep verb except POST becomes GET. // 307 and 308 responses have all verbs stay the same. // https://tools.ietf.org/html/rfc7231#section-6.4 if (response.StatusCode != HttpStatusCode.RedirectKeepVerb && response.StatusCode != HttpStatusCode.PermanentRedirect && requestHttpMethod == HttpMethod.Post) { requestHttpMethod = HttpMethod.Get; skipRequestContentIfPresent = true; } request.RequestUri = redirectUri; } response.RequestMessage = request; return response; } private RTHttpBaseProtocolFilter InitFilterWithNoCredentials() { RTHttpBaseProtocolFilter filter = new RTHttpBaseProtocolFilter(); filter.AllowAutoRedirect = _filter.AllowAutoRedirect; filter.AllowUI = _filter.AllowUI; filter.AutomaticDecompression = _filter.AutomaticDecompression; filter.CacheControl.ReadBehavior = _filter.CacheControl.ReadBehavior; filter.CacheControl.WriteBehavior = _filter.CacheControl.WriteBehavior; if (HttpClientHandler.RTCookieUsageBehaviorSupported) { filter.CookieUsageBehavior = _filter.CookieUsageBehavior; } filter.MaxConnectionsPerServer = _filter.MaxConnectionsPerServer; filter.MaxVersion = _filter.MaxVersion; filter.UseProxy = _filter.UseProxy; if (_handler.ServerCertificateCustomValidationCallback != null) { foreach (RTChainValidationResult error in _filter.IgnorableServerCertificateErrors) { filter.IgnorableServerCertificateErrors.Add(error); } filter.ServerCustomValidationRequested += _handler.RTServerCertificateCallback; } return filter; } // Taken from System.Net.CookieModule.OnReceivedHeaders private void ProcessResponseCookies(HttpResponseMessage response, Uri uri) { if (_handler.UseCookies) { IEnumerable<string> values; if (response.Headers.TryGetValues(HttpKnownHeaderNames.SetCookie, out values)) { foreach (string cookieString in values) { if (!string.IsNullOrWhiteSpace(cookieString)) { try { // Parse the cookies so that we can filter some of them out CookieContainer helper = new CookieContainer(); helper.SetCookies(uri, cookieString); CookieCollection cookies = helper.GetCookies(uri); foreach (Cookie cookie in cookies) { // We don't want to put HttpOnly cookies in the CookieContainer if the system // doesn't support the RTHttpBaseProtocolFilter CookieUsageBehavior property. // Prior to supporting that, the WinRT HttpClient could not turn off cookie // processing. So, it would always be storing all cookies in its internal container. // Putting HttpOnly cookies in the .NET CookieContainer would cause problems later // when the .NET layer tried to add them on outgoing requests and conflicted with // the WinRT internal cookie processing. // // With support for WinRT CookieUsageBehavior, cookie processing is turned off // within the WinRT layer. This allows us to process cookies using only the .NET // layer. So, we need to add all applicable cookies that are received to the // CookieContainer. if (HttpClientHandler.RTCookieUsageBehaviorSupported || !cookie.HttpOnly) { _handler.CookieContainer.Add(uri, cookie); } } } catch (Exception) { } } } } } } private async Task<RTHttpRequestMessage> ConvertRequestAsync( HttpRequestMessage request, HttpMethod httpMethod, bool skipRequestContentIfPresent) { RTHttpRequestMessage rtRequest = new RTHttpRequestMessage( new RTHttpMethod(httpMethod.Method), request.RequestUri); // Add a reference from the WinRT object back to the .NET object. rtRequest.Properties.Add(RequestMessageLookupKey, request); // We can only control the Version on the first request message since the WinRT API // has this property designed as a filter/handler property. In addition the overall design // of HTTP/2.0 is such that once the first request is using it, all the other requests // to the same endpoint will use it as well. if (Interlocked.Exchange(ref _filterMaxVersionSet, 1) == 0) { RTHttpVersion maxVersion; if (request.Version == HttpVersion.Version20) { maxVersion = RTHttpVersion.Http20; } else if (request.Version == HttpVersion.Version11) { maxVersion = RTHttpVersion.Http11; } else if (request.Version == HttpVersion.Version10) { maxVersion = RTHttpVersion.Http10; } else { maxVersion = RTHttpVersion.Http11; } // The default for WinRT HttpBaseProtocolFilter.MaxVersion is HttpVersion.Http20. // So, we only have to change it if we don't want HTTP/2.0. if (maxVersion != RTHttpVersion.Http20) { _filter.MaxVersion = maxVersion; } } // Headers foreach (KeyValuePair<string, IEnumerable<string>> headerPair in request.Headers) { foreach (string value in headerPair.Value) { bool success = rtRequest.Headers.TryAppendWithoutValidation(headerPair.Key, value); Debug.Assert(success); } } // Cookies if (_handler.UseCookies) { string cookieHeader = _handler.CookieContainer.GetCookieHeader(request.RequestUri); if (!string.IsNullOrWhiteSpace(cookieHeader)) { bool success = rtRequest.Headers.TryAppendWithoutValidation(HttpKnownHeaderNames.Cookie, cookieHeader); Debug.Assert(success); } } // Properties foreach (KeyValuePair<string, object> propertyPair in request.Properties) { rtRequest.Properties.Add(propertyPair.Key, propertyPair.Value); } // Content if (!skipRequestContentIfPresent && request.Content != null) { rtRequest.Content = await CreateRequestContentAsync(request, rtRequest.Headers).ConfigureAwait(false); } return rtRequest; } private static async Task<RTIHttpContent> CreateRequestContentAsync(HttpRequestMessage request, HttpRequestHeaderCollection rtHeaderCollection) { HttpContent content = request.Content; RTIHttpContent rtContent; ArraySegment<byte> buffer; // If we are buffered already, it is more efficient to send the data directly using the buffer with the // WinRT HttpBufferContent class than using HttpStreamContent. This also avoids issues caused by // a design limitation in the System.Runtime.WindowsRuntime System.IO.NetFxToWinRtStreamAdapter. if (content.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false); if (contentStream is RTIInputStream) { rtContent = new RTHttpStreamContent((RTIInputStream)contentStream); } else if (contentStream is MemoryStream) { var memStream = contentStream as MemoryStream; if (memStream.TryGetBuffer(out buffer)) { rtContent = new RTHttpBufferContent(buffer.Array.AsBuffer(), (uint)buffer.Offset, (uint)buffer.Count); } else { byte[] byteArray = memStream.ToArray(); rtContent = new RTHttpBufferContent(byteArray.AsBuffer(), 0, (uint) byteArray.Length); } } else { rtContent = new RTHttpStreamContent(contentStream.AsInputStream()); } } // RTHttpBufferContent constructor automatically adds a Content-Length header. RTHttpStreamContent does not. // Clear any 'Content-Length' header added by the RTHttp*Content objects. We need to clear that now // and decide later whether we need 'Content-Length' or 'Transfer-Encoding: chunked' headers based on the // .NET HttpRequestMessage and Content header collections. rtContent.Headers.ContentLength = null; // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // Desktop System.Net allows both headers to be specified but ends up stripping out // 'Content-Length' and using chunked semantics. The WinRT APIs throw an exception so // we need to manually strip out the conflicting header to maintain app compatibility. if (request.Headers.TransferEncodingChunked.HasValue && request.Headers.TransferEncodingChunked.Value) { content.Headers.ContentLength = null; } else { // Trigger delayed header generation via TryComputeLength. This code is needed due to an outstanding // bug in HttpContentHeaders.ContentLength. See GitHub Issue #5523. content.Headers.ContentLength = content.Headers.ContentLength; } foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers) { foreach (string value in headerPair.Value) { if (!rtContent.Headers.TryAppendWithoutValidation(headerPair.Key, value)) { // rtContent headers are restricted to a white-list of allowed headers, while System.Net.HttpClient's content headers // will allow custom headers. If something is not successfully added to the content headers, try adding them to the standard headers. bool success = rtHeaderCollection.TryAppendWithoutValidation(headerPair.Key, value); Debug.Assert(success); } } } return rtContent; } private static HttpResponseMessage ConvertResponse(RTHttpResponseMessage rtResponse) { HttpResponseMessage response = new HttpResponseMessage((HttpStatusCode)rtResponse.StatusCode); response.ReasonPhrase = rtResponse.ReasonPhrase; // Version if (rtResponse.Version == RTHttpVersion.Http11) { response.Version = HttpVersion.Version11; } else if (rtResponse.Version == RTHttpVersion.Http10) { response.Version = HttpVersion.Version10; } else if (rtResponse.Version == RTHttpVersion.Http20) { response.Version = HttpVersion.Version20; } else { response.Version = new Version(0,0); } bool success; // Headers foreach (KeyValuePair<string, string> headerPair in rtResponse.Headers) { if (headerPair.Key.Equals(HttpKnownHeaderNames.SetCookie, StringComparison.OrdinalIgnoreCase)) { // The Set-Cookie header always comes back with all of the cookies concatenated together. // For example if the response contains the following: // Set-Cookie A=1 // Set-Cookie B=2 // Then we will have a single header KeyValuePair of Key=Set-Cookie, Value=A=1, B=2. // However clients expect these headers to be separated(i.e. // httpResponseMessage.Headers.GetValues("Set-Cookie") should return two cookies not one // concatenated together). success = response.Headers.TryAddWithoutValidation(headerPair.Key, CookieHelper.GetCookiesFromHeader(headerPair.Value)); } else { success = response.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value); } Debug.Assert(success); } // Content if (rtResponse.Content != null) { var rtResponseStream = rtResponse.Content.ReadAsInputStreamAsync().AsTask().Result; response.Content = new StreamContent(rtResponseStream.AsStreamForRead()); foreach (KeyValuePair<string, string> headerPair in rtResponse.Content.Headers) { success = response.Content.Headers.TryAddWithoutValidation(headerPair.Key, headerPair.Value); Debug.Assert(success); } } return response; } } }
// 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.Generic; using System.Runtime; using System.ServiceModel; using System.Threading; namespace System.ServiceModel.Dispatcher { internal class ConcurrencyBehavior { private ConcurrencyMode _concurrencyMode; private bool _enforceOrderedReceive; internal ConcurrencyBehavior(DispatchRuntime runtime) { _concurrencyMode = runtime.ConcurrencyMode; _enforceOrderedReceive = runtime.EnsureOrderedDispatch; } internal bool IsConcurrent(ref MessageRpc rpc) { return IsConcurrent(_concurrencyMode, _enforceOrderedReceive, rpc.Channel.HasSession); } internal static bool IsConcurrent(ConcurrencyMode concurrencyMode, bool ensureOrderedDispatch, bool hasSession) { if (concurrencyMode != ConcurrencyMode.Single) { return true; } if (hasSession) { return false; } if (ensureOrderedDispatch) { return false; } return true; } internal static bool IsConcurrent(ChannelDispatcher runtime, bool hasSession) { bool isConcurrencyModeSingle = true; foreach (EndpointDispatcher endpointDispatcher in runtime.Endpoints) { if (endpointDispatcher.DispatchRuntime.EnsureOrderedDispatch) { return false; } if (endpointDispatcher.DispatchRuntime.ConcurrencyMode != ConcurrencyMode.Single) { isConcurrencyModeSingle = false; } } if (!isConcurrencyModeSingle) { return true; } if (!hasSession) { return true; } return false; } internal void LockInstance(ref MessageRpc rpc) { if (_concurrencyMode != ConcurrencyMode.Multiple) { ConcurrencyInstanceContextFacet resource = rpc.InstanceContext.Concurrency; lock (rpc.InstanceContext.ThisLock) { if (!resource.Locked) { resource.Locked = true; } else { MessageRpcWaiter waiter = new MessageRpcWaiter(rpc.Pause()); resource.EnqueueNewMessage(waiter); } } if (_concurrencyMode == ConcurrencyMode.Reentrant) { rpc.OperationContext.IsServiceReentrant = true; } } } internal void UnlockInstance(ref MessageRpc rpc) { if (_concurrencyMode != ConcurrencyMode.Multiple) { ConcurrencyBehavior.UnlockInstance(rpc.InstanceContext); } } internal static void UnlockInstanceBeforeCallout(OperationContext operationContext) { if (operationContext != null && operationContext.IsServiceReentrant) { ConcurrencyBehavior.UnlockInstance(operationContext.InstanceContext); } } private static void UnlockInstance(InstanceContext instanceContext) { ConcurrencyInstanceContextFacet resource = instanceContext.Concurrency; lock (instanceContext.ThisLock) { if (resource.HasWaiters) { IWaiter nextWaiter = resource.DequeueWaiter(); nextWaiter.Signal(); } else { //We have no pending Callouts and no new Messages to process resource.Locked = false; } } } internal static void LockInstanceAfterCallout(OperationContext operationContext) { if (operationContext != null) { InstanceContext instanceContext = operationContext.InstanceContext; if (operationContext.IsServiceReentrant) { ConcurrencyInstanceContextFacet resource = instanceContext.Concurrency; ThreadWaiter waiter = null; lock (instanceContext.ThisLock) { if (!resource.Locked) { resource.Locked = true; } else { waiter = new ThreadWaiter(); resource.EnqueueCalloutMessage(waiter); } } if (waiter != null) { waiter.Wait(); } } } } internal interface IWaiter { void Signal(); } internal class MessageRpcWaiter : IWaiter { private IResumeMessageRpc _resume; internal MessageRpcWaiter(IResumeMessageRpc resume) { _resume = resume; } void IWaiter.Signal() { try { bool alreadyResumedNoLock; _resume.Resume(out alreadyResumedNoLock); if (alreadyResumedNoLock) { Fx.Assert("ConcurrencyBehavior resumed more than once for same call."); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } } internal class ThreadWaiter : IWaiter { private ManualResetEvent _wait = new ManualResetEvent(false); void IWaiter.Signal() { _wait.Set(); } internal void Wait() { _wait.WaitOne(); _wait.Dispose(); } } } internal class ConcurrencyInstanceContextFacet { internal bool Locked; private Queue<ConcurrencyBehavior.IWaiter> _calloutMessageQueue; private Queue<ConcurrencyBehavior.IWaiter> _newMessageQueue; internal bool HasWaiters { get { return (((_calloutMessageQueue != null) && (_calloutMessageQueue.Count > 0)) || ((_newMessageQueue != null) && (_newMessageQueue.Count > 0))); } } private ConcurrencyBehavior.IWaiter DequeueFrom(Queue<ConcurrencyBehavior.IWaiter> queue) { ConcurrencyBehavior.IWaiter waiter = queue.Dequeue(); if (queue.Count == 0) { queue.TrimExcess(); } return waiter; } internal ConcurrencyBehavior.IWaiter DequeueWaiter() { // Finishing old work takes precedence over new work. if ((_calloutMessageQueue != null) && (_calloutMessageQueue.Count > 0)) { return this.DequeueFrom(_calloutMessageQueue); } else { return this.DequeueFrom(_newMessageQueue); } } internal void EnqueueNewMessage(ConcurrencyBehavior.IWaiter waiter) { if (_newMessageQueue == null) _newMessageQueue = new Queue<ConcurrencyBehavior.IWaiter>(); _newMessageQueue.Enqueue(waiter); } internal void EnqueueCalloutMessage(ConcurrencyBehavior.IWaiter waiter) { if (_calloutMessageQueue == null) _calloutMessageQueue = new Queue<ConcurrencyBehavior.IWaiter>(); _calloutMessageQueue.Enqueue(waiter); } } }
using System; using System.Dynamic; using NUnit.Framework; namespace SequelocityDotNet.Tests.SqlServer.DatabaseCommandExtensionsTests { [TestFixture] public class GenerateInsertForSqlServerTests { public class Customer { public int? CustomerId; public string FirstName; public string LastName; public DateTime DateOfBirth; } [Test] public void Should_Return_The_Last_Inserted_Id() { // Arrange const string sql = @" IF ( EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer' ) ) BEGIN DROP TABLE Customer END IF ( NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer') ) BEGIN CREATE TABLE Customer ( CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL ); END "; Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ) .ExecuteNonQuery(); var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; // Act var customerId = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .GenerateInsertForSqlServer( customer ) .ExecuteScalar<int>(); // Assert Assert.That( customerId == 1 ); } [Test] public void Should_Handle_Generating_Inserts_For_A_Strongly_Typed_Object() { // Arrange const string createSchemaSql = @" IF ( EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer' ) ) BEGIN DROP TABLE Customer END IF ( NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer') ) BEGIN CREATE TABLE Customer ( CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL ); END "; Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); var newCustomer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; // Act var customerId = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .GenerateInsertForSqlServer( newCustomer ) .ExecuteScalar<int>(); const string selectCustomerQuery = @" SELECT CustomerId, FirstName, LastName, DateOfBirth FROM Customer; "; var customer = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( selectCustomerQuery ) .ExecuteToObject<Customer>(); // Assert Assert.That( customerId == 1 ); Assert.That( customer.CustomerId == 1 ); Assert.That( customer.FirstName == newCustomer.FirstName ); Assert.That( customer.LastName == newCustomer.LastName ); Assert.That( customer.DateOfBirth == newCustomer.DateOfBirth ); } [Test] public void Should_Be_Able_To_Specify_The_Table_Name() { // Arrange const string sql = @" IF ( EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Person' ) ) BEGIN DROP TABLE Person END IF ( NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Person') ) BEGIN CREATE TABLE Person ( CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL ); END "; Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ) .ExecuteNonQuery(); var customer = new Customer { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; // Act var customerId = Sequelocity.GetDatabaseCommandForSqlServer( ConnectionStringsNames.SqlServerConnectionString ) .GenerateInsertForSqlServer( customer, "[Person]" ) // Specifying a table name of Person .ExecuteScalar<int>(); // Assert Assert.That( customerId == 1 ); } [Test] public void Should_Throw_An_Exception_When_Passing_An_Anonymous_Object_And_Not_Specifying_A_TableName() { // Arrange const string sql = @" IF ( EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Person' ) ) BEGIN DROP TABLE Person END IF ( NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Person') ) BEGIN CREATE TABLE Person ( CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL ); END "; Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ) .ExecuteNonQuery(); var customer = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; // Act TestDelegate action = () => Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .GenerateInsertForSqlServer( customer ) .ExecuteScalar<int>(); // Assert var exception = Assert.Catch<ArgumentNullException>( action ); Assert.That( exception.Message.Contains( "The 'tableName' parameter must be provided when the object supplied is an anonymous type." ) ); } [Test] public void Should_Handle_Generating_Inserts_For_An_Anonymous_Object() { // Arrange const string createSchemaSql = @" IF ( EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer' ) ) BEGIN DROP TABLE Customer END IF ( NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer') ) BEGIN CREATE TABLE Customer ( CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL ); END "; Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); var newCustomer = new { FirstName = "Clark", LastName = "Kent", DateOfBirth = DateTime.Parse( "06/18/1938" ) }; // Act var customerId = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .GenerateInsertForSqlServer( newCustomer, "[Customer]" ) .ExecuteScalar<int>(); const string selectCustomerQuery = @" SELECT CustomerId, FirstName, LastName, DateOfBirth FROM Customer; "; var customer = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( selectCustomerQuery ) .ExecuteToObject<Customer>(); // Assert Assert.That( customerId == 1 ); Assert.That( customer.CustomerId == 1 ); Assert.That( customer.FirstName == newCustomer.FirstName ); Assert.That( customer.LastName == newCustomer.LastName ); Assert.That( customer.DateOfBirth == newCustomer.DateOfBirth ); } [Test] public void Should_Handle_Generating_Inserts_For_A_Dynamic_Object() { // Arrange const string createSchemaSql = @" IF ( EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer' ) ) BEGIN DROP TABLE Customer END IF ( NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Customer') ) BEGIN CREATE TABLE Customer ( CustomerId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, FirstName NVARCHAR(120) NOT NULL, LastName NVARCHAR(120) NOT NULL, DateOfBirth DATETIME NOT NULL ); END "; Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( createSchemaSql ) .ExecuteNonQuery(); dynamic newCustomer = new ExpandoObject(); newCustomer.FirstName = "Clark"; newCustomer.LastName = "Kent"; newCustomer.DateOfBirth = DateTime.Parse( "06/18/1938" ); // Act var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ); databaseCommand = DatabaseCommandExtensions.GenerateInsertForSqlServer( databaseCommand, newCustomer, "[Customer]" ); var customerId = databaseCommand .ExecuteScalar<int>(); const string selectCustomerQuery = @" SELECT CustomerId, FirstName, LastName, DateOfBirth FROM Customer; "; var customer = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( selectCustomerQuery ) .ExecuteToObject<Customer>(); // Assert Assert.That( customerId == 1 ); Assert.That( customer.CustomerId == 1 ); Assert.That( customer.FirstName == newCustomer.FirstName ); Assert.That( customer.LastName == newCustomer.LastName ); Assert.That( customer.DateOfBirth == newCustomer.DateOfBirth ); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using Microsoft.Ccr.Core; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.ServiceModel.Dssp; using Microsoft.Dss.ServiceModel.DsspServiceBase; using W3C.Soap; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.Core.DsspHttpUtilities; using System.Net; using System.Net.Mime; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using submgr = Microsoft.Dss.Services.SubscriptionManager; using proxibrick = TrackRoamer.Robotics.Services.TrackRoamerBrickProximityBoard.Proxy; using sicklrf = Microsoft.Robotics.Services.Sensors.SickLRF.Proxy; using TrackRoamer.Robotics.Utility.LibSystem; namespace TrackRoamer.Robotics.Services.TrackRoamerUsrf { // The ActivationSettings attribute with Sharing == false makes the runtime dedicate a dispatcher thread pool just for this service. // ExecutionUnitsPerDispatcher - Indicates the number of execution units allocated to the dispatcher // ShareDispatcher - Inidicates whether multiple service instances can be pooled or not [ActivationSettings(ShareDispatcher = false, ExecutionUnitsPerDispatcher = 8)] [Contract(Contract.Identifier)] [DisplayName("(User) TrackRoamer Ultrasound Range Finder")] [Description("Provides access to a TrackRoamer Ultrasound Range Finder.")] [AlternateContract(sicklrf.Contract.Identifier)] class TrackRoamerUsrfService : DsspServiceBase { /// <summary> /// Service state /// </summary> //[ServiceState(StateTransform = "Microsoft.Robotics.Services.Sensors.SickLRF.SickLRF.xslt")] [ServiceState(StateTransform = "TrackRoamer.Robotics.Services.TrackRoamerUsrf.TrackRoamerUsrf.xslt")] sicklrf.State _state = new sicklrf.State(); bool doAveraging = true; bool doWeeding = true; /// <summary> /// Main service port /// </summary> [ServicePort("/usrf", AllowMultipleInstances = false)] sicklrf.SickLRFOperations _mainPort = new sicklrf.SickLRFOperations(); [SubscriptionManagerPartner] submgr.SubscriptionManagerPort _submgrPort = new submgr.SubscriptionManagerPort(); /// <summary> /// TrackRoamerBrickProximityBoardService partner /// </summary> [Partner("TrackRoamerProximityBrick", Contract = proxibrick.Contract.Identifier, CreationPolicy = PartnerCreationPolicy.UseExistingOrCreate)] proxibrick.TrackRoamerBrickProximityBoardOperations _trackRoamerBrickProximityBoardServicePort = new proxibrick.TrackRoamerBrickProximityBoardOperations(); proxibrick.TrackRoamerBrickProximityBoardOperations _trackRoamerBrickProximityBoardServiceNotify = new proxibrick.TrackRoamerBrickProximityBoardOperations(); DsspHttpUtilitiesPort _httpUtilities; /// <summary> /// Service constructor /// </summary> public TrackRoamerUsrfService(DsspServiceCreationPort creationPort) : base(creationPort) { Tracer.Trace("TrackRoamerUsrfService::TrackRoamerUsrfService()"); } /// <summary> /// Service start /// </summary> protected override void Start() { Tracer.Trace("TrackRoamerUsrfService::Start()"); _httpUtilities = DsspHttpUtilitiesService.Create(Environment); base.Start(); // fire up MainPortInterleave; wireup [ServiceHandler] methods MainPortInterleave.CombineWith(new Interleave( new ExclusiveReceiverGroup( Arbiter.ReceiveWithIterator<sicklrf.Subscribe>(true, _mainPort, SubscribeHandler), Arbiter.ReceiveWithIterator<sicklrf.ReliableSubscribe>(true, _mainPort, ReliableSubscribeHandler), Arbiter.Receive<sicklrf.Get>(true, _mainPort, GetHandler), Arbiter.Receive<sicklrf.Reset>(true, _mainPort, ResetHandler), Arbiter.Receive<proxibrick.UpdateSonarData>(true, _trackRoamerBrickProximityBoardServiceNotify, trpbUpdateSonarNotification) ), new ConcurrentReceiverGroup() )); Tracer.Trace("TrackRoamerUsrfService: calling Subscribe() for UpdateSonarData"); Type[] notifyMeOf = new Type[] { typeof(proxibrick.UpdateSonarData) }; _trackRoamerBrickProximityBoardServicePort.Subscribe(_trackRoamerBrickProximityBoardServiceNotify, notifyMeOf); } /// <summary> /// convert sonar sweep into laser-like 180 degrees data /// </summary> /// <param name="update"></param> void trpbUpdateSonarNotification(proxibrick.UpdateSonarData update) { //LogInfo("TrackRoamerUsrfService: trpbUpdateNotification()"); //Tracer.Trace("TrackRoamerUsrfService: trpbUpdateNotification()"); try { proxibrick.SonarDataDssSerializable p = update.Body; int packetLength = p.RangeMeters.Length; // must be 26 packets, each covering 7 degrees; if (packetLength != 26) { Tracer.Error("TrackRoamerUsrfService::trpbUpdateNotification() not a standard measurement, angles.Count=" + packetLength + " (expected 26) -- ignored"); return; } int[] intRanges = new int[packetLength]; for(int i=0; i < packetLength ;i++) { // range = (ushort)(i * 40); ushort range = (ushort)Math.Round(p.RangeMeters[i] * 1000.0d); if (range > 0x1FF7) { range = 0x2000; // limit to 8192 mm; actual range about 4 meters } intRanges[i] = (int)range; } if (doWeeding) { if (intRanges[0] < (intRanges[1] + intRanges[2]) / 4) { intRanges[0] = (intRanges[1] + intRanges[2]) / 2; } if (intRanges[packetLength - 1] < (intRanges[packetLength - 2] + intRanges[packetLength - 3]) / 4) { intRanges[packetLength - 1] = (intRanges[packetLength - 2] + intRanges[packetLength - 3]) / 2; } for (int i = 1; i < packetLength-1; i++) { if (intRanges[i] < (intRanges[i - 1] + intRanges[i + 1]) * 3 / 8) { intRanges[i] = (intRanges[i - 1] + intRanges[i + 1]) / 2; } } } int angularRange = 180; int angularResolution = 1; int mesLength = angularRange + 1; // 181 int[] lsdRanges = new int[mesLength]; // millimeters, with 1 degree resolution int step = (int)Math.Round((double)mesLength / (double)packetLength); // typically round(6.96) = 7 // if we smooth the measurements, Decide() has better chance of sorting the values right. It does not like 7 degrees steps. // we need these for exponential moving average: double emaPeriod = 4.0d; double emaMultiplier = 2.0d / (1.0d + emaPeriod); double? emaPrev = null; int iRange = 0; for (int i = 0; i < mesLength; i++) // 0...181 { int angleIndex = Math.Min(i / step, packetLength-1); iRange = intRanges[angleIndex]; if (doAveraging) { // calculate exponential moving average - smooth the curve a bit: double? ema = !emaPrev.HasGoodValue() ? iRange : ((iRange - emaPrev) * emaMultiplier + emaPrev); emaPrev = ema; iRange = (int)Math.Round((double)ema); } //Tracer.Trace("&&&&&&&&&&&&&&&&&&&&&&&&&&&& i=" + i + " range=" + range + " ema=" + iRange); lsdRanges[i] = iRange; // 5000; // milimeters } _state.AngularRange = angularRange; _state.AngularResolution = angularResolution; _state.DistanceMeasurements = lsdRanges; _state.Units = sicklrf.Units.Millimeters; _state.TimeStamp = p.TimeStamp; _state.LinkState = "Measurement received"; // // Inform subscribed services that the state has changed. // _submgrPort.Post(new submgr.Submit(_state, DsspActions.ReplaceRequest)); } catch (Exception exc) { LogError(exc); } } /// <summary> /// Handles Get requests /// </summary> /// <param name="get">request message</param> [ServiceHandler] public void GetHandler(sicklrf.Get get) { Tracer.Trace("TrackRoamerUsrfService::GetHandler()"); get.ResponsePort.Post(_state); } /// <summary> /// Handles Replace requests /// </summary> /// <param name="replace">request message</param> [ServiceHandler] public void ReplaceHandler(sicklrf.Replace replace) { Tracer.Trace("TrackRoamerUsrfService::ReplaceHandler()"); _state = replace.Body; replace.ResponsePort.Post(DefaultReplaceResponseType.Instance); } // ==================================================================================== // as generated: //[ServiceHandler] //public void SubscribeHandler(sicklrf.Subscribe subscribe) //{ // throw new NotImplementedException(); //} /// <summary> /// Handles Subscribe requests /// </summary> /// <param name="subscribe">request message</param> IEnumerator<ITask> SubscribeHandler(sicklrf.Subscribe subscribe) { Tracer.Trace("TrackRoamerUsrfService::SubscribeHandler()"); yield return Arbiter.Choice( SubscribeHelper(_submgrPort, subscribe.Body, subscribe.ResponsePort), delegate(SuccessResult success) { if (_state != null && _state.DistanceMeasurements != null) { _submgrPort.Post(new submgr.Submit( subscribe.Body.Subscriber, DsspActions.ReplaceRequest, _state, null)); } }, null ); } // ==================================================================================== // as generated: //[ServiceHandler] //public void ReliableSubscribeHandler(sicklrf.ReliableSubscribe reliablesubscribe) //{ // throw new NotImplementedException(); //} /// <summary> /// Handles ReliableSubscribe requests /// </summary> /// <param name="reliablesubscribe">request message</param> IEnumerator<ITask> ReliableSubscribeHandler(sicklrf.ReliableSubscribe reliablesubscribe) { Tracer.Trace("TrackRoamerUsrfService::ReliableSubscribeHandler()"); yield return Arbiter.Choice( SubscribeHelper(_submgrPort, reliablesubscribe.Body, reliablesubscribe.ResponsePort), delegate(SuccessResult success) { if (_state != null && _state.DistanceMeasurements != null) { _submgrPort.Post(new submgr.Submit( reliablesubscribe.Body.Subscriber, DsspActions.ReplaceRequest, _state, null)); } }, null ); } /// <summary> /// Handles Reset requests /// </summary> /// <param name="reset">request message</param> [ServiceHandler] public void ResetHandler(sicklrf.Reset reset) { Tracer.Trace("TrackRoamerUsrfService::ResetHandler()"); // TBD: send reset request to the board partner reset.ResponsePort.Post(DefaultSubmitResponseType.Instance); } #region HttpGet Handlers static readonly string _root = "/sicklrf"; static readonly string _root1 = "/usrf/sicklrf"; static readonly string _root2 = "/usrf"; static readonly string _raw1 = "raw"; static readonly string _cylinder = "cylinder"; static readonly string _top = "top"; static readonly string _topw = "top/"; // example: http://localhost:50000/usrf/top /// <summary> /// Handles HttpGet requests /// </summary> /// <param name="httpget">request message</param> [ServiceHandler] public void HttpGetHandler(Microsoft.Dss.Core.DsspHttp.HttpGet httpGet) { HttpListenerRequest request = httpGet.Body.Context.Request; HttpListenerResponse response = httpGet.Body.Context.Response; Stream image = null; bool isMyPath = false; string path = request.Url.AbsolutePath; //Tracer.Trace("GET: path='" + path + "'"); if (path.StartsWith(_root)) { path = path.Substring(_root.Length); isMyPath = true; } else if (path.StartsWith(_root1)) { path = path.Substring(_root1.Length); isMyPath = true; } else if (path.StartsWith(_root2)) { path = path.Substring(_root2.Length); isMyPath = true; } if (isMyPath && path.StartsWith("/")) { path = path.Substring(1); } if (path == _cylinder) { image = GenerateCylinder(); } else if (path == _top) { image = GenerateTop(540); } else if (path.StartsWith(_topw)) { int width; string remain = path.Substring(_topw.Length); if (int.TryParse(remain, out width)) { image = GenerateTop(width); } } else if (path == "" || path == _raw1) { HttpResponseType rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath); httpGet.ResponsePort.Post(rsp); return; } if (image != null) { SendJpeg(httpGet.Body.Context, image); } else { httpGet.ResponsePort.Post(Fault.FromCodeSubcodeReason( W3C.Soap.FaultCodes.Receiver, DsspFaultCodes.OperationFailed, "Unable to generate Image for path '" + path + "'")); } } private void SendJpeg(HttpListenerContext context, Stream stream) { WriteResponseFromStream write = new WriteResponseFromStream(context, stream, MediaTypeNames.Image.Jpeg); _httpUtilities.Post(write); Activate( Arbiter.Choice( write.ResultPort, delegate(Stream res) { stream.Close(); }, delegate(Exception e) { stream.Close(); LogError(e); } ) ); } #endregion #region Image generators for HttpGet private Stream GenerateCylinder() { if (_state.DistanceMeasurements == null) { return null; } MemoryStream memory = null; int scalefactor = 3; int bmpWidth = _state.DistanceMeasurements.Length * scalefactor; int nearRange = 300; int farRange = 2000; int bmpHeight = 100; int topTextHeight = 17; // leave top for the text Font font = new Font(FontFamily.GenericSansSerif, 10, GraphicsUnit.Pixel); using (Bitmap bmp = new Bitmap(bmpWidth, bmpHeight)) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.LightGray); int half = (int)Math.Round(bmp.Height * 0.65d); int middle = _state.DistanceMeasurements.Length / 2; int rangeMax = 0; int pointMax = -1; Dictionary<int, string> labels = new Dictionary<int, string>(); for (int i = 0; i < _state.DistanceMeasurements.Length; i++) { int range = _state.DistanceMeasurements[i]; int x = i * scalefactor; if (i == middle) { g.DrawLine(Pens.Gray, x, topTextHeight, x, bmpHeight); } if (range > 0 && range < 8192) { if (range > rangeMax) { rangeMax = range; pointMax = x; } int h = bmp.Height * 300 / range; if (h < 0) { h = 0; } Color col = ColorHelper.LinearColor(Color.OrangeRed, Color.LightGreen, nearRange, farRange, range); //Color col = ColorHelper.LinearColor(Color.DarkBlue, Color.LightGray, 0, 8192, range); g.DrawLine(new Pen(col, (float)scalefactor), bmp.Width - x, Math.Max(topTextHeight, half - h), bmp.Width - x, Math.Min(bmpHeight, half + h)); if (i > 0 && i % 20 == 0 && i < _state.DistanceMeasurements.Length - 10) { double roundRange = Math.Round(range / 1000.0d, 1); // meters string str = "" + roundRange; labels.Add(x, str); } } } foreach (int x in labels.Keys) { string str = labels[x]; g.DrawString(str, font, Brushes.Black, bmp.Width - x - 8, (int)(bmpHeight - topTextHeight * 2 + Math.Abs((double)middle - x / scalefactor) * 20 / middle)); } if (pointMax > 0) { // draw a vertical green line where the distance reaches its max value: double roundRangeMax = Math.Round(rangeMax / 1000.0d, 1); // meters int shift = 3; // account for the fact that we get chunks of approx 7 points for 26 scan stops g.DrawLine(new Pen(Color.DarkGreen, (float)scalefactor), bmp.Width - pointMax - shift, half, bmp.Width - pointMax - shift, bmpHeight); g.DrawString("" + roundRangeMax + "m", font, Brushes.DarkGreen, bmp.Width - pointMax, bmpHeight - topTextHeight); } g.DrawString( _state.TimeStamp.ToString() + " max: " + rangeMax + " red: <" + nearRange + " green: >" + farRange, font, Brushes.Black, 0, 0 ); } memory = new MemoryStream(); bmp.Save(memory, ImageFormat.Jpeg); memory.Position = 0; } return memory; } internal class Lbl { public float lx; public float ly; public string label; } private Stream GenerateTop(int imageWidth) { if (_state.DistanceMeasurements == null) { return null; } MemoryStream memory = null; Font font = new Font(FontFamily.GenericSansSerif, 10, GraphicsUnit.Pixel); // Ultrasonic sensor reaches to about 3.5 meters; we scale the height of our display to this range: double maxExpectedRange = 5000.0d; // mm int imageHeight = imageWidth / 2; using (Bitmap bmp = new Bitmap(imageWidth, imageHeight)) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.LightGray); double angularOffset = -90 + _state.AngularRange / 2.0; double piBy180 = Math.PI / 180.0; double halfAngle = _state.AngularResolution / 2.0; double scale = imageHeight / maxExpectedRange; double drangeMax = 0.0d; GraphicsPath path = new GraphicsPath(); Dictionary<int, Lbl> labels = new Dictionary<int, Lbl>(); for (int pass = 0; pass != 2; pass++) { for (int i = 0; i < _state.DistanceMeasurements.Length; i++) { int range = _state.DistanceMeasurements[i]; if (range > 0 && range < 8192) { double angle = i * _state.AngularResolution - angularOffset; double lowAngle = (angle - halfAngle) * piBy180; double highAngle = (angle + halfAngle) * piBy180; double drange = range * scale; float lx = (float)(imageHeight + drange * Math.Cos(lowAngle)); float ly = (float)(imageHeight - drange * Math.Sin(lowAngle)); float hx = (float)(imageHeight + drange * Math.Cos(highAngle)); float hy = (float)(imageHeight - drange * Math.Sin(highAngle)); if (pass == 0) { if (i == 0) { path.AddLine(imageHeight, imageHeight, lx, ly); } path.AddLine(lx, ly, hx, hy); drangeMax = Math.Max(drangeMax, drange); } else { g.DrawLine(Pens.DarkBlue, lx, ly, hx, hy); if (i > 0 && i % 20 == 0 && i < _state.DistanceMeasurements.Length - 10) { float llx = (float)(imageHeight + drangeMax * 1.3f * Math.Cos(lowAngle)); float lly = (float)(imageHeight - drangeMax * 1.3f * Math.Sin(lowAngle)); double roundRange = Math.Round(range / 1000.0d, 1); // meters string str = "" + roundRange; labels.Add(i, new Lbl() { label = str, lx = llx, ly = lly }); } } } } if (pass == 0) { g.FillPath(Brushes.White, path); } } float botHalfWidth = (float)(680 / 2.0d * scale); DrawHelper.drawRobotBoundaries(g, botHalfWidth, imageWidth / 2, imageHeight); g.DrawString(_state.TimeStamp.ToString(), font, Brushes.Black, 0, 0); foreach (int x in labels.Keys) { Lbl lbl = labels[x]; g.DrawString(lbl.label, font, Brushes.Black, lbl.lx, lbl.ly); } } memory = new MemoryStream(); bmp.Save(memory, ImageFormat.Jpeg); memory.Position = 0; } return memory; } #endregion } }
/* Copyright (c) 2004-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Reflection; using System.Diagnostics; using System.Collections; using System.Text.RegularExpressions; using PHP.Core.Emit; using PHP.Core.Reflection; using System.Collections.Generic; namespace PHP.Core { #region InclusionResolutionContext /// <summary> /// Contains information needed during inclusion resolution. /// </summary> public class InclusionResolutionContext { /// <summary> /// Application context. /// </summary> public ApplicationContext ApplicationContext { get { return applicationContext; } } private ApplicationContext applicationContext; /// <summary> /// Directory, where the including script is present. /// </summary> public string ScriptDirectory { get { return scriptDirectory; } } private string scriptDirectory; /// <summary> /// Working directory. /// </summary> public string WorkingDirectory { get { return workingDirectory; } } private string workingDirectory; /// <summary> /// Semicolon-separated list of paths where included file is searched before the local directory is checked. /// </summary> public string SearchPaths { get { return searchPaths; } } private string searchPaths; /* /// <summary> /// Severity of inclusion-related errors. This is determined by type of inclusion being made and is needed by subsequent functions to report errors. /// </summary> public PhpError ErrorSeverity { get { return errorSeverity; } } private PhpError errorSeverity; */ public InclusionResolutionContext(ApplicationContext applicationContext, string scriptDirectory, string workingDirectory, string searchPaths) { Debug.Assert(applicationContext != null && scriptDirectory != null && workingDirectory != null && searchPaths != null); this.applicationContext = applicationContext; this.scriptDirectory = scriptDirectory; this.workingDirectory = workingDirectory; this.searchPaths = searchPaths; } } #endregion /// <summary> /// Interface marking a class containing script implementation. /// </summary> public interface IPhpScript { } /// <summary> /// Provides functionality related to PHP scripts. /// </summary> public sealed class PhpScript { /// <summary> /// A name of an assembly where all web pages are compiled in. /// </summary> /// <remarks> /// This has to be unified with the script library concept in the future. /// </remarks> public const string CompiledWebAppAssemblyName = "WebPages.dll"; #region Main Helper /// <summary> /// Determines whether a specified method whose declaring type is a script type is a Main helper. /// </summary> /// <param name="method">The method.</param> /// <param name="parameters">GetUserEntryPoint parameters (optimization). Can be <B>null</B> reference.</param> /// <returns>Whether a specified method is an arg-less stub.</returns> internal static bool IsMainHelper(MethodInfo/*!*/ method, ParameterInfo[] parameters) { Debug.Assert(method != null && PhpScript.IsScriptType(method.DeclaringType)); if (method.Name != ScriptModule.MainHelperName) return false; if (parameters == null) parameters = method.GetParameters(); return parameters.Length == 5 && parameters[4].ParameterType == Emit.Types.Bool[0]; } /// <summary> /// Checks whether a specified <see cref="Type"/> is a script type. /// </summary> /// <param name="type">The type to be checked.</param> /// <returns><B>true</B> iff <paramref name="type"/> is a script type.</returns> public static bool IsScriptType(Type type) { return typeof(IPhpScript).IsAssignableFrom(type); } ///// <summary> ///// Invokes a main method of a specified script. ///// </summary> ///// <param name="script">The script type to be dynamically included.</param> ///// <param name="context">A script context.</param> ///// <param name="variables">A table of defined variables.</param> ///// <param name="self">PHP object context.</param> ///// <param name="includer">PHP class context.</param> ///// <param name="isMain">Whether the target script is the main script.</param> ///// <returns>The return value of the helper method.</returns> ///// <exception cref="MissingMethodException">If the helper method is not found.</exception> ///// <exception cref="PhpException">Fatal error.</exception> ///// <exception cref="PhpUserException">Uncaught user exception.</exception> ///// <exception cref="ScriptDiedException">Script died or exit.</exception> ///// <exception cref="TargetInvocationException">An internal error thrown by the target.</exception> //internal static object InvokeMainHelper( // Type script, // ScriptContext context, // Dictionary<string, object> variables, // DObject self, // DTypeDesc includer, // bool isMain) //{ // MethodInfo mi = script.GetMethod(ScriptModule.MainHelperName); // if (mi == null) // throw new MissingMethodException(ScriptModule.MainHelperName); // return PhpFunctionUtils.Invoke(mi, null, context, variables, self, includer, isMain); //} #endregion #region Names /// <summary> /// String added to identifiers of m-decl functions/classes. /// </summary> internal const char MDeclMark = '#'; /// <summary> /// Splits a specified identifier and into a function/class name and an m-decl index (if applicable). /// </summary> /// <param name="fullClrName">An identifier.</param> /// <param name="name">The name of the function/class.</param> /// <param name="index">The index of the function/class if identifier has m-decl format or -1 if not.</param> public static void ParseMDeclName(string/*!*/ fullClrName, out string name, out int index) { Debug.Assert(fullClrName != null); int idx = fullClrName.LastIndexOf(MDeclMark); if (idx > 0) { name = fullClrName.Substring(0, idx); index = (int)UInt32.Parse(fullClrName.Substring(idx + 1)); } else { name = fullClrName; index = -1; } } public static string/*!*/ ParseMDeclName(string/*!*/ fullClrName) { Debug.Assert(fullClrName != null); int idx = fullClrName.LastIndexOf(MDeclMark); return (idx > 0) ? fullClrName.Substring(0, idx) : fullClrName; } /// <summary> /// Decides whehter a specified name has m-decl name format. /// </summary> /// <param name="name">The name of the function.</param> /// <param name="index">The m-decl index of the function. Should be positive.</param> /// <returns>Whether the name has m-decl name format.</returns> public static string FormatMDeclName(string name, int index) { Debug.Assert(index > 0); return String.Concat(name, MDeclMark, index.ToString()); } #endregion #region FindInclusionTargetPath, IsXxxInclusion #if !SILVERLIGHT ///// <summary> ///// Tests whether path can be used for script inclusion. ///// </summary> ///// <param name="context">Inclusion context containing information about include which is being evaluated.</param> ///// <param name="fullPath">FullPath value.</param> ///// <param name="pathIsValid">Function deciding about file existence.</param> ///// <param name="errorMessage">Error message containing description of occured error. If no error occured, null value is returned.</param> ///// <returns>True is path is valid for inclusion, otherwise false.</returns> //internal static bool IsPathValidForInclusion(InclusionResolutionContext context, FullPath fullPath, Predicate<FullPath>/*!*/pathIsValid, out string errorMessage) //{ // errorMessage = null; // //return // // (context.ApplicationContext.ScriptLibraryDatabase != null && context.ApplicationContext.ScriptLibraryDatabase.ContainsScript(fullPath)) || // // (fileExists != null && fileExists(fullPath)) || // // (fullPath.FileExists); // Debug.Assert(pathIsValid != null); // return pathIsValid(fullPath); //} /// <summary> /// Searches for an existing file among files which names are combinations of a relative path and one of the /// paths specified in a list. /// </summary> /// <param name="context">Inclusion context containing information about include which is being evaluated.</param> /// <param name="relativePath">The relative path.</param> /// <param name="pathIsValid">Function deciding file existence.</param> /// <returns>Full path to a first existing file or an empty path.</returns> private static FullPath SearchInSearchPaths(InclusionResolutionContext context, string relativePath, Predicate<FullPath>/*!*/pathIsValid) { // TODO: review this when script libraries are united with precompiled web if (context.SearchPaths == String.Empty) return FullPath.Empty; Debug.Assert(pathIsValid != null); string path; for (int i = 0, j = 0; j >= 0; i = j + 1) { j = context.SearchPaths.IndexOf(Path.PathSeparator, i); path = (j >= 0) ? context.SearchPaths.Substring(i, j - i) : context.SearchPaths.Substring(i); FullPath result = FullPath.Empty; // TODO: exceptions should be handled better, not as part of algorithm's logic try { string path_root = Path.GetPathRoot(path); // makes the path complete and absolute: if (path_root == "\\") { path = Path.Combine(Path.GetPathRoot(context.WorkingDirectory), path.Substring(1)); } else if (path_root == "") { path = Path.Combine(context.WorkingDirectory, path); } // combines the search path with the relative path: path = Path.GetFullPath(Path.Combine(path, relativePath)); // prepare the FullPath version result = new FullPath(path, false); } catch (SystemException) { continue; } // this function might throw an exception in case of ambiguity if (pathIsValid(result)/*IsPathValidForInclusion(context, result, pathIsValid, out errorMessage)*/) return result; //if (errorMessage != null) // return FullPath.Empty; } //errorMessage = null; return FullPath.Empty; } /// <summary> /// Searches for a specified inclusion target. /// </summary> /// <param name="context">Inclustion resolution context.</param> /// <param name="path">Path to the file to search.</param> /// <param name="pathIsValid">Function deciding about file existence. Only path that passes this function is returned.</param> /// <param name="errorMessage">Warning which should be reported by the compiler or a <B>null</B> reference. The error message can be set iff the returned path is empty.</param> /// <returns> /// A canonical path to the target file or a <B>null</B> reference if the file path is not valid or the file not exists. /// </returns> internal static FullPath FindInclusionTargetPath(InclusionResolutionContext context, string path, Predicate<FullPath>/*!*/pathIsValid, out string errorMessage) { Debug.Assert(context != null && path != null); Debug.Assert(pathIsValid != null); try { string root = Path.GetPathRoot(path); if (root == "\\") { // incomplete absolute path // // the path is at least one character long - the first character is slash that should be trimmed out: path = Path.Combine(Path.GetPathRoot(context.WorkingDirectory), path.Substring(1)); } else if (root == "") { // relative path // // search in search paths at first (accepts empty path list as well): FullPath result = SearchInSearchPaths(context, path, pathIsValid/*, out errorMessage*/); // if an error message occurred, immediately return //if (errorMessage != null) // return FullPath.Empty; // if the file is found then it exists so we can return immediately: if (!result.IsEmpty) { errorMessage = null; return result; } // not found => the path is combined with the directory where the script being compiled is stored: path = Path.Combine(context.ScriptDirectory, path); } // canonizes the complete absolute path: path = Path.GetFullPath(path); } catch (SystemException e) { errorMessage = e.Message + "\n" + e.StackTrace; return FullPath.Empty; } FullPath full_path = new FullPath(path, false); // file does not exists: if (!pathIsValid(full_path)/*IsPathValidForInclusion(context, full_path, pathIsValid, out errorMessage)*/) { errorMessage = "Script cannot be included with current configuration."; return FullPath.Empty; } errorMessage = null; return full_path; } #endif #endregion #region Unit Testing #if DEBUG && !SILVERLIGHT public static void Test_FindInclusionTargetPath() { ApplicationConfiguration app_config = Configuration.Application; string result, message; string[,] s = new string[,] { // source script // included script // working dir // include_path { @"C:\Web\phpBB2\includes\db.php", "./db/mssql.php", @"C:\Web\phpBB2", "."}, // -> path='C:\Web\phpBB2\db\mssql.php' message="" { @"C:\Web\phpBB2\includes\db.php", "/db/mssql.php", @"D:\Video", ""}, // -> path='' message="File 'D:\db\mssql.php' does not exist." { @"C:\Web\phpBB2\includes\db.php", "./mssql.php", @"C:\Web\phpBB2", "db"}, // -> path='C:\Web\phpBB2\db\mssql.php' message="" { @"C:\Web\phpBB2\includes\db.php", "./mssql.php", @"C:\Web\phpBB2", "x"}, // -> path='' message="File 'C:\Web\phpBB2\includes\mssql.php' does not exist." { @"C:\Web\phpBB2\includes\db.php", "mssql.php", @"C:\Web\phpBB2", "/Web/phpBB2/db"}, // -> path='C:\Web\phpBB2\db\mssql.php' message="" { @"C:\Web\phpBB2\includes\db.php", "mssql.php", @"C:\Web\phpBB2", "/Web/php*B2/db"}, // -> path='' message="File 'C:\Web\phpBB2\includes\mssql.php' does not exist." { @"C:\Web\phpBB2\includes\db.php", "mssql.php", @"C:\W*b\phpBB2", "/Web/phpBB2/db"}, // -> path='C:\Web\phpBB2\db\mssql.php' message="" { @"C:\Web\phpBB2\includes\db.php", "*/mssql.php", @"C:\W*b\phpBB2", "/Web/phpBB2/db"}, // -> path='' message="Illegal characters in path." }; Console.WriteLine("{0}; {1}; {2}; {3}\n", "source script", "included script", "working dir", "include_path"); for (int i = 0; i < s.GetLength(0); i++) { result = FindInclusionTargetPath(new InclusionResolutionContext(ApplicationContext.Default, s[i, 0], s[i, 2], s[i, 3]), s[i, 1], (path) => path.FileExists, out message); Console.WriteLine("'{0}'; '{1}'; '{2}'; '{3}'\npath='{4}' message=\"{5}\"\n", s[i, 0], s[i, 1], s[i, 2], s[i, 3], result, message); } } public static void Test_TranslateIncludeExpression() { ApplicationConfiguration app = Configuration.Application; string[,] s = new string[,] { // pattern // replacement // expression {@"LIB_PATH\s*\.\s*""([^""$]+)""", @"/Library/$1", "LIB_PATH . \"file1.php\""}, // result='/Library/file1.php' {@"LIB_PATH\s*\.\s*""([^""$]+)""", @"/Library/$1", " \t LIB_PATH . \"file2.php\""}, // result='/Library/file2.php' {@"LIB_PATH\s*\.\s*""([^""$]+)""", @"/Library/$1", "lib_path.\"file3.php\""}, // result='/Library/file3.php' {@"LIB_PATH\s*\.\s*""([^""$]+)""", @"/Library/$1", "LIB_PATH.\"file$i.php\""}, // result='' {@"LIB_PATH\s*\.\s*""([^""$]+)""", @"/Library/$1", "'file3.php'"}, // result='' {@"LIB_PATH\s*\.\s*""([^""$]+)""", @"/Library/$1", "$x.'file3.php'"}, // result='' }; List<InclusionMapping> mappings = new List<InclusionMapping>(1); Console.WriteLine("{0}; {1}; {2};\n", "pattern", "replacement", "expression"); for (int i = 0; i < s.GetLength(0); i++) { mappings[0] = new InclusionMapping(s[i, 0], s[i, 1], null); string result = InclusionMapping.TranslateExpression(mappings, s[i, 2], @"C:\inetpub\wwwroot"); Console.WriteLine("#{0}# '{1}' '{2}'\nresult='{3}'\n", s[i, 0], s[i, 1], s[i, 2], result); } } #endif #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Platform.IO; using ZLib = ICSharpCode.SharpZipLib.Zip; namespace Platform.VirtualFileSystem.Providers.Zip { public class ZipFileSystem : AbstractFileSystem { internal ZLib.ZipFile zipFile; public override bool SupportsActivityEvents => true; private readonly AttributeChangeDeterminer changeDeterminer; private readonly Dictionary<string, ZipFileInfo> zipFileInfos = new Dictionary<string, ZipFileInfo>(StringComparer.InvariantCultureIgnoreCase); private readonly Dictionary<string, ZipDirectoryInfo> zipDirectoryInfos = new Dictionary<string, ZipDirectoryInfo>(StringComparer.InvariantCultureIgnoreCase); internal virtual ZipDirectoryInfo GetZipDirectoryInfo(string path) { lock (this) { ZipDirectoryInfo retval; if (!zipDirectoryInfos.TryGetValue(path, out retval)) { retval = new ZipDirectoryInfo(false) { AbsolutePath = path }; zipDirectoryInfos[path] = retval; } return retval; } } internal virtual ZipFileInfo GetZipFileInfo(string path) { lock (this) { ZipFileInfo retval; if (!zipFileInfos.TryGetValue(path, out retval)) { retval = new ZipFileInfo(null) { AbsolutePath = path }; zipFileInfos[path] = retval; } return retval; } } private void RefreshNodeInfos() { lock (this) { if (zipFileInfos != null) { foreach (var zipFileInfo in this.zipFileInfos.Values.Where(c => c.ShadowFile != null)) { try { zipFileInfo.ShadowFile.Delete(); } catch { } } } zipFileInfos.Clear(); zipDirectoryInfos.Clear(); var directories = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { "/" }; var zipEntriesByDirectory = new Dictionary<string, ZLib.ZipEntry>(); foreach (ZLib.ZipEntry zipEntry in zipFile) { if (zipEntry.IsDirectory) { var s = "/" + zipEntry.Name.TrimRight('/'); directories.Add(s); zipEntriesByDirectory[s] = zipEntry; } else { var zipFileInfo = new ZipFileInfo(zipEntry); var x = zipEntry.Name.LastIndexOf('/'); if (x > 0) { var path = zipEntry.Name.Substring(0, x); directories.Add("/" + path); } zipFileInfo.AbsolutePath = "/" + zipEntry.Name; zipFileInfos[zipFileInfo.AbsolutePath] = zipFileInfo; } } foreach (var directoryPath in directories) { ZLib.ZipEntry zipEntry; var zipDirectoryInfo = new ZipDirectoryInfo(true); if (zipEntriesByDirectory.TryGetValue(directoryPath, out zipEntry)) { zipDirectoryInfo.ZipEntry = zipEntry; } zipDirectoryInfo.AbsolutePath = directoryPath; zipDirectoryInfos[zipDirectoryInfo.AbsolutePath] = zipDirectoryInfo; } } } public virtual void Flush() { this.Flush(true); } private void Flush(bool refresh) { lock (this) { var filesChanged = zipFileInfos.Values.Where(c => c.ShadowFile != null).ToList(); var filesDeleted = zipFileInfos.Values.Where(c => !c.Exists && c.ZipEntry != null).ToList(); var setOfPreviousDirectories = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); foreach (ZLib.ZipEntry zipEntry in zipFile) { if (zipEntry.IsDirectory) { setOfPreviousDirectories.Add("/" + zipEntry.Name.Substring(0, zipEntry.Name.Length - 1)); } else { var x = zipEntry.Name.LastIndexOf('/'); if (x > 0) { var path = zipEntry.Name.Substring(0, x); setOfPreviousDirectories.Add("/" + path); } } } var setOfCurrentImplicitDirectories = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); var setOfCurrentDirectories = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); foreach (var zipFileInfo in zipFileInfos.Values) { if (zipFileInfo.Exists) { var x = zipFileInfo.AbsolutePath.LastIndexOf('/'); if (x > 0) { var path = zipFileInfo.AbsolutePath.Substring(0, x); setOfCurrentDirectories.Add(path); setOfCurrentImplicitDirectories.Add(path); } } } foreach (var zipDirectoryInfo in zipDirectoryInfos.Values.Where(c => c.Exists)) { setOfCurrentDirectories.Add(zipDirectoryInfo.AbsolutePath); } var setOfNewDirectories = new HashSet<string>(setOfCurrentDirectories.Where(c => !setOfPreviousDirectories.Contains(c)), StringComparer.InvariantCultureIgnoreCase); var setOfDeletedDirectories = new HashSet<string>(setOfPreviousDirectories.Where(c => !setOfCurrentDirectories.Contains(c)), StringComparer.InvariantCultureIgnoreCase); var setOfDirectoriesToCreate = new HashSet<string>(setOfNewDirectories.Where(c => !setOfCurrentImplicitDirectories.Contains(c)), StringComparer.InvariantCultureIgnoreCase); setOfDirectoriesToCreate.Remove("/"); if (filesChanged.Count > 0 || filesDeleted.Count > 0) { zipFile.BeginUpdate(); try { foreach (var zipFileInfo in filesChanged) { var shadowFile = zipFileInfo.ShadowFile; var name = zipFileInfo.AbsolutePath; try { zipFile.Add(new StreamDataSource(shadowFile.GetContent().GetInputStream()), name); } catch (FileNodeNotFoundException) { } } foreach (var zipFileInfo in filesDeleted) { zipFile.Delete(zipFileInfo.ZipEntry); } foreach (var directoryToCreate in setOfDirectoriesToCreate) { zipFile.AddDirectory(directoryToCreate); } foreach (var directory in setOfDeletedDirectories) { // SharpZipLib currently doesn't support removing explicit directories } } finally { zipFile.CommitUpdate(); } } if (refresh) { this.RefreshNodeInfos(); } } } protected override void Dispose(bool disposing) { lock (this) { this.Flush(false); this.Close(); foreach (var zipFileInfo in this.zipFileInfos.Values.Where(c => c.ShadowFile != null)) { try { zipFileInfo.ShadowFile.Delete(); } catch { } } ((IDisposable)this.zipFile).Dispose(); } base.Dispose(disposing); } public ZipFileSystem(IFile file) : this(file, FileSystemOptions.Default) { } public ZipFileSystem(IFile file, FileSystemOptions options) : this(LayeredNodeAddress.Parse("zip://[" + file.Address.Uri + "]"), file, options) { } public static ZipFileSystem CreateZipFile(IFile zipFile) { return CreateZipFile(zipFile, FileSystemOptions.Default); } public static ZipFileSystem CreateZipFile(IFile zipFile, FileSystemOptions options) { return CreateZipFile(zipFile, null, null, options); } public static ZipFileSystem CreateZipFile(IFile zipFile, IDirectory zipFilecontents) { return CreateZipFile(zipFile, zipFilecontents, FileSystemOptions.Default); } public static ZipFileSystem CreateZipFile(IFile zipFile, IDirectory zipFileContents, FileSystemOptions options) { return CreateZipFile(zipFile, zipFileContents.Walk(NodeType.File).Select(c => (IFile)c), file => zipFileContents.Address.GetRelativePathTo(file.Address), options); } public static ZipFileSystem CreateZipFile(IFile zipFile, IEnumerable<IFile> files, Func<IFile, string> fileToFullPath, FileSystemOptions options) { var compressionLevel = 9; var zipCompressionLevel = options.Variables["ZipCompressionLevel"]; if (zipCompressionLevel != null) { compressionLevel = Convert.ToInt32(zipCompressionLevel); if (compressionLevel < 0) { compressionLevel = 0; } else if (compressionLevel > 9) { compressionLevel = 9; } } var password = options.Variables["ZipPassword"]; using (var zipOutputStream = new ZLib.ZipOutputStream(zipFile.GetContent().GetOutputStream())) { zipOutputStream.SetLevel(compressionLevel); zipOutputStream.IsStreamOwner = true; zipOutputStream.UseZip64 = ZLib.UseZip64.Dynamic; zipOutputStream.Password = password; if (files != null) { foreach (var file in files) { var entryName = fileToFullPath(file); entryName = ZLib.ZipEntry.CleanName(entryName); var entry = new ZLib.ZipEntry(entryName); using (var stream = file.GetContent().GetInputStream(FileMode.Open, FileShare.Read)) { if (stream.Length > 0) { entry.Size = stream.Length; } zipOutputStream.PutNextEntry(entry); stream.CopyTo(zipOutputStream); } zipOutputStream.CloseEntry(); } } } return new ZipFileSystem(zipFile, options); } private static IFile GetZipFile(IFile zipFile) { if (zipFile.Address.QueryValues["shadow"] as string == "true") { return zipFile; } if (ConfigurationSection.Instance.AutoShadowThreshold == -1 || zipFile.Length <= ConfigurationSection.Instance.AutoShadowThreshold) { zipFile = zipFile.ResolveFile(StringUriUtils.AppendQueryPart(zipFile.Address.NameAndQuery, "shadow", "true")); } return zipFile; } /// <summary> /// Constructs a new <c>ZipFileSystem</c> /// </summary> /// <param name="rootAddress">The root address of the zip file system.</param> /// <param name="zipFile">The zip file that hosts the file system.</param> /// <param name="options">Options for the file system.</param> public ZipFileSystem(INodeAddress rootAddress, IFile zipFile, FileSystemOptions options) : base(rootAddress, GetZipFile(zipFile), options) { this.changeDeterminer = new AttributeChangeDeterminer(ParentLayer, "LastWriteTime", "Length"); this.OpenZlib(); this.RefreshNodeInfos(); if (zipFile.SupportsActivityEvents && options.ReadOnly) { zipFile.Activity += new NodeActivityEventHandler(ZipFile_Activity); } } protected virtual void ZipFile_Activity(object sender, NodeActivityEventArgs eventArgs) { if (eventArgs.Activity == FileSystemActivity.Changed) { Reload(); } } internal virtual void CheckAndReload() { if (!this.changeDeterminer.IsUnchanged()) { Reload(); } } private void OpenZlib() { if (this.Options.ReadOnly) { this.zipFile = new ZLib.ZipFile(this.ParentLayer.GetContent().GetInputStream(FileShare.ReadWrite)) { Password = this.Options.Variables["ZipPassword"] }; } else { this.zipFile = new ZLib.ZipFile(this.ParentLayer.GetContent().OpenStream(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { Password = this.Options.Variables["ZipPassword"] }; } } protected virtual void Reload() { lock (this) { if (this.isClosed || this.isClosing) { return; } this.zipFile.Close(); this.changeDeterminer.MakeUnchanged(); this.OpenZlib(); this.RefreshNodeInfos(); } } public override event FileSystemActivityEventHandler Activity; protected virtual void OnActivity(FileSystemActivityEventArgs eventArgs) { if (Activity != null) { Activity(this, eventArgs); } } private bool isClosed; private bool isClosing; public override void Close() { isClosing = true; base.Close(); lock (this) { if (isClosed) { return; } this.zipFile.Close(); isClosed = true; foreach (var zipFileInfo in this.zipFileInfos.Values.Where(c => c.ShadowFile != null)) { try { zipFileInfo.ShadowFile.Delete(); } catch { } } } } public override INode Resolve(INodeAddress address, NodeType nodeType) { lock (this) { CheckAndReload(); if (nodeType == NodeType.Any) { var node = this.Resolve(address, NodeType.File); if (node.Exists) { return node; } node = Resolve(address, NodeType.Directory); if (node.Exists) { return node; } return base.Resolve(address, NodeType.Directory); } return base.Resolve(address, nodeType); } } internal virtual ZLib.ZipEntry GetEntry(string path) { lock (this) { CheckAndReload(); if (path.Length > 1 && path[0] == FileSystemManager.SeperatorChar) { path = path.Substring(1); } return this.zipFile.GetEntry(path); } } private class PrivateStreamWrapper : StreamWrapper { public PrivateStreamWrapper(Stream s) : base(s) { } public override void Close() { } } internal virtual Stream GetInputStream(string path) { lock (this) { if (path.Length > 1 && path[0] == FileSystemManager.SeperatorChar) { path = path.Substring(1); } var zipEntry = this.zipFile.GetEntry(path); if (zipEntry == null) { throw new FileNodeNotFoundException(); } return GetInputStream(zipEntry); } } internal virtual Stream GetInputStream(ZLib.ZipEntry zipEntry) { lock (this) { return new PrivateStreamWrapper(this.zipFile.GetInputStream(zipEntry)); } } protected override INode CreateNode(INodeAddress address, NodeType nodeType) { lock (this) { string path; if (nodeType.Equals(NodeType.File)) { path = ((AbstractNodeAddressWithRootPart)address).AbsolutePathIncludingRootPart; return new ZipFile(this, (LayeredNodeAddress)address, GetEntry(path)); } else if (nodeType.Equals(NodeType.Directory)) { path = ((AbstractNodeAddressWithRootPart)address).AbsolutePathIncludingRootPart; if (path != FileSystemManager.SeperatorString) { path += "/"; } return new ZipDirectory(this, (LayeredNodeAddress)address, GetEntry(path)); } else { throw new NotSupportedException(nodeType.ToString()); } } } } }
using Prism.Properties; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Policy; namespace Prism.Modularity { /// <summary> /// Represets a catalog created from a directory on disk. /// </summary> /// <remarks> /// The directory catalog will scan the contents of a directory, locating classes that implement /// <see cref="IModule"/> and add them to the catalog based on contents in their associated <see cref="ModuleAttribute"/>. /// Assemblies are loaded into a new application domain with ReflectionOnlyLoad. The application domain is destroyed /// once the assemblies have been discovered. /// /// The diretory catalog does not continue to monitor the directory after it has created the initialze catalog. /// </remarks> public class DirectoryModuleCatalog : ModuleCatalog { /// <summary> /// Directory containing modules to search for. /// </summary> public string ModulePath { get; set; } /// <summary> /// Drives the main logic of building the child domain and searching for the assemblies. /// </summary> protected override void InnerLoad() { if (string.IsNullOrEmpty(this.ModulePath)) throw new InvalidOperationException(Resources.ModulePathCannotBeNullOrEmpty); if (!Directory.Exists(this.ModulePath)) throw new InvalidOperationException( string.Format(CultureInfo.CurrentCulture, Resources.DirectoryNotFound, this.ModulePath)); AppDomain childDomain = this.BuildChildDomain(AppDomain.CurrentDomain); try { List<string> loadedAssemblies = new List<string>(); var assemblies = ( from Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() where !(assembly is System.Reflection.Emit.AssemblyBuilder) && assembly.GetType().FullName != "System.Reflection.Emit.InternalAssemblyBuilder" && !String.IsNullOrEmpty(assembly.Location) select assembly.Location ); loadedAssemblies.AddRange(assemblies); Type loaderType = typeof(InnerModuleInfoLoader); if (loaderType.Assembly != null) { var loader = (InnerModuleInfoLoader) childDomain.CreateInstanceFrom(loaderType.Assembly.Location, loaderType.FullName).Unwrap(); loader.LoadAssemblies(loadedAssemblies); this.Items.AddRange(loader.GetModuleInfos(this.ModulePath)); } } finally { AppDomain.Unload(childDomain); } } /// <summary> /// Creates a new child domain and copies the evidence from a parent domain. /// </summary> /// <param name="parentDomain">The parent domain.</param> /// <returns>The new child domain.</returns> /// <remarks> /// Grabs the <paramref name="parentDomain"/> evidence and uses it to construct the new /// <see cref="AppDomain"/> because in a ClickOnce execution environment, creating an /// <see cref="AppDomain"/> will by default pick up the partial trust environment of /// the AppLaunch.exe, which was the root executable. The AppLaunch.exe does a /// create domain and applies the evidence from the ClickOnce manifests to /// create the domain that the application is actually executing in. This will /// need to be Full Trust for Prism applications. /// </remarks> /// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException"/> is thrown if <paramref name="parentDomain"/> is null.</exception> protected virtual AppDomain BuildChildDomain(AppDomain parentDomain) { if (parentDomain == null) throw new ArgumentNullException(nameof(parentDomain)); Evidence evidence = new Evidence(parentDomain.Evidence); AppDomainSetup setup = parentDomain.SetupInformation; return AppDomain.CreateDomain("DiscoveryRegion", evidence, setup); } private class InnerModuleInfoLoader : MarshalByRefObject { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal ModuleInfo[] GetModuleInfos(string path) { DirectoryInfo directory = new DirectoryInfo(path); ResolveEventHandler resolveEventHandler = delegate(object sender, ResolveEventArgs args) { return OnReflectionOnlyResolve(args, directory); }; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolveEventHandler; Assembly moduleReflectionOnlyAssembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().First( asm => asm.FullName == typeof(IModule).Assembly.FullName); Type IModuleType = moduleReflectionOnlyAssembly.GetType(typeof(IModule).FullName); IEnumerable<ModuleInfo> modules = GetNotAllreadyLoadedModuleInfos(directory, IModuleType); var array = modules.ToArray(); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolveEventHandler; return array; } private static IEnumerable<ModuleInfo> GetNotAllreadyLoadedModuleInfos(DirectoryInfo directory, Type IModuleType) { List<FileInfo> validAssemblies = new List<FileInfo>(); Assembly[] alreadyLoadedAssemblies = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies(); var fileInfos = directory.GetFiles("*.dll") .Where(file => alreadyLoadedAssemblies .FirstOrDefault( assembly => String.Compare(Path.GetFileName(assembly.Location), file.Name, StringComparison.OrdinalIgnoreCase) == 0) == null); foreach (FileInfo fileInfo in fileInfos) { try { Assembly.ReflectionOnlyLoadFrom(fileInfo.FullName); validAssemblies.Add(fileInfo); } catch (BadImageFormatException) { // skip non-.NET Dlls } } return validAssemblies.SelectMany(file => Assembly.ReflectionOnlyLoadFrom(file.FullName) .GetExportedTypes() .Where(IModuleType.IsAssignableFrom) .Where(t => t != IModuleType) .Where(t => !t.IsAbstract) .Select(type => CreateModuleInfo(type))); } private static Assembly OnReflectionOnlyResolve(ResolveEventArgs args, DirectoryInfo directory) { Assembly loadedAssembly = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies().FirstOrDefault( asm => string.Equals(asm.FullName, args.Name, StringComparison.OrdinalIgnoreCase)); if (loadedAssembly != null) { return loadedAssembly; } AssemblyName assemblyName = new AssemblyName(args.Name); string dependentAssemblyFilename = Path.Combine(directory.FullName, assemblyName.Name + ".dll"); if (File.Exists(dependentAssemblyFilename)) { return Assembly.ReflectionOnlyLoadFrom(dependentAssemblyFilename); } return Assembly.ReflectionOnlyLoad(args.Name); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void LoadAssemblies(IEnumerable<string> assemblies) { foreach (string assemblyPath in assemblies) { try { Assembly.ReflectionOnlyLoadFrom(assemblyPath); } catch (FileNotFoundException) { // Continue loading assemblies even if an assembly can not be loaded in the new AppDomain } } } private static ModuleInfo CreateModuleInfo(Type type) { string moduleName = type.Name; List<string> dependsOn = new List<string>(); bool onDemand = false; var moduleAttribute = CustomAttributeData.GetCustomAttributes(type).FirstOrDefault( cad => cad.Constructor.DeclaringType.FullName == typeof(ModuleAttribute).FullName); if (moduleAttribute != null) { foreach (CustomAttributeNamedArgument argument in moduleAttribute.NamedArguments) { string argumentName = argument.MemberInfo.Name; switch (argumentName) { case "ModuleName": moduleName = (string) argument.TypedValue.Value; break; case "OnDemand": onDemand = (bool) argument.TypedValue.Value; break; case "StartupLoaded": onDemand = !((bool) argument.TypedValue.Value); break; } } } var moduleDependencyAttributes = CustomAttributeData.GetCustomAttributes(type).Where( cad => cad.Constructor.DeclaringType.FullName == typeof(ModuleDependencyAttribute).FullName); foreach (CustomAttributeData cad in moduleDependencyAttributes) { dependsOn.Add((string) cad.ConstructorArguments[0].Value); } ModuleInfo moduleInfo = new ModuleInfo(moduleName, type.AssemblyQualifiedName) { InitializationMode = onDemand ? InitializationMode.OnDemand : InitializationMode.WhenAvailable, Ref = type.Assembly.CodeBase, }; moduleInfo.DependsOn.AddRange(dependsOn); return moduleInfo; } } } }
//--------------------------------------------------------------------------- // // File: RtfToXamlLexer.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Rtf lexer. // //--------------------------------------------------------------------------- using System.Collections; using System.Diagnostics; using System.Globalization; using System.Text; using System.IO; // Stream namespace System.Windows.Documents { /// <summary> /// RtfToXamlLexer. /// </summary> internal class RtfToXamlLexer { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// RtfToXamlLexer /// </summary> internal RtfToXamlLexer(byte[] rtfBytes) { _rtfBytes = rtfBytes; _currentCodePage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage; _currentEncoding = Encoding.GetEncoding(_currentCodePage); } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// /// </summary> /// <param name="token"></param> /// <param name="formatState"></param> /// <returns></returns> internal RtfToXamlError Next(RtfToken token, FormatState formatState) { RtfToXamlError rtfToXamlError = RtfToXamlError.None; _rtfLastIndex = _rtfIndex; token.Empty(); if (_rtfIndex >= _rtfBytes.Length) { token.Type = RtfTokenType.TokenEOF; return rtfToXamlError; } int rtfStartIndex = _rtfIndex; byte tokenChar = _rtfBytes[_rtfIndex++]; switch (tokenChar) { // GroupStart case (byte)'{': token.Type = RtfTokenType.TokenGroupStart; break; // GroupEnd case (byte)'}': token.Type = RtfTokenType.TokenGroupEnd; break; // Control Word case (byte)'\r': case (byte)'\n': token.Type = RtfTokenType.TokenNewline; break; case (byte)0: token.Type = RtfTokenType.TokenNullChar; break; case (byte)'\\': // Input ends with control sequence if (_rtfIndex >= _rtfBytes.Length) { token.Type = RtfTokenType.TokenInvalid; } // Normal control character else { if (IsControlCharValid(CurByte)) { int controlStartIndex = _rtfIndex; // Set _rtfIndex to get actual control SetRtfIndex(token, controlStartIndex); // Also provide actual control text - useful for unknown controls token.Text = CurrentEncoding.GetString(_rtfBytes, controlStartIndex - 1, _rtfIndex - rtfStartIndex); } // Hex character else if (CurByte == (byte)'\'') { _rtfIndex--; return NextText(token); } // Explicit destination else if (CurByte == '*') { _rtfIndex++; token.Type = RtfTokenType.TokenDestination; } // Quoted control character (be generous) - should be limited to "'-*;\_{|}~" else { token.Type = RtfTokenType.TokenTextSymbol; token.Text = CurrentEncoding.GetString(_rtfBytes, _rtfIndex, 1); _rtfIndex++; } } break; // Text or Picture data default: _rtfIndex--; if (formatState != null && formatState.RtfDestination == RtfDestination.DestPicture) { token.Type = RtfTokenType.TokenPictureData; break; } else { return NextText(token); } } return rtfToXamlError; } internal RtfToXamlError AdvanceForUnicode(long nSkip) { RtfToXamlError rtfToXamlError = RtfToXamlError.None; // Advancing for text is a little tricky RtfToken token = new RtfToken(); while (nSkip > 0 && rtfToXamlError == RtfToXamlError.None) { rtfToXamlError = Next(token, /*formatState:*/null); if (rtfToXamlError != RtfToXamlError.None) break; switch (token.Type) { default: case RtfTokenType.TokenGroupStart: case RtfTokenType.TokenGroupEnd: case RtfTokenType.TokenInvalid: case RtfTokenType.TokenEOF: case RtfTokenType.TokenDestination: Backup(); nSkip = 0; break; case RtfTokenType.TokenControl: if (token.RtfControlWordInfo != null && token.RtfControlWordInfo.Control == RtfControlWord.Ctrl_BIN) { AdvanceForBinary((int)token.Parameter); } nSkip--; break; case RtfTokenType.TokenNewline: // Newlines don't count for skipping purposes break; case RtfTokenType.TokenNullChar: // Null chars don't count for skipping purposes break; case RtfTokenType.TokenText: // We need to skip *bytes*, considering hex-encoded control words as a single byte. // Since Next() returned TokenText, we know that we can safely assume that the next // sequence of bytes is either simple text or hex-encoded bytes. int nEndTextIndex = _rtfIndex; Backup(); while (nSkip > 0 && _rtfIndex < nEndTextIndex) { if (CurByte == '\\') { _rtfIndex += 4; } else { _rtfIndex++; } nSkip--; } break; } } return rtfToXamlError; } internal void AdvanceForBinary(int skip) { if (_rtfIndex + skip < _rtfBytes.Length) { _rtfIndex += skip; } else { _rtfIndex = _rtfBytes.Length - 1; } } // Advance for the image data internal void AdvanceForImageData() { byte tokenChar = _rtfBytes[_rtfIndex]; // Find the end position of image data while (tokenChar != (byte)'}') { tokenChar = _rtfBytes[_rtfIndex++]; } // Move back to the group end char('}') to handle the group end token _rtfIndex--; } // Write the rtf image binary data to the image stream which is the image part of // the container on WpfPayLoad internal void WriteImageData(Stream imageStream, bool isBinary) { byte tokenChar = _rtfBytes[_rtfIndex]; byte tokenNextChar; // Write the rtf image data(binary or hex) to the image stream of WpfPayLoad while (tokenChar != (byte)'{' && tokenChar != (byte)'}' && tokenChar != (byte)'\\') { if (isBinary) { // Write the image binary data directly imageStream.WriteByte(tokenChar); } else { tokenNextChar = _rtfBytes[_rtfIndex + 1]; // Write the image data after convert rtf image hex data to binary data if (IsHex(tokenChar) && IsHex(tokenNextChar)) { byte firstHex = HexToByte(tokenChar); byte secondHex = HexToByte(tokenNextChar); imageStream.WriteByte((byte)(firstHex << 4 | secondHex)); _rtfIndex++; } } _rtfIndex++; tokenChar = _rtfBytes[_rtfIndex]; } } #endregion Internal Properties //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties internal int CodePage { set { if (_currentCodePage != value) { _currentCodePage = value; _currentEncoding = Encoding.GetEncoding(_currentCodePage); } } } internal Encoding CurrentEncoding { get { return _currentEncoding; } } internal byte CurByte { get { return _rtfBytes[_rtfIndex]; } } #endregion Internal Properties //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// Called to process sequence of text and \'hh encoded bytes. /// </summary> /// <param name="token"></param> /// <returns></returns> private RtfToXamlError NextText(RtfToken token) { RtfToXamlError rtfToXamlError = RtfToXamlError.None; _rtfLastIndex = _rtfIndex; token.Empty(); token.Type = RtfTokenType.TokenText; int s = _rtfIndex; int e = s; bool bSawHex = false; while (e < _rtfBytes.Length) { if (IsControl(_rtfBytes[e])) { if (_rtfBytes[e] == (byte)'\\' && e + 3 < _rtfBytes.Length && _rtfBytes[e + 1] == '\'' && IsHex(_rtfBytes[e + 2]) && IsHex(_rtfBytes[e + 3])) { e += 4; bSawHex = true; } else { break; } } else if (_rtfBytes[e] == '\r' || _rtfBytes[e] == '\n' || _rtfBytes[e] == 0) { break; } else { e++; } } if (s == e) { token.Type = RtfTokenType.TokenInvalid; } else { _rtfIndex = e; if (bSawHex) { int i = 0; int n = e - s; byte[] bytes = new byte[n]; while (s < e) { if (_rtfBytes[s] == '\\') { bytes[i++] = (byte)((byte)(HexToByte(_rtfBytes[s + 2]) << 4) + HexToByte(_rtfBytes[s + 3])); s += 4; } else { bytes[i++] = _rtfBytes[s++]; } } token.Text = CurrentEncoding.GetString(bytes, 0, i); } else { token.Text = CurrentEncoding.GetString(_rtfBytes, s, e - s); } } return rtfToXamlError; } private RtfToXamlError Backup() { if (_rtfLastIndex == 0) { // This is a programming error. Debug.Assert(false); return RtfToXamlError.InvalidFormat; } _rtfIndex = _rtfLastIndex; _rtfLastIndex = 0; return RtfToXamlError.None; } private void SetRtfIndex(RtfToken token, int controlStartIndex) { while (_rtfIndex < _rtfBytes.Length && IsControlCharValid(CurByte)) { _rtfIndex++; } int controlLength = _rtfIndex - controlStartIndex; string controlName = CurrentEncoding.GetString(_rtfBytes, controlStartIndex, controlLength); // If control sequence > MAX_CONTROL_LENGTH characters, invalid input. if (controlLength > MAX_CONTROL_LENGTH) { token.Type = RtfTokenType.TokenInvalid; } else { token.Type = RtfTokenType.TokenControl; token.RtfControlWordInfo = RtfControlWordLookup(controlName); if (_rtfIndex < _rtfBytes.Length) { if (CurByte == ' ') { _rtfIndex++; } else if (IsParameterStart(CurByte)) { bool isNegative = false; if (CurByte == '-') { isNegative = true; _rtfIndex++; } long parameter = 0; int paramStartIndex = _rtfIndex; while (_rtfIndex < _rtfBytes.Length && IsParameterFollow(CurByte)) { parameter = (parameter * 10) + (CurByte - '0'); _rtfIndex++; } int paramLength = _rtfIndex - paramStartIndex; // Following space is not part of text input if (_rtfIndex < _rtfBytes.Length && CurByte == ' ') { _rtfIndex++; } if (isNegative) { parameter = -parameter; } // If parameter is too long, invalid input. if (paramLength > MAX_PARAM_LENGTH) { token.Type = RtfTokenType.TokenInvalid; } else { token.Parameter = parameter; } } } } } private bool IsControl(byte controlChar) { return ((controlChar) == (byte)'\\' || (controlChar) == (byte)'{' || (controlChar) == (byte)'}'); } private bool IsControlCharValid(byte controlChar) { return (((controlChar) >= (byte)'a' && (controlChar) <= (byte)'z') || ((controlChar) >= (byte)'A' && (controlChar) <= (byte)'Z')); } private bool IsParameterStart(byte controlChar) { return ((controlChar) == (byte)'-' || ((controlChar) >= (byte)'0' && (controlChar) <= (byte)'9')); } private bool IsParameterFollow(byte controlChar) { return (((controlChar) >= (byte)'0' && (controlChar) <= (byte)'9')); } private bool IsHex(byte controlChar) { return ((controlChar >= (byte)'0' && controlChar <= (byte)'9') || (controlChar >= (byte)'a' && controlChar <= (byte)'f') || (controlChar >= (byte)'A' && controlChar <= (byte)'F')); } private byte HexToByte(byte hexByte) { if (hexByte >= (byte)'0' && hexByte <= (byte)'9') { return (byte)(hexByte - ((byte)'0')); } else if (hexByte >= (byte)'a' && hexByte <= (byte)'f') { return (byte)(10 + hexByte - ((byte)'a')); } else if (hexByte >= (byte)'A' && hexByte <= (byte)'F') { return (byte)(10 + hexByte - ((byte)'A')); } else { return 0; } } private static RtfControlWordInfo RtfControlWordLookup(string controlName) { // Initialize hashtable lock (_rtfControlTableMutex) { if (_rtfControlTable == null) { RtfControlWordInfo[] controlWordInfoTable = RtfControls.ControlTable; _rtfControlTable = new Hashtable(controlWordInfoTable.Length); for (int i = 0; i < controlWordInfoTable.Length; i++) { _rtfControlTable.Add(controlWordInfoTable[i].ControlName, controlWordInfoTable[i]); } } } RtfControlWordInfo cwi = (RtfControlWordInfo)_rtfControlTable[controlName]; if (cwi == null) { // OK, then canonicalize it controlName = controlName.ToLower(CultureInfo.InvariantCulture); cwi = (RtfControlWordInfo)_rtfControlTable[controlName]; } return cwi; } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private byte[] _rtfBytes; private int _rtfIndex; private int _rtfLastIndex; private int _currentCodePage; private Encoding _currentEncoding; private static object _rtfControlTableMutex = new object(); private static Hashtable _rtfControlTable = null; #endregion Private Fields //------------------------------------------------------ // // Private Const // //------------------------------------------------------ #region Private Const private const int MAX_CONTROL_LENGTH = 32; private const int MAX_PARAM_LENGTH = 10; // 10 decimal digits in 32 bits #endregion Private Const } // RtfToXamlLexer }
// 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.Reflection; using System.Collections; using NUnit.Framework; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine; using System.Text.RegularExpressions; using System.Xml; using System.Collections.Generic; namespace Microsoft.Build.UnitTests { [TestFixture] public class NodeManager_Tests { private Engine engine = new Engine(@"c:\"); [Test] public void TestConstructor() { NodeManager nodeManager = new NodeManager(1, false, engine); Assert.IsTrue(nodeManager.TaskExecutionModule.GetExecutionModuleMode() == TaskExecutionModule.TaskExecutionModuleMode.SingleProcMode, "Expected Task Mode to be Single"); nodeManager.UpdateSettings(true, true, true); } [Test] public void TestConstructor2() { NodeManager nodeManager = new NodeManager(1, true, engine); Assert.IsTrue(nodeManager.TaskExecutionModule.GetExecutionModuleMode() == TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, "Expected Task Mode to be SingleProc"); } [Test] public void TestConstructor3() { NodeManager nodeManager = new NodeManager(4, true, engine); Assert.IsTrue(nodeManager.TaskExecutionModule.GetExecutionModuleMode() == TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, "Expected Task Mode to be MultiProc"); } [Test] public void TestConstructor4() { NodeManager nodeManager = new NodeManager(4, false, engine); Assert.IsTrue(nodeManager.TaskExecutionModule.GetExecutionModuleMode() == TaskExecutionModule.TaskExecutionModuleMode.MultiProcFullNodeMode, "Expected Task Mode to be MultiProc"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void RegisterNullNodeProviders() { MockNodeProvider nullNodeProvider = null; NodeManager nodeManager = new NodeManager(1, false, engine); nodeManager.RegisterNodeProvider(nullNodeProvider); } [Test] public void RegisterNodeProviders() { MockNodeProvider ProviderOneNode = new MockNodeProvider(); ProviderOneNode.NodeDescriptions.Add(new MockNodeDescription("Provider One Node One")); MockNodeProvider ProviderThreeNodes = new MockNodeProvider(); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node One")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Two")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Three")); MockNodeProvider ProviderNoNodes = new MockNodeProvider(); // Register a node provider with only one node NodeManager nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderOneNode); // One from node added by node provider, one for the default 0 local node (null as there is no description) Assert.IsTrue(nodeManager.GetNodeDescriptions().Length == 2, "Expected there to be two node Descriptions"); Assert.AreEqual(2, nodeManager.MaxNodeCount); Assert.IsNull(nodeManager.GetNodeDescriptions()[0],"Expected first element to be null"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[1]).NodeDescription, "Provider One Node One", StringComparison.OrdinalIgnoreCase)==0, "Expected node description to be Provider One Node One"); // Register a node provider with more than one node nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderThreeNodes); // THree from node added by node provider, one for the default 0 local node (null as there is no description) Assert.IsTrue(nodeManager.GetNodeDescriptions().Length == 4, "Expected there to be four node Descriptions"); Assert.AreEqual(4, nodeManager.MaxNodeCount); Assert.IsNull(nodeManager.GetNodeDescriptions()[0], "Expected first element to be null"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[1]).NodeDescription, "Provider Two Node One", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node One"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[2]).NodeDescription, "Provider Two Node Two", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node Two"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[3]).NodeDescription, "Provider Two Node Three", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node Three"); // Register a node provider with more than one node nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderOneNode); nodeManager.RegisterNodeProvider(ProviderThreeNodes); // THree from node added by node provider, one for the default 0 local node (null as there is no description) Assert.IsTrue(nodeManager.GetNodeDescriptions().Length == 5, "Expected there to be four node Descriptions"); Assert.AreEqual(5, nodeManager.MaxNodeCount); Assert.IsNull(nodeManager.GetNodeDescriptions()[0], "Expected first element to be null"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[1]).NodeDescription, "Provider One Node One", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider One Node One"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[2]).NodeDescription, "Provider Two Node One", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node One"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[3]).NodeDescription, "Provider Two Node Two", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node Two"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[4]).NodeDescription, "Provider Two Node Three", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node Three"); // Register a node provider with more than one node nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderThreeNodes); nodeManager.RegisterNodeProvider(ProviderOneNode); nodeManager.UpdateSettings(true, false, true); // just need to test this once // THree from node added by node provider, one for the default 0 local node (null as there is no description) Assert.IsTrue(nodeManager.GetNodeDescriptions().Length == 5, "Expected there to be four node Descriptions"); Assert.AreEqual(5, nodeManager.MaxNodeCount); Assert.IsNull(nodeManager.GetNodeDescriptions()[0], "Expected first element to be null"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[1]).NodeDescription, "Provider Two Node One", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node One"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[2]).NodeDescription, "Provider Two Node Two", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node Two"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[3]).NodeDescription, "Provider Two Node Three", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider Two Node Three"); Assert.IsTrue(string.Compare(((MockNodeDescription)nodeManager.GetNodeDescriptions()[4]).NodeDescription, "Provider One Node One", StringComparison.OrdinalIgnoreCase) == 0, "Expected node description to be Provider One Node One"); } [Test] public void TestEnableOutOfProcLogging() { // Register a node provider with more than one node MockNodeProvider ProviderOneNode = new MockNodeProvider(); ProviderOneNode.NodeDescriptions.Add(new MockNodeDescription("Provider One Node One")); NodeManager nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderOneNode); nodeManager.UpdateSettings(true,false, true); // just need to test this once } [Test] public void TestShutdownNodes() { MockNodeProvider ProviderThreeNodes = new MockNodeProvider(); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node One")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Two")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Three")); NodeManager nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderThreeNodes); nodeManager.ShutdownNodes(Node.NodeShutdownLevel.PoliteShutdown); Assert.IsTrue(ProviderThreeNodes.NodeDescriptions.TrueForAll(delegate(INodeDescription o) { return o == null; } ), "Expected all descriptions to be null"); } [Test] public void TestPostBuildResultToNode() { MockNodeProvider ProviderThreeNodes = new MockNodeProvider(); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node One")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Two")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Three")); MockNodeProvider ProviderOneNode = new MockNodeProvider(); ProviderOneNode.NodeDescriptions.Add(new MockNodeDescription("Provider One Node One")); NodeManager nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderThreeNodes); nodeManager.RegisterNodeProvider(ProviderOneNode); nodeManager.PostBuildResultToNode(1, new BuildResult(null, new Hashtable(StringComparer.OrdinalIgnoreCase), false, 2, 1, 6, false, string.Empty, string.Empty, 0, 0, 0)); nodeManager.PostBuildResultToNode(2, new BuildResult(null, new Hashtable(StringComparer.OrdinalIgnoreCase), false, 3, 2, 7, false, string.Empty, string.Empty, 0, 0, 0)); nodeManager.PostBuildResultToNode(3, new BuildResult(null, new Hashtable(StringComparer.OrdinalIgnoreCase), false, 4, 3, 8, false, string.Empty, string.Empty, 0, 0, 0)); nodeManager.PostBuildResultToNode(4, new BuildResult(null, new Hashtable(StringComparer.OrdinalIgnoreCase), false, 5, 4, 9, false, string.Empty, string.Empty, 0, 0, 0)); Assert.IsTrue(ProviderThreeNodes.buildResultsSubmittedToProvider.Count == 3, "Expected there to be three build results in the mock provider"); Assert.IsTrue(ProviderThreeNodes.buildResultsSubmittedToProvider[0].HandleId == 2, "Expected first NodeProxyId to be 2"); Assert.IsTrue(ProviderThreeNodes.buildResultsSubmittedToProvider[1].HandleId == 3, "Expected second NodeProxyId to be 3"); Assert.IsTrue(ProviderThreeNodes.buildResultsSubmittedToProvider[2].HandleId == 4, "Expected third NodeProxyId to be 4"); Assert.IsTrue(ProviderOneNode.buildResultsSubmittedToProvider.Count == 1, "Expected there to be one build results in the mock provider"); Assert.IsTrue(ProviderOneNode.buildResultsSubmittedToProvider[0].HandleId == 5, "Expected first NodeProxyId to be 5"); } [Test] public void TestPostBuildRequestToNode() { MockNodeProvider ProviderThreeNodes = new MockNodeProvider(); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node One")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Two")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Three")); MockNodeProvider ProviderOneNode = new MockNodeProvider(); ProviderOneNode.NodeDescriptions.Add(new MockNodeDescription("Provider One Node One")); NodeManager nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderThreeNodes); nodeManager.RegisterNodeProvider(ProviderOneNode); nodeManager.PostBuildRequestToNode(1, new BuildRequest(1, "ProjectFile", null, new BuildPropertyGroup(), null, 1, false, false)); nodeManager.PostBuildRequestToNode(2, new BuildRequest(2, "ProjectFile", null, new BuildPropertyGroup(), null, 2, false, false)); nodeManager.PostBuildRequestToNode(3, new BuildRequest(3, "ProjectFile", null, new BuildPropertyGroup(), null, 3, false, false)); nodeManager.PostBuildRequestToNode(4, new BuildRequest(4, "ProjectFile", null, new BuildPropertyGroup(), null, 4, false, false)); Assert.IsTrue(ProviderThreeNodes.buildRequestsSubmittedToProvider.Count == 3, "Expected there to be three build results in the mock provider"); Assert.IsTrue(ProviderThreeNodes.buildRequestsSubmittedToProvider[0].HandleId == 1, "Expected first NodeProxyId to be 1"); Assert.IsTrue(ProviderThreeNodes.buildRequestsSubmittedToProvider[1].HandleId == 2, "Expected second NodeProxyId to be 2"); Assert.IsTrue(ProviderThreeNodes.buildRequestsSubmittedToProvider[2].HandleId == 3, "Expected third NodeProxyId to be 3"); Assert.IsTrue(ProviderOneNode.buildRequestsSubmittedToProvider.Count == 1, "Expected there to be one build results in the mock provider"); Assert.IsTrue(ProviderOneNode.buildRequestsSubmittedToProvider[0].HandleId == 4, "Expected first NodeProxyId to be 4"); } [Test] public void TestGetNodeDescriptions() { MockNodeProvider ProviderThreeNodes = new MockNodeProvider(); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node One")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Two")); ProviderThreeNodes.NodeDescriptions.Add(new MockNodeDescription("Provider Two Node Three")); MockNodeProvider ProviderOneNode = new MockNodeProvider(); ProviderOneNode.NodeDescriptions.Add(new MockNodeDescription("Provider One Node One")); NodeManager nodeManager = new NodeManager(1, false, new Engine(@"c:\")); nodeManager.RegisterNodeProvider(ProviderThreeNodes); nodeManager.RegisterNodeProvider(ProviderOneNode); // Cant assert the contents yet as there is no definition inside of a INodeDescription interface Assert.IsTrue(nodeManager.GetNodeDescriptions().Length == 5, "Expected there to be five descriptions"); } } /// <summary> /// Dont know what node description is, so I just set it to something for now /// </summary> internal class MockNodeDescription:INodeDescription { string nodeDescription; public string NodeDescription { get { return nodeDescription; } } internal MockNodeDescription(string description) { nodeDescription = description; } } internal class MockNodeProvider:INodeProvider { string initConfiguration; IEngineCallback initEngineCallback; List<INodeDescription> nodeDescriptions; BuildPropertyGroup parentGlobalProperties; ToolsetDefinitionLocations toolsetSearchLocations; string startDirectory; internal List<INodeDescription> NodeDescriptions { get { return nodeDescriptions; } set { nodeDescriptions = value; } } internal List<BuildRequest> buildRequestsSubmittedToProvider; internal List<BuildResult> buildResultsSubmittedToProvider; #region INodeProvider Members internal MockNodeProvider() { nodeDescriptions = new List<INodeDescription>(); buildRequestsSubmittedToProvider = new List<BuildRequest>(); buildResultsSubmittedToProvider = new List<BuildResult>(); } void INodeProvider.Initialize(string configuration, IEngineCallback engineCallback, BuildPropertyGroup parentGlobalProperties, ToolsetDefinitionLocations toolsetSearchLocations, string startDirectory) { this.initConfiguration = configuration; this.initEngineCallback = engineCallback; this.parentGlobalProperties = parentGlobalProperties; this.toolsetSearchLocations = toolsetSearchLocations; this.startDirectory = startDirectory; } INodeDescription[] INodeProvider.QueryNodeDescriptions() { return nodeDescriptions.ToArray(); } void INodeProvider.RegisterNodeLogger(LoggerDescription description ) { if ( description == null ) { throw new ArgumentException("Logger description should be non-null"); } } void INodeProvider.PostBuildRequestToNode(int nodeIndex, BuildRequest buildRequest) { if (nodeIndex > nodeDescriptions.Count) { throw new ArgumentException("Node index is out of range"); } buildRequestsSubmittedToProvider.Add(buildRequest); } void INodeProvider.PostBuildResultToNode(int nodeIndex, BuildResult buildResultToPost) { if (nodeIndex > nodeDescriptions.Count) { throw new ArgumentException("Node index is out of range"); } buildResultsSubmittedToProvider.Add(buildResultToPost); } void INodeProvider.ShutdownNodes(Node.NodeShutdownLevel nodeShutdownLevel) { for (int i = 0; i < NodeDescriptions.Count; i++) { NodeDescriptions[i] = null; } } #endregion #region INodeProvider Members public void UpdateSettings(bool enableOutOfProcLogging, bool enableOnlyLogCriticalEvents, bool useBreadthFirstTraversalSetting) { } #endregion #region INodeProvider Members public void AssignNodeIdentifiers(int[] nodeIdentifiers) { } public void RequestNodeStatus(int nodeIndex, int requestId) { } public void PostIntrospectorCommand(int nodeIndex, TargetInProgessState child, TargetInProgessState parent) { } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ProfilesOperations operations. /// </summary> public partial interface IProfilesOperations { /// <summary> /// Creates a profile within a Hub, or updates an existing profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete Profile type operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ProfileResourceFormat>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, ProfileResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the specified profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ProfileResourceFormat>> GetWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a profile within a hub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all profile in the hub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ProfileResourceFormat>>> ListByHubWithHttpMessagesAsync(string resourceGroupName, string hubName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the KPIs that enrich the profile Type identified by the /// supplied name. Enrichment happens through participants of the /// Interaction on an Interaction KPI and through Relationships for /// Profile KPIs. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IList<KpiDefinition>>> GetEnrichingKpisWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a profile within a Hub, or updates an existing profile. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/delete Profile type operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ProfileResourceFormat>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, ProfileResourceFormat parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a profile within a hub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='hubName'> /// The name of the hub. /// </param> /// <param name='profileName'> /// The name of the profile. /// </param> /// <param name='localeCode'> /// Locale of profile to retrieve, default is en-us. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string hubName, string profileName, string localeCode = "en-us", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all profile in the hub. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<ProfileResourceFormat>>> ListByHubNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using Xunit; using FluentAssertions; using Microsoft.DotNet.CoreSetup.Test; using System.Collections.Generic; using Microsoft.DotNet.Cli.Build; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.NativeHostApis { public class GivenThatICareAboutNativeHostApis : IClassFixture<GivenThatICareAboutNativeHostApis.SharedTestState> { private SharedTestState sharedTestState; public GivenThatICareAboutNativeHostApis(GivenThatICareAboutNativeHostApis.SharedTestState fixture) { sharedTestState = fixture; } [Fact] public void Muxer_activation_of_Publish_Output_Portable_DLL_hostfxr_get_native_search_directories_Succeeds() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; var dotnetLocation = Path.Combine(dotnet.BinPath, $"dotnet{fixture.ExeExtension}"); string[] args = { "hostfxr_get_native_search_directories", dotnetLocation, appDll }; dotnet.Exec(appDll, args) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_get_native_search_directories:Success") .And .HaveStdOutContaining("hostfxr_get_native_search_directories buffer:[" + dotnet.GreatestVersionSharedFxPath); } [Fact] public void Breadcrumb_thread_finishes_when_app_closes_normally() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("CORE_BREADCRUMBS", sharedTestState.BreadcrumbLocation) .EnvironmentVariable("COREHOST_TRACE", "1") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("Hello World") .And .HaveStdErrContaining("Waiting for breadcrumb thread to exit..."); } [Fact] public void Breadcrumb_thread_does_not_finish_when_app_has_unhandled_exception() { var fixture = sharedTestState.PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture.Copy(); var dotnet = fixture.BuiltDotnet; var appDll = fixture.TestProject.AppDll; dotnet.Exec(appDll) .EnvironmentVariable("CORE_BREADCRUMBS", sharedTestState.BreadcrumbLocation) .EnvironmentVariable("COREHOST_TRACE", "1") .CaptureStdOut() .CaptureStdErr() .Execute(fExpectedToFail: true) .Should() .Fail() .And .HaveStdErrContaining("Unhandled Exception: System.Exception: Goodbye World") .And // The breadcrumb thread does not wait since destructors are not called when an exception is thrown. // However, destructors will be called when the caller (such as a custom host) is compiled with SEH Exceptions (/EHa) and has a try\catch. // Todo: add a native host test app so we can verify this behavior. .NotHaveStdErrContaining("Waiting for breadcrumb thread to exit..."); } private class SdkResolutionFixture { private readonly TestProjectFixture _fixture; public DotNetCli Dotnet => _fixture.BuiltDotnet; public string AppDll => _fixture.TestProject.AppDll; public string ExeDir => Path.Combine(_fixture.TestProject.ProjectDirectory, "ed"); public string ProgramFiles => Path.Combine(ExeDir, "pf"); public string WorkingDir => Path.Combine(_fixture.TestProject.ProjectDirectory, "wd"); public string GlobalSdkDir => Path.Combine(ProgramFiles, "dotnet", "sdk"); public string LocalSdkDir => Path.Combine(ExeDir, "sdk"); public string GlobalJson => Path.Combine(WorkingDir, "global.json"); public string[] GlobalSdks = new[] { "4.5.6", "1.2.3", "2.3.4-preview" }; public string[] LocalSdks = new[] { "0.1.2", "5.6.7-preview", "1.2.3" }; public SdkResolutionFixture(SharedTestState state) { _fixture = state.PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Copy(); Directory.CreateDirectory(WorkingDir); // start with an empty global.json, it will be ignored, but prevent one lying on disk // on a given machine from impacting the test. File.WriteAllText(GlobalJson, "{}"); foreach (string sdk in GlobalSdks) { Directory.CreateDirectory(Path.Combine(GlobalSdkDir, sdk)); } foreach (string sdk in LocalSdks) { Directory.CreateDirectory(Path.Combine(LocalSdkDir, sdk)); } } } [Fact] public void Hostfxr_get_available_sdks_with_multilevel_lookup() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // multilevel lookup is not supported on non-Windows return; } var f = new SdkResolutionFixture(sharedTestState); // With multi-level lookup (windows onnly): get local and global sdks sorted by ascending version, // with global sdk coming before local sdk when versions are equal string expectedList = string.Join(';', new[] { Path.Combine(f.LocalSdkDir, "0.1.2"), Path.Combine(f.GlobalSdkDir, "1.2.3"), Path.Combine(f.LocalSdkDir, "1.2.3"), Path.Combine(f.GlobalSdkDir, "2.3.4-preview"), Path.Combine(f.GlobalSdkDir, "4.5.6"), Path.Combine(f.LocalSdkDir, "5.6.7-preview"), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_get_available_sdks", f.ExeDir }) .EnvironmentVariable("TEST_MULTILEVEL_LOOKUP_PROGRAM_FILES", f.ProgramFiles) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_get_available_sdks:Success") .And .HaveStdOutContaining($"hostfxr_get_available_sdks sdks:[{expectedList}]"); } [Fact] public void Hostfxr_get_available_sdks_without_multilevel_lookup() { // Without multi-level lookup: get only sdks sorted by ascending version var f = new SdkResolutionFixture(sharedTestState); string expectedList = string.Join(';', new[] { Path.Combine(f.LocalSdkDir, "0.1.2"), Path.Combine(f.LocalSdkDir, "1.2.3"), Path.Combine(f.LocalSdkDir, "5.6.7-preview"), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_get_available_sdks", f.ExeDir }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_get_available_sdks:Success") .And .HaveStdOutContaining($"hostfxr_get_available_sdks sdks:[{expectedList}]"); } [Fact] public void Hostfxr_resolve_sdk2_without_global_json_or_flags() { // with no global.json and no flags, pick latest SDK var f = new SdkResolutionFixture(sharedTestState); string expectedData = string.Join(';', new[] { ("resolved_sdk_dir", Path.Combine(f.LocalSdkDir, "5.6.7-preview")), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_resolve_sdk2", f.ExeDir, f.WorkingDir, "0" }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_resolve_sdk2:Success") .And .HaveStdOutContaining($"hostfxr_resolve_sdk2 data:[{expectedData}]"); } [Fact] public void Hostfxr_resolve_sdk2_without_global_json_and_disallowing_previews() { // Without global.json and disallowing previews, pick latest non-preview var f = new SdkResolutionFixture(sharedTestState); string expectedData = string.Join(';', new[] { ("resolved_sdk_dir", Path.Combine(f.LocalSdkDir, "1.2.3")) }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_resolve_sdk2", f.ExeDir, f.WorkingDir, "disallow_prerelease" }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_resolve_sdk2:Success") .And .HaveStdOutContaining($"hostfxr_resolve_sdk2 data:[{expectedData}]"); } [Fact] public void Hostfxr_resolve_sdk2_with_global_json_and_disallowing_previews() { // With global.json specifying a preview, roll forward to preview // since flag has no impact if global.json specifies a preview. // Also check that global.json that impacted resolution is reported. var f = new SdkResolutionFixture(sharedTestState); File.WriteAllText(f.GlobalJson, "{ \"sdk\": { \"version\": \"5.6.6-preview\" } }"); string expectedData = string.Join(';', new[] { ("resolved_sdk_dir", Path.Combine(f.LocalSdkDir, "5.6.7-preview")), ("global_json_path", f.GlobalJson), }); f.Dotnet.Exec(f.AppDll, new[] { "hostfxr_resolve_sdk2", f.ExeDir, f.WorkingDir, "disallow_prerelease" }) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdOutContaining("hostfxr_resolve_sdk2:Success") .And .HaveStdOutContaining($"hostfxr_resolve_sdk2 data:[{expectedData}]"); } public class SharedTestState : IDisposable { public TestProjectFixture PreviouslyPublishedAndRestoredPortableApiTestProjectFixture { get; set; } public TestProjectFixture PreviouslyPublishedAndRestoredPortableAppProjectFixture { get; set; } public TestProjectFixture PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture { get; set; } public RepoDirectoriesProvider RepoDirectories { get; set; } public string BreadcrumbLocation { get; set; } public SharedTestState() { RepoDirectories = new RepoDirectoriesProvider(); PreviouslyPublishedAndRestoredPortableApiTestProjectFixture = new TestProjectFixture("HostApiInvokerApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .BuildProject(); PreviouslyPublishedAndRestoredPortableAppProjectFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture = new TestProjectFixture("PortableAppWithException", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .PublishProject(); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { BreadcrumbLocation = Path.Combine( PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture.TestProject.OutputDirectory, "opt", "corebreadcrumbs"); Directory.CreateDirectory(BreadcrumbLocation); // On non-Windows, we can't just P/Invoke to already loaded hostfxr, so copy it next to the app dll. var fixture = PreviouslyPublishedAndRestoredPortableApiTestProjectFixture; var hostfxr = Path.Combine( fixture.BuiltDotnet.GreatestVersionHostFxrPath, $"{fixture.SharedLibraryPrefix}hostfxr{fixture.SharedLibraryExtension}"); File.Copy( hostfxr, Path.GetDirectoryName(fixture.TestProject.AppDll)); } } public void Dispose() { PreviouslyPublishedAndRestoredPortableApiTestProjectFixture.Dispose(); PreviouslyPublishedAndRestoredPortableAppProjectFixture.Dispose(); PreviouslyPublishedAndRestoredPortableAppWithExceptionProjectFixture.Dispose(); } } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Text; using gov.va.medora; // for StringTestObject using NUnit.Framework; using Spring.Context; using Spring.Context.Support; using Common.Logging; using gov.va.medora.mdo.exceptions; namespace gov.va.medora.utils { [TestFixture] public class DateUtilsTest { private static readonly ILog LOG = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); [Test] public void testIsLeapYear() { Assert.IsTrue(DateUtils.isLeapYear(2000)); Assert.IsFalse(DateUtils.isLeapYear(2001)); Assert.IsTrue(DateUtils.isLeapYear(2012)); Assert.IsTrue(DateUtils.isLeapYear(6024)); Assert.IsFalse(DateUtils.isLeapYear(0)); } [Test] public void testIsValidMonth() { Assert.IsFalse(DateUtils.isValidMonth(-12)); Assert.IsFalse(DateUtils.isValidMonth(13)); Assert.IsTrue(DateUtils.isValidMonth(1)); Assert.IsTrue(DateUtils.isValidMonth(2)); Assert.IsTrue(DateUtils.isValidMonth(3)); Assert.IsTrue(DateUtils.isValidMonth(4)); Assert.IsTrue(DateUtils.isValidMonth(5)); Assert.IsTrue(DateUtils.isValidMonth(6)); Assert.IsTrue(DateUtils.isValidMonth(7)); Assert.IsTrue(DateUtils.isValidMonth(8)); Assert.IsTrue(DateUtils.isValidMonth(9)); Assert.IsTrue(DateUtils.isValidMonth(10)); Assert.IsTrue(DateUtils.isValidMonth(11)); Assert.IsTrue(DateUtils.isValidMonth(12)); } [Test] public void testIsValidDay() { Assert.IsFalse(DateUtils.isValidDay(1900, 2, 0)); Assert.IsFalse(DateUtils.isValidDay(1900, 2, 32)); Assert.IsFalse(DateUtils.isValidDay(1900, 4, 31)); Assert.IsTrue(DateUtils.isValidDay(1900, 1, 30)); Assert.IsFalse(DateUtils.isValidDay(1900, 2, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 3, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 4, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 5, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 6, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 7, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 8, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 9, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 10, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 11, 30)); Assert.IsTrue(DateUtils.isValidDay(1900, 12, 30)); Assert.IsFalse(DateUtils.isValidDay(2001, 2, 29)); Assert.IsTrue(DateUtils.isValidDay(2004, 2, 29)); } [Test] public void testIs30DayMonth() { Assert.IsTrue(DateUtils.is30DayMonth(4)); Assert.IsTrue(DateUtils.is30DayMonth(6)); Assert.IsTrue(DateUtils.is30DayMonth(9)); Assert.IsTrue(DateUtils.is30DayMonth(11)); Assert.IsFalse(DateUtils.is30DayMonth(1)); Assert.IsFalse(DateUtils.is30DayMonth(2)); Assert.IsFalse(DateUtils.is30DayMonth(3)); Assert.IsFalse(DateUtils.is30DayMonth(5)); Assert.IsFalse(DateUtils.is30DayMonth(7)); Assert.IsFalse(DateUtils.is30DayMonth(8)); Assert.IsFalse(DateUtils.is30DayMonth(10)); Assert.IsFalse(DateUtils.is30DayMonth(12)); } [Test] public void testIsWellFormedDatePart() { Assert.IsFalse(DateUtils.isWellFormedDatePart("")); Assert.IsFalse(DateUtils.isWellFormedDatePart(null)); Assert.IsFalse(DateUtils.isWellFormedDatePart("09121978")); Assert.IsFalse(DateUtils.isWellFormedDatePart("1978")); Assert.IsFalse(DateUtils.isWellFormedDatePart("1978052212")); Assert.IsFalse(DateUtils.isWellFormedDatePart("theeight")); Assert.IsFalse(DateUtils.isWellFormedDatePart("1978.0912.")); Assert.IsFalse(DateUtils.isWellFormedDatePart("19782112")); // bad month Assert.IsFalse(DateUtils.isWellFormedDatePart("19782112")); // bad day Assert.IsFalse(DateUtils.isWellFormedDatePart("19780499")); // too many days Assert.IsFalse(DateUtils.isWellFormedDatePart("19780431")); // too many days Assert.IsFalse(DateUtils.isWellFormedDatePart("19780631")); // too many days Assert.IsFalse(DateUtils.isWellFormedDatePart("19780931")); // too many days Assert.IsFalse(DateUtils.isWellFormedDatePart("19781131")); // too many days Assert.IsFalse(DateUtils.isWellFormedDatePart("19780230")); // too many days Assert.IsFalse(DateUtils.isWellFormedDatePart("19780229")); // not leap year Assert.IsTrue(DateUtils.isWellFormedDatePart("19780912")); Assert.IsTrue(DateUtils.isWellFormedDatePart("19780912.")); Assert.IsTrue(DateUtils.isWellFormedDatePart("19800229")); } [Test] public void testIsWellFormedTimePart() { Assert.IsTrue(DateUtils.isWellFormedTimePart("asdf")); Assert.IsFalse(DateUtils.isWellFormedTimePart("200405.221234")); Assert.IsTrue(DateUtils.isWellFormedTimePart("20040522.1234")); Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.12345678")); Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.12345678")); Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.asdfgh")); Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.443456")); Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.129956")); Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.123499")); Assert.IsTrue(DateUtils.isWellFormedTimePart("20040522.123456")); } [Test] public void testIsWellFormedUtcDateTime() { Assert.IsTrue(DateUtils.isWellFormedUtcDateTime("20040522.123456")); Assert.IsFalse(DateUtils.isWellFormedUtcDateTime("200405.123456")); Assert.IsTrue(DateUtils.isWellFormedUtcDateTime("20040522.1234")); } [Test] public void testTrimSeconds() { Assert.AreEqual("20040522123456", DateUtils.trimSeconds("20040522123456")); Assert.AreEqual("20040522.1234", DateUtils.trimSeconds("20040522.1234")); Assert.AreEqual("20040522.1234", DateUtils.trimSeconds("20040522.123456")); } [Test] public void testZeroSeconds() { Assert.AreEqual("20040522123456.000000", DateUtils.zeroSeconds("20040522123456")); Assert.AreEqual("20040522.123400", DateUtils.zeroSeconds("20040522.1234")); Assert.AreEqual("20040522.123400", DateUtils.zeroSeconds("20040522.123456")); } [Test] [ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid 'from' date: ")] public void testIsValidDateRangesNull1stArg() { DateUtils.CheckDateRange(null, "20070102"); } [Test] [ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid 'to' date: ")] public void testIsValidDateRangesNull2ndArg() { DateUtils.CheckDateRange("20070102", null); } [Test] [ExpectedException(typeof(MdoException), "Invalid 'from' date: abcd")] public void testIsValidDateRangesBadFrom() { DateUtils.CheckDateRange("abcd", "20070102"); } [Test] [ExpectedException(typeof(MdoException), "Invalid 'to' date: abcd")] public void testIsValidDateRangesBadTo() { DateUtils.CheckDateRange("20070102", "abcd"); } [Test] public void testValidDateRanges() { DateUtils.CheckDateRange("20070102", "20080102"); DateUtils.CheckDateRange("20070102.012345", "20080102"); DateUtils.CheckDateRange("20070102", "20080102.012345"); DateUtils.CheckDateRange("20070102.012345", "20080102.012345"); } [Test] [ExpectedException(typeof(InvalidDateRangeException), "Invalid date range")] public void testInvalidDateRange_starttimeBeforeEnd() { DateUtils.CheckDateRange("20070102.022345", "20070102.012345"); } [Test] [ExpectedException(typeof(InvalidDateRangeException), "Invalid date range")] public void testInvalidDateRange_startBeforeEnd() { DateUtils.CheckDateRange("20070103", "20070102"); } [Test] [ExpectedException(typeof(InvalidDateRangeException), "Invalid date range")] public void testInvalidDateRange_startEqualsEnd() { DateUtils.CheckDateRange("20070102", "20070102"); //same date } [Test] public void TestIsoDateStringToDateTime() { String dateString = "20070102"; DateTime testTime = DateUtils.IsoDateStringToDateTime(dateString); Assert.AreEqual(new DateTime(2007, 01, 02), testTime, "expect new DateTime of 2007/01/02"); } [Test] [Category("real-sites")] public void TestIsoDateStringToDateTimeWithHours() { String dateString = "20070102.123456789"; DateTime testTime = DateUtils.IsoDateStringToDateTime(dateString); Assert.AreEqual(new DateTime(2007, 01, 02,12,34,56,789), testTime, "unexpected DateTime"); } [Test] [Category("real-sites")] public void TestIsoDateStringToDateTimeWithHoursMissingSeconds() { String dateString = "20070102.123400789"; DateTime testTime = DateUtils.IsoDateStringToDateTime(dateString); Assert.AreEqual(new DateTime(2007, 01, 02, 12, 34, 0, 789), testTime, "unexpected DateTime"); } [Test] [Category("unit-only")] public void TestTrimTime_NormalDateTime() { string DATE_TIME = "20091123.123456"; Assert.AreEqual("20091123", DateUtils.trimTime(DATE_TIME)); } [Test] [Category("unit-only")] public void TestTrimTime_NormalDateOnly() { string DATE_TIME = "20091123"; Assert.AreEqual("20091123", DateUtils.trimTime(DATE_TIME)); } /// <summary>Function will return an empty date if nothing present before the '.' separator /// </summary> [Test] [Category("unit-only")] public void TestTrimTime_SeparatorAndTimeOnly() { string DATE_TIME = ".123456"; Assert.AreEqual("", DateUtils.trimTime(DATE_TIME)); } } }
// 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.Diagnostics; using System.Globalization; namespace System.DirectoryServices.AccountManagement { #if TESTHOOK public class PasswordInfo #else internal class PasswordInfo #endif { // // Properties exposed to the public through AuthenticablePrincipal // // LastPasswordSet private Nullable<DateTime> _lastPasswordSet = null; private LoadState _lastPasswordSetLoaded = LoadState.NotSet; public Nullable<DateTime> LastPasswordSet { get { return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastPasswordSet, PropertyNames.PwdInfoLastPasswordSet, ref _lastPasswordSetLoaded); } } // LastBadPasswordAttempt private Nullable<DateTime> _lastBadPasswordAttempt = null; private LoadState _lastBadPasswordAttemptLoaded = LoadState.NotSet; public Nullable<DateTime> LastBadPasswordAttempt { get { return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastBadPasswordAttempt, PropertyNames.PwdInfoLastBadPasswordAttempt, ref _lastBadPasswordAttemptLoaded); } } // PasswordNotRequired private bool _passwordNotRequired = false; private LoadState _passwordNotRequiredChanged = LoadState.NotSet; public bool PasswordNotRequired { get { return _owningPrincipal.HandleGet<bool>(ref _passwordNotRequired, PropertyNames.PwdInfoPasswordNotRequired, ref _passwordNotRequiredChanged); } set { _owningPrincipal.HandleSet<bool>(ref _passwordNotRequired, value, ref _passwordNotRequiredChanged, PropertyNames.PwdInfoPasswordNotRequired); } } // PasswordNeverExpires private bool _passwordNeverExpires = false; private LoadState _passwordNeverExpiresChanged = LoadState.NotSet; public bool PasswordNeverExpires { get { return _owningPrincipal.HandleGet<bool>(ref _passwordNeverExpires, PropertyNames.PwdInfoPasswordNeverExpires, ref _passwordNeverExpiresChanged); } set { _owningPrincipal.HandleSet<bool>(ref _passwordNeverExpires, value, ref _passwordNeverExpiresChanged, PropertyNames.PwdInfoPasswordNeverExpires); } } // UserCannotChangePassword private bool _cannotChangePassword = false; private LoadState _cannotChangePasswordChanged = LoadState.NotSet; private bool _cannotChangePasswordRead = false; // For this property we are doing an on demand load. The store will not load this property when load is called beacuse // the loading of this property is perf intensive. HandleGet still needs to be called to load the other object properties if // needed. We read the status directly from the store and then cache it for use later. public bool UserCannotChangePassword { get { _owningPrincipal.HandleGet<bool>(ref _cannotChangePassword, PropertyNames.PwdInfoCannotChangePassword, ref _cannotChangePasswordChanged); if ((_cannotChangePasswordChanged != LoadState.Changed) && !_cannotChangePasswordRead && !_owningPrincipal.unpersisted) { _cannotChangePassword = _owningPrincipal.GetStoreCtxToUse().AccessCheck(_owningPrincipal, PrincipalAccessMask.ChangePassword); _cannotChangePasswordRead = true; } return _cannotChangePassword; } set { _owningPrincipal.HandleSet<bool>(ref _cannotChangePassword, value, ref _cannotChangePasswordChanged, PropertyNames.PwdInfoCannotChangePassword); } } // AllowReversiblePasswordEncryption private bool _allowReversiblePasswordEncryption = false; private LoadState _allowReversiblePasswordEncryptionChanged = LoadState.NotSet; public bool AllowReversiblePasswordEncryption { get { return _owningPrincipal.HandleGet<bool>(ref _allowReversiblePasswordEncryption, PropertyNames.PwdInfoAllowReversiblePasswordEncryption, ref _allowReversiblePasswordEncryptionChanged); } set { _owningPrincipal.HandleSet<bool>(ref _allowReversiblePasswordEncryption, value, ref _allowReversiblePasswordEncryptionChanged, PropertyNames.PwdInfoAllowReversiblePasswordEncryption); } } // // Methods exposed to the public through AuthenticablePrincipal // private string _storedNewPassword = null; public void SetPassword(string newPassword) { if (newPassword == null) throw new ArgumentNullException("newPassword"); // If we're not persisted, we just save up the change until we're Saved if (_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "SetPassword: saving until persisted"); _storedNewPassword = newPassword; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "SetPassword: sending request"); _owningPrincipal.GetStoreCtxToUse().SetPassword(_owningPrincipal, newPassword); } } public void ChangePassword(string oldPassword, string newPassword) { if (oldPassword == null) throw new ArgumentNullException("oldPassword"); if (newPassword == null) throw new ArgumentNullException("newPassword"); // While you can reset the password on an unpersisted principal (and it will be used as the initial password // for the pricipal), changing the password on a principal that doesn't exist yet doesn't make sense if (_owningPrincipal.unpersisted) throw new InvalidOperationException(SR.PasswordInfoChangePwdOnUnpersistedPrinc); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ChangePassword: sending request"); _owningPrincipal.GetStoreCtxToUse().ChangePassword(_owningPrincipal, oldPassword, newPassword); } private bool _expirePasswordImmediately = false; public void ExpirePasswordNow() { // If we're not persisted, we just save up the change until we're Saved if (_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ExpirePasswordNow: saving until persisted"); _expirePasswordImmediately = true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ExpirePasswordNow: sending request"); _owningPrincipal.GetStoreCtxToUse().ExpirePassword(_owningPrincipal); } } public void RefreshExpiredPassword() { // If we're not persisted, we undo the expiration we saved up when ExpirePasswordNow was called (if it was). if (_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "RefreshExpiredPassword: saving until persisted"); _expirePasswordImmediately = false; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "RefreshExpiredPassword: sending request"); _owningPrincipal.GetStoreCtxToUse().UnexpirePassword(_owningPrincipal); } } // // Internal constructor // internal PasswordInfo(AuthenticablePrincipal principal) { _owningPrincipal = principal; } // // Private implementation // private AuthenticablePrincipal _owningPrincipal; /* // These methods implement the logic shared by all the get/set accessors for the internal properties T HandleGet<T>(ref T currentValue, string name) { // Check that we actually support this propery in our store //this.owningPrincipal.CheckSupportedProperty(name); return currentValue; } void HandleSet<T>(ref T currentValue, T newValue, ref bool changed, string name) { // Check that we actually support this propery in our store //this.owningPrincipal.CheckSupportedProperty(name); currentValue = newValue; changed = true; } */ // // Load/Store // // // Loading with query results // internal void LoadValueIntoProperty(string propertyName, object value) { if (value != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString()); } switch (propertyName) { case (PropertyNames.PwdInfoLastPasswordSet): _lastPasswordSet = (Nullable<DateTime>)value; _lastPasswordSetLoaded = LoadState.Loaded; break; case (PropertyNames.PwdInfoLastBadPasswordAttempt): _lastBadPasswordAttempt = (Nullable<DateTime>)value; _lastBadPasswordAttemptLoaded = LoadState.Loaded; break; case (PropertyNames.PwdInfoPasswordNotRequired): _passwordNotRequired = (bool)value; _passwordNotRequiredChanged = LoadState.Loaded; break; case (PropertyNames.PwdInfoPasswordNeverExpires): _passwordNeverExpires = (bool)value; _passwordNeverExpiresChanged = LoadState.Loaded; break; case (PropertyNames.PwdInfoCannotChangePassword): _cannotChangePassword = (bool)value; _cannotChangePasswordChanged = LoadState.Loaded; break; case (PropertyNames.PwdInfoAllowReversiblePasswordEncryption): _allowReversiblePasswordEncryption = (bool)value; _allowReversiblePasswordEncryptionChanged = LoadState.Loaded; break; default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "PasswordInfo.LoadValueIntoProperty: fell off end looking for {0}", propertyName)); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.PwdInfoPasswordNotRequired): return _passwordNotRequiredChanged == LoadState.Changed; case (PropertyNames.PwdInfoPasswordNeverExpires): return _passwordNeverExpiresChanged == LoadState.Changed; case (PropertyNames.PwdInfoCannotChangePassword): return _cannotChangePasswordChanged == LoadState.Changed; case (PropertyNames.PwdInfoAllowReversiblePasswordEncryption): return _allowReversiblePasswordEncryptionChanged == LoadState.Changed; case (PropertyNames.PwdInfoPassword): return (_storedNewPassword != null); case (PropertyNames.PwdInfoExpireImmediately): return (_expirePasswordImmediately != false); default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "PasswordInfo.GetChangeStatusForProperty: fell off end looking for {0}", propertyName)); return false; } } // Given a property name, returns the current value for the property. internal object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.PwdInfoPasswordNotRequired): return _passwordNotRequired; case (PropertyNames.PwdInfoPasswordNeverExpires): return _passwordNeverExpires; case (PropertyNames.PwdInfoCannotChangePassword): return _cannotChangePassword; case (PropertyNames.PwdInfoAllowReversiblePasswordEncryption): return _allowReversiblePasswordEncryption; case (PropertyNames.PwdInfoPassword): return _storedNewPassword; case (PropertyNames.PwdInfoExpireImmediately): return _expirePasswordImmediately; default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "PasswordInfo.GetValueForProperty: fell off end looking for {0}", propertyName)); return null; } } // Reset all change-tracking status for all properties on the object to "unchanged". internal void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ResetAllChangeStatus"); _passwordNotRequiredChanged = (_passwordNotRequiredChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _passwordNeverExpiresChanged = (_passwordNeverExpiresChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _cannotChangePasswordChanged = (_cannotChangePasswordChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _allowReversiblePasswordEncryptionChanged = (_allowReversiblePasswordEncryptionChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _storedNewPassword = null; _expirePasswordImmediately = false; } } }
using System; using System.Diagnostics; using Raksha.Crypto.Parameters; namespace Raksha.Crypto { /** * A wrapper class that allows block ciphers to be used to process data in * a piecemeal fashion. The BufferedBlockCipher outputs a block only when the * buffer is full and more data is being added, or on a doFinal. * <p> * Note: in the case where the underlying cipher is either a CFB cipher or an * OFB one the last block may not be a multiple of the block size. * </p> */ public class BufferedBlockCipher : BufferedCipherBase { internal byte[] buf; internal int bufOff; internal bool forEncryption; internal IBlockCipher cipher; /** * constructor for subclasses */ protected BufferedBlockCipher() { } /** * Create a buffered block cipher without padding. * * @param cipher the underlying block cipher this buffering object wraps. * false otherwise. */ public BufferedBlockCipher( IBlockCipher cipher) { if (cipher == null) throw new ArgumentNullException("cipher"); this.cipher = cipher; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } public override string AlgorithmName { get { return cipher.AlgorithmName; } } /** * initialise the cipher. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ // Note: This doubles as the Init in the event that this cipher is being used as an IWrapper public override void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; if (parameters is ParametersWithRandom) { parameters = ((ParametersWithRandom) parameters).Parameters; } Reset(); cipher.Init(forEncryption, parameters); } /** * return the blocksize for the underlying cipher. * * @return the blocksize for the underlying cipher. */ public override int GetBlockSize() { return cipher.GetBlockSize(); } /** * return the size of the output buffer required for an update * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update * with len bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; return total - leftOver; } /** * return the size of the output buffer required for an update plus a * doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update and doFinal * with len bytes of input. */ public override int GetOutputSize( int length) { // Note: Can assume IsPartialBlockOkay is true for purposes of this calculation return length + bufOff; } /** * process a single byte, producing an output block if neccessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { buf[bufOff++] = input; if (bufOff == buf.Length) { if ((outOff + buf.Length) > output.Length) throw new DataLengthException("output buffer too short"); bufOff = 0; return cipher.ProcessBlock(buf, 0, output, outOff); } return 0; } public override byte[] ProcessByte( byte input) { int outLength = GetUpdateOutputSize(1); byte[] outBytes = outLength > 0 ? new byte[outLength] : null; int pos = ProcessByte(input, outBytes, 0); if (outLength > 0 && pos < outLength) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } public override byte[] ProcessBytes( byte[] input, int inOff, int length) { if (input == null) throw new ArgumentNullException("input"); if (length < 1) return null; int outLength = GetUpdateOutputSize(length); byte[] outBytes = outLength > 0 ? new byte[outLength] : null; int pos = ProcessBytes(input, inOff, length, outBytes, 0); if (outLength > 0 && pos < outLength) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param len the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if (length < 1) { if (length < 0) throw new ArgumentException("Can't have a negative input length!"); return 0; } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if (outLength > 0) { if ((outOff + outLength) > output.Length) { throw new DataLengthException("output buffer too short"); } } int resultLen = 0; int gapLen = buf.Length - bufOff; if (length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; inOff += gapLen; while (length > buf.Length) { resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; if (bufOff == buf.Length) { resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); bufOff = 0; } return resultLen; } public override byte[] DoFinal() { byte[] outBytes = EmptyBuffer; int length = GetOutputSize(0); if (length > 0) { outBytes = new byte[length]; int pos = DoFinal(outBytes, 0); if (pos < outBytes.Length) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } public override byte[] DoFinal( byte[] input, int inOff, int inLen) { if (input == null) throw new ArgumentNullException("input"); int length = GetOutputSize(inLen); byte[] outBytes = EmptyBuffer; if (length > 0) { outBytes = new byte[length]; int pos = (inLen > 0) ? ProcessBytes(input, inOff, inLen, outBytes, 0) : 0; pos += DoFinal(outBytes, pos); if (pos < outBytes.Length) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } /** * Process the last block in the buffer. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output, or the input is not block size aligned and should be. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if padding is expected and not found. * @exception DataLengthException if the input is not block size * aligned. */ public override int DoFinal( byte[] output, int outOff) { try { if (bufOff != 0) { if (!cipher.IsPartialBlockOkay) { throw new DataLengthException("data not block size aligned"); } if (outOff + bufOff > output.Length) { throw new DataLengthException("output buffer too short for DoFinal()"); } // NB: Can't copy directly, or we may write too much output cipher.ProcessBlock(buf, 0, buf, 0); Array.Copy(buf, 0, output, outOff, bufOff); } return bufOff; } finally { Reset(); } } /** * Reset the buffer and cipher. After resetting the object is in the same * state as it was after the last init (if there was one). */ public override void Reset() { Array.Clear(buf, 0, buf.Length); bufOff = 0; cipher.Reset(); } } }
using UnityEngine; using System.Collections.Generic; /** * Create Audio dynamically and easily playback * * @class LeanAudio * @constructor */ public class LeanAudio : MonoBehaviour { public static float MIN_FREQEUNCY_PERIOD = 0.00001f; public static int PROCESSING_ITERATIONS_MAX = 50000; public static List<float> generatedWaveDistances; public static LeanAudioOptions options(){ return new LeanAudioOptions(); } /** * Create dynamic audio from a set of Animation Curves and other options. * * @method createAudio * @param {AnimationCurve} volumeCurve:AnimationCurve describing the shape of the audios volume (from 0-1). The length of the audio is dicated by the end value here. * @param {AnimationCurve} frequencyCurve:AnimationCurve describing the width of the oscillations between the sound waves in seconds. Large numbers mean a lower note, while higher numbers mean a tighter frequency and therefor a higher note. Values are usually between 0.01 and 0.000001 (or smaller) * @param {LeanAudioOptions} options:LeanAudioOptions You can pass any other values in here like vibrato or the frequency you would like the sound to be encoded at. See <a href="LeanAudioOptions.html">LeanAudioOptions</a> for more details. * @return {AudioClip} AudioClip of the procedurally generated audio * @example * AnimationCurve volumeCurve = new AnimationCurve( new Keyframe(0f, 1f, 0f, -1f), new Keyframe(1f, 0f, -1f, 0f));<br> * AnimationCurve frequencyCurve = new AnimationCurve( new Keyframe(0f, 0.003f, 0f, 0f), new Keyframe(1f, 0.003f, 0f, 0f));<br> * AudioClip audioClip = LeanAudio.createAudio(volumeCurve, frequencyCurve, LeanAudio.options().setVibrato( new Vector3[]{ new Vector3(0.32f,0f,0f)} ));<br> */ public static AudioClip createAudio( AnimationCurve volume, AnimationCurve frequency, LeanAudioOptions options = null ){ if(options==null) options = new LeanAudioOptions(); float[] generatedWavePts = createAudioWave( volume, frequency, options); return createAudioFromWave( generatedWavePts, options ); } private static float[] createAudioWave( AnimationCurve volume, AnimationCurve frequency, LeanAudioOptions options ){ float time = volume[ volume.length - 1 ].time; List<float> list = new List<float>(); generatedWaveDistances = new List<float>(); // float[] vibratoValues = new float[ vibrato.Length ]; float passed = 0f; for(int i = 0; i < PROCESSING_ITERATIONS_MAX; i++){ float f = frequency.Evaluate(passed); if(f<MIN_FREQEUNCY_PERIOD) f = MIN_FREQEUNCY_PERIOD; float height = volume.Evaluate(passed + 0.5f*f); if(options.vibrato!=null){ for(int j=0; j<options.vibrato.Length; j++){ float peakMulti = Mathf.Abs( Mathf.Sin( 1.5708f + passed * (1f/options.vibrato[j][0]) * Mathf.PI ) ); float diff = (1f-options.vibrato[j][1]); peakMulti = options.vibrato[j][1] + diff*peakMulti; height *= peakMulti; } } // Debug.Log("i:"+i+" f:"+f+" passed:"+passed+" height:"+height+" time:"+time); if(passed + 0.5f*f>=time) break; generatedWaveDistances.Add( f ); passed += f; list.Add( passed ); list.Add( i%2==0 ? -height : height ); if(i>=PROCESSING_ITERATIONS_MAX-1){ Debug.LogError("LeanAudio has reached it's processing cap. To avoid this error increase the number of iterations ex: LeanAudio.PROCESSING_ITERATIONS_MAX = "+(PROCESSING_ITERATIONS_MAX*2)); } } float[] wave = new float[ list.Count ]; for(int i = 0; i < wave.Length; i++){ wave[i] = list[i]; } return wave; } private static AudioClip createAudioFromWave( float[] wave, LeanAudioOptions options ){ float time = wave[ wave.Length - 2 ]; float[] audioArr = new float[ (int)(options.frequencyRate*time) ]; int waveIter = 0; float subWaveDiff = wave[waveIter]; float subWaveTimeLast = 0f; float subWaveTime = wave[waveIter]; float waveHeight = wave[waveIter+1]; for(int i = 0; i < audioArr.Length; i++){ float passedTime = (float)i / (float)options.frequencyRate; if(passedTime > wave[waveIter] ){ subWaveTimeLast = wave[waveIter]; waveIter += 2; subWaveDiff = wave[waveIter] - wave[waveIter-2]; waveHeight = wave[waveIter+1]; // Debug.Log("passed wave i:"+i); } subWaveTime = passedTime - subWaveTimeLast; float ratioElapsed = subWaveTime / subWaveDiff; float value = Mathf.Sin( ratioElapsed * Mathf.PI ); //if(i<25) // Debug.Log("passedTime:"+passedTime+" value:"+value+" ratioElapsed:"+ratioElapsed+" subWaveTime:"+subWaveTime+" subWaveDiff:"+subWaveDiff); value *= waveHeight; audioArr[i] = value; // Debug.Log("pt:"+pt+" i:"+i+" val:"+audioArr[i]+" len:"+audioArr.Length); } int lengthSamples = audioArr.Length; #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 AudioClip audioClip = AudioClip.Create("Generated Audio", lengthSamples, 1, options.frequencyRate, false); #else bool is3dSound = false; AudioClip audioClip = AudioClip.Create("Generated Audio", lengthSamples, 1, options.frequencyRate, is3dSound, false); #endif audioClip.SetData(audioArr, 0); return audioClip; } public static AudioClip generateAudioFromCurve( AnimationCurve curve, int frequencyRate = 44100 ){ float curveTime = curve[ curve.length - 1 ].time; float time = curveTime; float[] audioArr = new float[ (int)(frequencyRate*time) ]; // Debug.Log("curveTime:"+curveTime+" AudioSettings.outputSampleRate:"+AudioSettings.outputSampleRate); for(int i = 0; i < audioArr.Length; i++){ float pt = (float)i / (float)frequencyRate; audioArr[i] = curve.Evaluate( pt ); // Debug.Log("pt:"+pt+" i:"+i+" val:"+audioArr[i]+" len:"+audioArr.Length); } int lengthSamples = audioArr.Length;//(int)( (float)frequencyRate * curveTime ); #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 AudioClip audioClip = AudioClip.Create("Generated Audio", lengthSamples, 1, frequencyRate, false); #else bool is3dSound = false; AudioClip audioClip = AudioClip.Create("Generated Audio", lengthSamples, 1, frequencyRate, is3dSound, false); #endif audioClip.SetData(audioArr, 0); return audioClip; } public static void playAudio( AudioClip audio, Vector3 pos, float volume, float pitch ){ // Debug.Log("audio length:"+audio.length); AudioSource audioSource = playClipAt(audio, pos); audioSource.minDistance = 1f; audioSource.pitch = pitch; audioSource.volume = volume; } public static AudioSource playClipAt( AudioClip clip, Vector3 pos ) { GameObject tempGO = new GameObject(); // create the temp object tempGO.transform.position = pos; // set its position AudioSource aSource = tempGO.AddComponent<AudioSource>(); // add an audio source aSource.clip = clip; // define the clip aSource.Play(); // start the sound Destroy(tempGO, clip.length); // destroy object after clip du1783ration return aSource; // return the AudioSource reference } public static void printOutAudioClip( AudioClip audioClip, ref AnimationCurve curve, float scaleX = 1f ){ // Debug.Log("Audio channels:"+audioClip.channels+" frequency:"+audioClip.frequency+" length:"+audioClip.length+" samples:"+audioClip.samples); float[] samples = new float[audioClip.samples * audioClip.channels]; audioClip.GetData(samples, 0); int i = 0; Keyframe[] frames = new Keyframe[samples.Length]; while (i < samples.Length) { frames[i] = new Keyframe( (float)i * scaleX, samples[i] ); ++i; } curve = new AnimationCurve( frames ); } } /** * Pass in options to LeanAudio * * @class LeanAudioOptions * @constructor */ public class LeanAudioOptions : object { public Vector3[] vibrato; public int frequencyRate = 44100; public LeanAudioOptions(){} /** * Set the frequency for the audio is encoded. 44100 is CD quality, but you can usually get away with much lower (or use a lower amount to get a more 8-bit sound). * * @method setFrequency * @param {int} frequencyRate:int of the frequency you wish to encode the AudioClip at * @return {LeanAudioOptions} LeanAudioOptions describing optional values * @example * AnimationCurve volumeCurve = new AnimationCurve( new Keyframe(0f, 1f, 0f, -1f), new Keyframe(1f, 0f, -1f, 0f));<br> * AnimationCurve frequencyCurve = new AnimationCurve( new Keyframe(0f, 0.003f, 0f, 0f), new Keyframe(1f, 0.003f, 0f, 0f));<br> * AudioClip audioClip = LeanAudio.createAudio(volumeCurve, frequencyCurve, LeanAudio.options().setVibrato( new Vector3[]{ new Vector3(0.32f,0f,0f)} ).setFrequency(12100) );<br> */ public LeanAudioOptions setFrequency( int frequencyRate ){ this.frequencyRate = frequencyRate; return this; } /** * Set details about the shape of the curve by adding vibrato waves through it. You can add as many as you want to sculpt out more detail in the sound wave. * * @method setVibrato * @param {Vector3[]} vibratoArray:Vector3[] The first value is the period in seconds that you wish to have the vibrato wave fluctuate at. The second value is the minimum height you wish the vibrato wave to dip down to (default is zero). The third is reserved for future effects. * @return {LeanAudioOptions} LeanAudioOptions describing optional values * @example * AnimationCurve volumeCurve = new AnimationCurve( new Keyframe(0f, 1f, 0f, -1f), new Keyframe(1f, 0f, -1f, 0f));<br> * AnimationCurve frequencyCurve = new AnimationCurve( new Keyframe(0f, 0.003f, 0f, 0f), new Keyframe(1f, 0.003f, 0f, 0f));<br> * AudioClip audioClip = LeanAudio.createAudio(volumeCurve, frequencyCurve, LeanAudio.options().setVibrato( new Vector3[]{ new Vector3(0.32f,0.3f,0f)} ).setFrequency(12100) );<br> */ public LeanAudioOptions setVibrato( Vector3[] vibrato ){ this.vibrato = vibrato; return this; } }
using System.Collections; using System.Globalization; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Iana; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Macs; using Org.BouncyCastle.Crypto.Paddings; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Security { /// <remarks> /// Utility class for creating HMac object from their names/Oids /// </remarks> public sealed class MacUtilities { private MacUtilities() { } private static readonly IDictionary algorithms = Platform.CreateHashtable(); //private static readonly IDictionary oids = Platform.CreateHashtable(); static MacUtilities() { algorithms[IanaObjectIdentifiers.HmacMD5.Id] = "HMAC-MD5"; algorithms[IanaObjectIdentifiers.HmacRipeMD160.Id] = "HMAC-RIPEMD160"; algorithms[IanaObjectIdentifiers.HmacSha1.Id] = "HMAC-SHA1"; algorithms[IanaObjectIdentifiers.HmacTiger.Id] = "HMAC-TIGER"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha1.Id] = "HMAC-SHA1"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha224.Id] = "HMAC-SHA224"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha256.Id] = "HMAC-SHA256"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha384.Id] = "HMAC-SHA384"; algorithms[PkcsObjectIdentifiers.IdHmacWithSha512.Id] = "HMAC-SHA512"; // TODO AESMAC? algorithms["DES"] = "DESMAC"; algorithms["DES/CFB8"] = "DESMAC/CFB8"; algorithms["DESEDE"] = "DESEDEMAC"; algorithms[PkcsObjectIdentifiers.DesEde3Cbc.Id] = "DESEDEMAC"; algorithms["DESEDE/CFB8"] = "DESEDEMAC/CFB8"; algorithms["DESISO9797MAC"] = "DESWITHISO9797"; algorithms["DESEDE64"] = "DESEDEMAC64"; algorithms["DESEDE64WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING"; algorithms["DESEDEISO9797ALG1MACWITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING"; algorithms["DESEDEISO9797ALG1WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING"; algorithms["ISO9797ALG3"] = "ISO9797ALG3MAC"; algorithms["ISO9797ALG3MACWITHISO7816-4PADDING"] = "ISO9797ALG3WITHISO7816-4PADDING"; algorithms["SKIPJACK"] = "SKIPJACKMAC"; algorithms["SKIPJACK/CFB8"] = "SKIPJACKMAC/CFB8"; algorithms["IDEA"] = "IDEAMAC"; algorithms["IDEA/CFB8"] = "IDEAMAC/CFB8"; algorithms["RC2"] = "RC2MAC"; algorithms["RC2/CFB8"] = "RC2MAC/CFB8"; algorithms["RC5"] = "RC5MAC"; algorithms["RC5/CFB8"] = "RC5MAC/CFB8"; algorithms["GOST28147"] = "GOST28147MAC"; algorithms["VMPC"] = "VMPCMAC"; algorithms["VMPC-MAC"] = "VMPCMAC"; algorithms["PBEWITHHMACSHA"] = "PBEWITHHMACSHA1"; algorithms["1.3.14.3.2.26"] = "PBEWITHHMACSHA1"; } // /// <summary> // /// Returns a ObjectIdentifier for a given digest mechanism. // /// </summary> // /// <param name="mechanism">A string representation of the digest meanism.</param> // /// <returns>A DerObjectIdentifier, null if the Oid is not available.</returns> // public static DerObjectIdentifier GetObjectIdentifier( // string mechanism) // { // mechanism = (string) algorithms[mechanism.ToUpper(CultureInfo.InvariantCulture)]; // // if (mechanism != null) // { // return (DerObjectIdentifier)oids[mechanism]; // } // // return null; // } // public static ICollection Algorithms // { // get { return oids.Keys; } // } public static IMac GetMac( DerObjectIdentifier id) { return GetMac(id.Id); } public static IMac GetMac( string algorithm) { string upper = Platform.StringToUpper(algorithm); string mechanism = (string) algorithms[upper]; if (mechanism == null) { mechanism = upper; } if (mechanism.StartsWith("PBEWITH")) { mechanism = mechanism.Substring("PBEWITH".Length); } if (mechanism.StartsWith("HMAC")) { string digestName; if (mechanism.StartsWith("HMAC-") || mechanism.StartsWith("HMAC/")) { digestName = mechanism.Substring(5); } else { digestName = mechanism.Substring(4); } return new HMac(DigestUtilities.GetDigest(digestName)); } if (mechanism == "AESCMAC") { return new CMac(new AesFastEngine()); } if (mechanism == "DESMAC") { return new CbcBlockCipherMac(new DesEngine()); } if (mechanism == "DESMAC/CFB8") { return new CfbBlockCipherMac(new DesEngine()); } if (mechanism == "DESEDECMAC") { return new CMac(new DesEdeEngine()); } if (mechanism == "DESEDEMAC") { return new CbcBlockCipherMac(new DesEdeEngine()); } if (mechanism == "DESEDEMAC/CFB8") { return new CfbBlockCipherMac(new DesEdeEngine()); } if (mechanism == "DESEDEMAC64") { return new CbcBlockCipherMac(new DesEdeEngine(), 64); } if (mechanism == "DESEDEMAC64WITHISO7816-4PADDING") { return new CbcBlockCipherMac(new DesEdeEngine(), 64, new ISO7816d4Padding()); } if (mechanism == "DESWITHISO9797" || mechanism == "ISO9797ALG3MAC") { return new ISO9797Alg3Mac(new DesEngine()); } if (mechanism == "ISO9797ALG3WITHISO7816-4PADDING") { return new ISO9797Alg3Mac(new DesEngine(), new ISO7816d4Padding()); } if (mechanism == "SKIPJACKMAC") { return new CbcBlockCipherMac(new SkipjackEngine()); } if (mechanism == "SKIPJACKMAC/CFB8") { return new CfbBlockCipherMac(new SkipjackEngine()); } #if INCLUDE_IDEA if (mechanism == "IDEAMAC") { return new CbcBlockCipherMac(new IdeaEngine()); } if (mechanism == "IDEAMAC/CFB8") { return new CfbBlockCipherMac(new IdeaEngine()); } #endif if (mechanism == "RC2MAC") { return new CbcBlockCipherMac(new RC2Engine()); } if (mechanism == "RC2MAC/CFB8") { return new CfbBlockCipherMac(new RC2Engine()); } if (mechanism == "RC5MAC") { return new CbcBlockCipherMac(new RC532Engine()); } if (mechanism == "RC5MAC/CFB8") { return new CfbBlockCipherMac(new RC532Engine()); } if (mechanism == "GOST28147MAC") { return new Gost28147Mac(); } if (mechanism == "VMPCMAC") { return new VmpcMac(); } throw new SecurityUtilityException("Mac " + mechanism + " not recognised."); } public static string GetAlgorithmName( DerObjectIdentifier oid) { return (string) algorithms[oid.Id]; } public static byte[] DoFinal( IMac mac) { byte[] b = new byte[mac.GetMacSize()]; mac.DoFinal(b, 0); return b; } } }
/* * 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 log4net; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenMetaverse; namespace OpenSim.Region.PhysicsModules.SharedBase { public delegate void PositionUpdate(Vector3 position); public delegate void VelocityUpdate(Vector3 velocity); public delegate void OrientationUpdate(Quaternion orientation); public enum ActorTypes : int { Unknown = 0, Agent = 1, Prim = 2, Ground = 3, Water = 4 } public enum PIDHoverType { Ground, GroundAndWater, Water, Absolute } public struct CameraData { public Quaternion CameraRotation; public Vector3 CameraAtAxis; public bool MouseLook; public bool Valid; } public struct ContactPoint { public Vector3 Position; public Vector3 SurfaceNormal; public float PenetrationDepth; public float RelativeSpeed; public bool CharacterFeet; public ContactPoint(Vector3 position, Vector3 surfaceNormal, float penetrationDepth) { Position = position; SurfaceNormal = surfaceNormal; PenetrationDepth = penetrationDepth; RelativeSpeed = 0f; // for now let this one be set explicity CharacterFeet = true; // keep other plugins work as before } public ContactPoint(Vector3 position, Vector3 surfaceNormal, float penetrationDepth, bool feet) { Position = position; SurfaceNormal = surfaceNormal; PenetrationDepth = penetrationDepth; RelativeSpeed = 0f; // for now let this one be set explicity CharacterFeet = feet; // keep other plugins work as before } } public struct ContactData { public float mu; public float bounce; public bool softcolide; public ContactData(float _mu, float _bounce, bool _softcolide) { mu = _mu; bounce = _bounce; softcolide = _softcolide; } } /// <summary> /// Used to pass collision information to OnCollisionUpdate listeners. /// </summary> public class CollisionEventUpdate : EventArgs { /// <summary> /// Number of collision events in this update. /// </summary> public int Count { get { return m_objCollisionList.Count; } } public bool CollisionsOnPreviousFrame { get; private set; } public Dictionary<uint, ContactPoint> m_objCollisionList; public CollisionEventUpdate(Dictionary<uint, ContactPoint> objCollisionList) { m_objCollisionList = objCollisionList; } public CollisionEventUpdate() { m_objCollisionList = new Dictionary<uint, ContactPoint>(); } public void AddCollider(uint localID, ContactPoint contact) { if (!m_objCollisionList.ContainsKey(localID)) { m_objCollisionList.Add(localID, contact); } else { float lastVel = m_objCollisionList[localID].RelativeSpeed; if (m_objCollisionList[localID].PenetrationDepth < contact.PenetrationDepth) { if(Math.Abs(lastVel) > Math.Abs(contact.RelativeSpeed)) contact.RelativeSpeed = lastVel; m_objCollisionList[localID] = contact; } else if(Math.Abs(lastVel) < Math.Abs(contact.RelativeSpeed)) { ContactPoint tmp = m_objCollisionList[localID]; tmp.RelativeSpeed = contact.RelativeSpeed; m_objCollisionList[localID] = tmp; } } } /// <summary> /// Clear added collision events. /// </summary> public void Clear() { m_objCollisionList.Clear(); } } public abstract class PhysicsActor { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public delegate void RequestTerseUpdate(); public delegate void CollisionUpdate(EventArgs e); public delegate void OutOfBounds(Vector3 pos); public delegate CameraData GetCameraData(); // disable warning: public events #pragma warning disable 67 public event PositionUpdate OnPositionUpdate; public event VelocityUpdate OnVelocityUpdate; public event OrientationUpdate OnOrientationUpdate; public event RequestTerseUpdate OnRequestTerseUpdate; public event GetCameraData OnPhysicsRequestingCameraData; /// <summary> /// Subscribers to this event must synchronously handle the dictionary of collisions received, since the event /// object is reused in subsequent physics frames. /// </summary> public event CollisionUpdate OnCollisionUpdate; public event OutOfBounds OnOutOfBounds; #pragma warning restore 67 public CameraData TryGetCameraData() { GetCameraData handler = OnPhysicsRequestingCameraData; if (handler != null) { return handler(); } return new CameraData { Valid = false }; } public static PhysicsActor Null { get { return new NullPhysicsActor(); } } public virtual bool Building { get; set; } public virtual void getContactData(ref ContactData cdata) { cdata.mu = 0; cdata.bounce = 0; } public abstract bool Stopped { get; } public abstract Vector3 Size { get; set; } public virtual void setAvatarSize(Vector3 size, float feetOffset) { Size = size; } public virtual bool Phantom { get; set; } public virtual bool IsVolumeDtc { get { return false; } set { return; } } public virtual byte PhysicsShapeType { get; set; } public abstract PrimitiveBaseShape Shape { set; } uint m_baseLocalID; public virtual uint LocalID { set { m_baseLocalID = value; } get { return m_baseLocalID; } } public abstract bool Grabbed { set; } public abstract bool Selected { set; } /// <summary> /// Name of this actor. /// </summary> /// <remarks> /// XXX: Bizarrely, this cannot be "Terrain" or "Water" right now unless it really is simulating terrain or /// water. This is not a problem due to the formatting of names given by prims and avatars. /// </remarks> public string Name { get; set; } /// <summary> /// This is being used by ODE joint code. /// </summary> public string SOPName; public abstract void CrossingFailure(); public abstract void link(PhysicsActor obj); public abstract void delink(); public abstract void LockAngularMotion(byte axislocks); public virtual void RequestPhysicsterseUpdate() { // Make a temporary copy of the event to avoid possibility of // a race condition if the last subscriber unsubscribes // immediately after the null check and before the event is raised. RequestTerseUpdate handler = OnRequestTerseUpdate; if (handler != null) { handler(); } } public virtual void RaiseOutOfBounds(Vector3 pos) { // Make a temporary copy of the event to avoid possibility of // a race condition if the last subscriber unsubscribes // immediately after the null check and before the event is raised. OutOfBounds handler = OnOutOfBounds; if (handler != null) { handler(pos); } } public virtual void SendCollisionUpdate(EventArgs e) { CollisionUpdate handler = OnCollisionUpdate; // m_log.DebugFormat("[PHYSICS ACTOR]: Sending collision for {0}", LocalID); if (handler != null) handler(e); } public virtual void SetMaterial (int material) { } public virtual float Density { get; set; } public virtual float GravModifier { get; set; } public virtual float Friction { get; set; } public virtual float Restitution { get; set; } /// <summary> /// Position of this actor. /// </summary> /// <remarks> /// Setting this directly moves the actor to a given position. /// Getting this retrieves the position calculated by physics scene updates, using factors such as velocity and /// collisions. /// </remarks> public abstract Vector3 Position { get; set; } public abstract float Mass { get; } public abstract Vector3 Force { get; set; } public abstract int VehicleType { get; set; } public abstract void VehicleFloatParam(int param, float value); public abstract void VehicleVectorParam(int param, Vector3 value); public abstract void VehicleRotationParam(int param, Quaternion rotation); public abstract void VehicleFlags(int param, bool remove); // This is an overridable version of SetVehicle() that works for all physics engines. // This is VERY inefficient. It behoves any physics engine to override this and // implement a more efficient setting of all the vehicle parameters. public virtual void SetVehicle(object pvdata) { VehicleData vdata = (VehicleData)pvdata; // vehicleActor.ProcessSetVehicle((VehicleData)vdata); this.VehicleType = (int)vdata.m_type; this.VehicleFlags(-1, false); // clears all flags this.VehicleFlags((int)vdata.m_flags, false); // Linear properties this.VehicleVectorParam((int)Vehicle.LINEAR_MOTOR_DIRECTION, vdata.m_linearMotorDirection); this.VehicleVectorParam((int)Vehicle.LINEAR_FRICTION_TIMESCALE, vdata.m_linearFrictionTimescale); this.VehicleFloatParam((int)Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE, vdata.m_linearMotorDecayTimescale); this.VehicleFloatParam((int)Vehicle.LINEAR_MOTOR_TIMESCALE, vdata.m_linearMotorTimescale); this.VehicleVectorParam((int)Vehicle.LINEAR_MOTOR_OFFSET, vdata.m_linearMotorOffset); //Angular properties this.VehicleVectorParam((int)Vehicle.ANGULAR_MOTOR_DIRECTION, vdata.m_angularMotorDirection); this.VehicleFloatParam((int)Vehicle.ANGULAR_MOTOR_TIMESCALE, vdata.m_angularMotorTimescale); this.VehicleFloatParam((int)Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE, vdata.m_angularMotorDecayTimescale); this.VehicleVectorParam((int)Vehicle.ANGULAR_FRICTION_TIMESCALE, vdata.m_angularFrictionTimescale); //Deflection properties this.VehicleFloatParam((int)Vehicle.ANGULAR_DEFLECTION_EFFICIENCY, vdata.m_angularDeflectionEfficiency); this.VehicleFloatParam((int)Vehicle.ANGULAR_DEFLECTION_TIMESCALE, vdata.m_angularDeflectionTimescale); this.VehicleFloatParam((int)Vehicle.LINEAR_DEFLECTION_EFFICIENCY, vdata.m_linearDeflectionEfficiency); this.VehicleFloatParam((int)Vehicle.LINEAR_DEFLECTION_TIMESCALE, vdata.m_linearDeflectionTimescale); //Banking properties this.VehicleFloatParam((int)Vehicle.BANKING_EFFICIENCY, vdata.m_bankingEfficiency); this.VehicleFloatParam((int)Vehicle.BANKING_MIX, vdata.m_bankingMix); this.VehicleFloatParam((int)Vehicle.BANKING_TIMESCALE, vdata.m_bankingTimescale); //Hover and Buoyancy properties this.VehicleFloatParam((int)Vehicle.HOVER_HEIGHT, vdata.m_VhoverHeight); this.VehicleFloatParam((int)Vehicle.HOVER_EFFICIENCY, vdata.m_VhoverEfficiency); this.VehicleFloatParam((int)Vehicle.HOVER_TIMESCALE, vdata.m_VhoverTimescale); this.VehicleFloatParam((int)Vehicle.BUOYANCY, vdata.m_VehicleBuoyancy); //Attractor properties this.VehicleFloatParam((int)Vehicle.VERTICAL_ATTRACTION_EFFICIENCY, vdata.m_verticalAttractionEfficiency); this.VehicleFloatParam((int)Vehicle.VERTICAL_ATTRACTION_TIMESCALE, vdata.m_verticalAttractionTimescale); this.VehicleRotationParam((int)Vehicle.REFERENCE_FRAME, vdata.m_referenceFrame); } /// <summary> /// Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more /// </summary> public abstract void SetVolumeDetect(int param); public abstract Vector3 GeometricCenter { get; } public abstract Vector3 CenterOfMass { get; } public virtual float PhysicsCost { get { return 0.1f; } } public virtual float StreamCost { get { return 1.0f; } } /// <summary> /// The desired velocity of this actor. /// </summary> /// <remarks> /// Setting this provides a target velocity for physics scene updates. /// Getting this returns the last set target. Fetch Velocity to get the current velocity. /// </remarks> protected Vector3 m_targetVelocity; public virtual Vector3 TargetVelocity { get { return m_targetVelocity; } set { m_targetVelocity = value; Velocity = m_targetVelocity; } } public abstract Vector3 Velocity { get; set; } public virtual Vector3 rootVelocity { get { return Vector3.Zero; } } public abstract Vector3 Torque { get; set; } public abstract float CollisionScore { get; set;} public abstract Vector3 Acceleration { get; set; } public abstract Quaternion Orientation { get; set; } public abstract int PhysicsActorType { get; set; } public abstract bool IsPhysical { get; set; } public abstract bool Flying { get; set; } public abstract bool SetAlwaysRun { get; set; } public abstract bool ThrottleUpdates { get; set; } public abstract bool IsColliding { get; set; } public abstract bool CollidingGround { get; set; } public abstract bool CollidingObj { get; set; } public abstract bool FloatOnWater { set; } public abstract Vector3 RotationalVelocity { get; set; } public abstract bool Kinematic { get; set; } public abstract float Buoyancy { get; set; } // Used for MoveTo public abstract Vector3 PIDTarget { set; } public abstract bool PIDActive { get; set; } public abstract float PIDTau { set; } // Used for llSetHoverHeight and maybe vehicle height // Hover Height will override MoveTo target's Z public abstract bool PIDHoverActive {get; set;} public abstract float PIDHoverHeight { set;} public abstract PIDHoverType PIDHoverType { set;} public abstract float PIDHoverTau { set;} // For RotLookAt public abstract Quaternion APIDTarget { set;} public abstract bool APIDActive { set;} public abstract float APIDStrength { set;} public abstract float APIDDamping { set;} public abstract void AddForce(Vector3 force, bool pushforce); public abstract void AddAngularForce(Vector3 force, bool pushforce); public abstract void SetMomentum(Vector3 momentum); public abstract void SubscribeEvents(int ms); public abstract void UnSubscribeEvents(); public abstract bool SubscribedEvents(); public virtual void AddCollisionEvent(uint CollidedWith, ContactPoint contact) { } // Warning in a parent part it returns itself, not null public virtual PhysicsActor ParentActor { get { return this; } } // Extendable interface for new, physics engine specific operations public virtual object Extension(string pFunct, params object[] pParams) { // A NOP of the physics engine does not implement this feature return null; } } public class NullPhysicsActor : PhysicsActor { private ActorTypes m_actorType = ActorTypes.Unknown; public override bool Stopped { get{ return true; } } public override Vector3 Position { get { return Vector3.Zero; } set { return; } } public override bool SetAlwaysRun { get { return false; } set { return; } } public override uint LocalID { get { return 0; } set { return; } } public override bool Grabbed { set { return; } } public override bool Selected { set { return; } } public override float Buoyancy { get { return 0f; } set { return; } } public override bool FloatOnWater { set { return; } } public override bool CollidingGround { get { return false; } set { return; } } public override bool CollidingObj { get { return false; } set { return; } } public override Vector3 Size { get { return Vector3.Zero; } set { return; } } public override float Mass { get { return 0f; } } public override Vector3 Force { get { return Vector3.Zero; } set { return; } } public override int VehicleType { get { return 0; } set { return; } } public override void VehicleFloatParam(int param, float value) {} public override void VehicleVectorParam(int param, Vector3 value) { } public override void VehicleRotationParam(int param, Quaternion rotation) { } public override void VehicleFlags(int param, bool remove) { } public override void SetVolumeDetect(int param) {} public override void SetMaterial(int material) {} public override Vector3 CenterOfMass { get { return Vector3.Zero; }} public override Vector3 GeometricCenter { get { return Vector3.Zero; }} public override PrimitiveBaseShape Shape { set { return; }} public override Vector3 Velocity { get { return Vector3.Zero; } set { return; } } public override Vector3 Torque { get { return Vector3.Zero; } set { return; } } public override float CollisionScore { get { return 0f; } set { } } public override void CrossingFailure() {} public override Quaternion Orientation { get { return Quaternion.Identity; } set { } } public override Vector3 Acceleration { get { return Vector3.Zero; } set { } } public override bool IsPhysical { get { return false; } set { return; } } public override bool Flying { get { return false; } set { return; } } public override bool ThrottleUpdates { get { return false; } set { return; } } public override bool IsColliding { get { return false; } set { return; } } public override int PhysicsActorType { get { return (int)m_actorType; } set { ActorTypes type = (ActorTypes)value; switch (type) { case ActorTypes.Ground: case ActorTypes.Water: m_actorType = type; break; default: m_actorType = ActorTypes.Unknown; break; } } } public override bool Kinematic { get { return true; } set { return; } } public override void link(PhysicsActor obj) { } public override void delink() { } public override void LockAngularMotion(byte axislocks) { } public override void AddForce(Vector3 force, bool pushforce) { } public override void AddAngularForce(Vector3 force, bool pushforce) { } public override Vector3 RotationalVelocity { get { return Vector3.Zero; } set { return; } } public override Vector3 PIDTarget { set { return; } } public override bool PIDActive { get { return false; } set { return; } } public override float PIDTau { set { return; } } public override float PIDHoverHeight { set { return; } } public override bool PIDHoverActive {get {return false;} set { return; } } public override PIDHoverType PIDHoverType { set { return; } } public override float PIDHoverTau { set { return; } } public override Quaternion APIDTarget { set { return; } } public override bool APIDActive { set { return; } } public override float APIDStrength { set { return; } } public override float APIDDamping { set { return; } } public override void SetMomentum(Vector3 momentum) { } public override void SubscribeEvents(int ms) { } public override void UnSubscribeEvents() { } public override bool SubscribedEvents() { return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Text; using System.Windows.Forms; namespace ListViewPrinterDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.LoadXmlDataIntoList(); this.Rebuild(); this.UpdatePrintPreview(null, null); } private void LoadXmlDataIntoList() { DataSet ds = new DataSet(); try { ds.ReadXml("Persons.xml"); LoadTableIntoList(this.listView1, ds.Tables["Person"]); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void LoadTableIntoList(ListView lv, DataTable table) { lv.BeginUpdate(); lv.Items.Clear(); foreach (DataRow row in table.Rows) { ListViewItem lvi = new ListViewItem(); lvi.Text = row[0].ToString(); lvi.ImageIndex = Int32.Parse(row[1].ToString()); for (int i = 2; i < table.Columns.Count; i++) { lvi.SubItems.Add(row[i].ToString()); } lv.Items.Add(lvi); } lv.EndUpdate(); } private void tabControl1_Selected(object sender, TabControlEventArgs e) { if (e.TabPageIndex == 1) this.UpdatePrintPreview(null, null); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { this.printPreviewControl1.Zoom = 2.0; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { this.printPreviewControl1.Zoom = 1.0; } private void radioButton3_CheckedChanged(object sender, EventArgs e) { this.printPreviewControl1.Zoom = 0.5; } private void radioButton4_CheckedChanged(object sender, EventArgs e) { this.printPreviewControl1.Zoom = 1.0; this.printPreviewControl1.AutoZoom = true; } private void button1_Click(object sender, EventArgs e) { this.listViewPrinter1.PageSetup(); this.UpdatePrintPreview(null, null); } private void button2_Click(object sender, EventArgs e) { this.listViewPrinter1.PrintPreview(); } private void button3_Click(object sender, EventArgs e) { this.listViewPrinter1.PrintWithDialog(); } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { int pages = (int)this.numericUpDown1.Value; switch (pages) { case 1: case 2: case 3: this.printPreviewControl1.Rows = 1; this.printPreviewControl1.Columns = pages; break; default: this.printPreviewControl1.Rows = 2; this.printPreviewControl1.Columns = ((pages-1) / 2) + 1; break; } } private void UpdatePrintPreview(object sender, EventArgs e) { this.listViewPrinter1.Header = this.tbHeader.Text.Replace("\\t", "\t"); this.listViewPrinter1.Footer = this.tbFooter.Text.Replace("\\t", "\t"); this.listViewPrinter1.Watermark = this.tbWatermark.Text; this.listViewPrinter1.IsShrinkToFit = this.cbShrinkToFit.Checked; //this.listViewPrinter1.IsTextOnly = !this.cbListHeaderOnEveryPage.Checked; this.listViewPrinter1.IsListHeaderOnEachPage = this.cbListHeaderOnEveryPage.Checked; this.listViewPrinter1.IsPrintSelectionOnly = this.cbPrintSelection.Checked; if (this.rbStyleMinimal.Checked == true) this.ApplyMinimalFormatting(); else if (this.rbStyleModern.Checked == true) this.ApplyModernFormatting(); else if (this.rbStyleOTT.Checked == true) this.ApplyOverTheTopFormatting(); else if (this.rbStyleCustom.Checked == true) this.ApplyCustomFormatting(); if (this.cbUseGridLines.Checked == false) this.listViewPrinter1.ListGridPen = null; //this.listViewPrinter1.FirstPage = (int)this.numericUpDown1.Value; //this.listViewPrinter1.LastPage = (int)this.numericUpDown2.Value; this.printPreviewControl1.InvalidatePreview(); } /// <summary> /// Give the report a minimal set of default formatting values. /// </summary> public void ApplyMinimalFormatting() { this.listViewPrinter1.CellFormat = null; this.listViewPrinter1.ListFont = new Font("Tahoma", 9); this.listViewPrinter1.HeaderFormat = BrightIdeasSoftware.BlockFormat.Header(); this.listViewPrinter1.HeaderFormat.TextBrush = Brushes.Black; this.listViewPrinter1.HeaderFormat.BackgroundBrush = null; this.listViewPrinter1.HeaderFormat.SetBorderPen(BrightIdeasSoftware.Sides.Bottom, new Pen(Color.Black, 0.5f)); this.listViewPrinter1.FooterFormat = BrightIdeasSoftware.BlockFormat.Footer(); this.listViewPrinter1.GroupHeaderFormat = BrightIdeasSoftware.BlockFormat.GroupHeader(); Brush brush = new LinearGradientBrush(new Point(0, 0), new Point(200, 0), Color.Gray, Color.White); this.listViewPrinter1.GroupHeaderFormat.SetBorder(BrightIdeasSoftware.Sides.Bottom, 2, brush); this.listViewPrinter1.ListHeaderFormat = BrightIdeasSoftware.BlockFormat.ListHeader(); this.listViewPrinter1.ListHeaderFormat.BackgroundBrush = null; this.listViewPrinter1.WatermarkFont = null; this.listViewPrinter1.WatermarkColor = Color.Empty; } /// <summary> /// Give the report a minimal set of default formatting values. /// </summary> public void ApplyModernFormatting() { this.listViewPrinter1.CellFormat = null; this.listViewPrinter1.ListFont = new Font("Ms Sans Serif", 9); this.listViewPrinter1.ListGridPen = new Pen(Color.DarkGray, 0.5f); this.listViewPrinter1.HeaderFormat = BrightIdeasSoftware.BlockFormat.Header(new Font("Verdana", 24, FontStyle.Bold)); this.listViewPrinter1.HeaderFormat.BackgroundBrush = new LinearGradientBrush(new Point(0, 0), new Point(200, 0), Color.DarkBlue, Color.White); this.listViewPrinter1.FooterFormat = BrightIdeasSoftware.BlockFormat.Footer(); this.listViewPrinter1.FooterFormat.BackgroundBrush = new LinearGradientBrush(new Point(0, 0), new Point(200, 0), Color.White, Color.Blue); this.listViewPrinter1.GroupHeaderFormat = BrightIdeasSoftware.BlockFormat.GroupHeader(); this.listViewPrinter1.ListHeaderFormat = BrightIdeasSoftware.BlockFormat.ListHeader(new Font("Verdana", 12)); this.listViewPrinter1.WatermarkFont = null; this.listViewPrinter1.WatermarkColor = Color.Empty; } /// <summary> /// Give the report a some outrageous formatting values. /// </summary> public void ApplyOverTheTopFormatting() { this.listViewPrinter1.CellFormat = null; this.listViewPrinter1.ListFont = new Font("Ms Sans Serif", 9); this.listViewPrinter1.ListGridPen = new Pen(Color.Blue, 0.5f); this.listViewPrinter1.HeaderFormat = BrightIdeasSoftware.BlockFormat.Header(new Font("Comic Sans MS", 36)); this.listViewPrinter1.HeaderFormat.TextBrush = new LinearGradientBrush(new Point(0, 0), new Point(900, 0), Color.Black, Color.Blue); this.listViewPrinter1.HeaderFormat.BackgroundBrush = new TextureBrush(this.listView1.SmallImageList.Images["music"], WrapMode.Tile); this.listViewPrinter1.HeaderFormat.SetBorder(BrightIdeasSoftware.Sides.All, 10, new LinearGradientBrush(new Point(0, 0), new Point(300, 0), Color.Purple, Color.Pink)); this.listViewPrinter1.FooterFormat = BrightIdeasSoftware.BlockFormat.Footer(new Font("Comic Sans MS", 12)); this.listViewPrinter1.FooterFormat.TextBrush = Brushes.Blue; this.listViewPrinter1.FooterFormat.BackgroundBrush = new LinearGradientBrush(new Point(0, 0), new Point(200, 0), Color.Gold, Color.Green); this.listViewPrinter1.FooterFormat.SetBorderPen(BrightIdeasSoftware.Sides.All, new Pen(Color.FromArgb(128, Color.Green), 5)); this.listViewPrinter1.GroupHeaderFormat = BrightIdeasSoftware.BlockFormat.GroupHeader(); Brush brush = new HatchBrush(HatchStyle.LargeConfetti, Color.Blue, Color.Empty); this.listViewPrinter1.GroupHeaderFormat.SetBorder(BrightIdeasSoftware.Sides.Bottom, 5, brush); this.listViewPrinter1.ListHeaderFormat = BrightIdeasSoftware.BlockFormat.ListHeader(new Font("Comic Sans MS", 12)); this.listViewPrinter1.ListHeaderFormat.BackgroundBrush = Brushes.PowderBlue; this.listViewPrinter1.ListHeaderFormat.TextBrush = Brushes.Black; this.listViewPrinter1.WatermarkFont = new Font("Comic Sans MS", 72); this.listViewPrinter1.WatermarkColor = Color.Red; } /// <summary> /// Copy the formatting from the formatting that the user has setup on the custom format panel. /// </summary> public void ApplyCustomFormatting() { this.listViewPrinter1.ListFont = this.listViewPrinter2.ListFont; this.listViewPrinter1.CellFormat = this.listViewPrinter2.CellFormat; this.listViewPrinter1.HeaderFormat = this.listViewPrinter2.HeaderFormat; this.listViewPrinter1.FooterFormat = this.listViewPrinter2.FooterFormat; this.listViewPrinter1.GroupHeaderFormat = this.listViewPrinter2.GroupHeaderFormat; this.listViewPrinter1.ListHeaderFormat = this.listViewPrinter2.ListHeaderFormat; this.listViewPrinter1.WatermarkFont = this.listViewPrinter2.WatermarkFont; this.listViewPrinter1.WatermarkTransparency = this.listViewPrinter2.WatermarkTransparency; this.listViewPrinter1.WatermarkColor = this.listViewPrinter2.WatermarkColor; } private void checkBox1_CheckedChanged(object sender, EventArgs e) { this.listView1.ShowGroups = this.checkBox1.Checked; this.Rebuild(); } //----------------------------------------------------------------------------- // Include all the stupid normal stuff that a ListView needs to be useful // Better to use an ObjectListView! private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) { if (e.Column == this.lastSortColumn) { if (this.lastSortOrder == SortOrder.Ascending) this.lastSortOrder = SortOrder.Descending; else this.lastSortOrder = SortOrder.Ascending; } else { this.lastSortOrder = SortOrder.Ascending; this.lastSortColumn = e.Column; } this.Rebuild(); } private int lastSortColumn = 0; private SortOrder lastSortOrder = SortOrder.Ascending; private void Rebuild() { if (this.listView1.ShowGroups) this.BuildGroups(this.lastSortColumn); else this.listView1.ListViewItemSorter = new ColumnComparer(this.lastSortColumn, this.lastSortOrder); } private void BuildGroups(int column) { this.listView1.Groups.Clear(); // Getting the Count forces any internal cache of the ListView to be flushed. Without // this, iterating over the Items will not work correctly if the ListView handle // has not yet been created. int dummy = this.listView1.Items.Count; // Separate the list view items into groups, using the group key as the descrimanent Dictionary<String, List<ListViewItem>> map = new Dictionary<String, List<ListViewItem>>(); foreach (ListViewItem lvi in this.listView1.Items) { String key = lvi.SubItems[column].Text; if (column == 0 && key.Length > 0) key = key.Substring(0, 1); if (!map.ContainsKey(key)) map[key] = new List<ListViewItem>(); map[key].Add(lvi); } // Make a list of the required groups List<ListViewGroup> groups = new List<ListViewGroup>(); foreach (String key in map.Keys) { groups.Add(new ListViewGroup(key)); } // Sort the groups groups.Sort(new ListViewGroupComparer(this.lastSortOrder)); // Put each group into the list view, and give each group its member items. // The order of statements is important here: // - the header must be calculate before the group is added to the list view, // otherwise changing the header causes a nasty redraw (even in the middle of a BeginUpdate...EndUpdate pair) // - the group must be added before it is given items, otherwise an exception is thrown (is this documented?) ColumnComparer itemSorter = new ColumnComparer(column, this.lastSortOrder); foreach (ListViewGroup group in groups) { this.listView1.Groups.Add(group); map[group.Header].Sort(itemSorter); group.Items.AddRange(map[group.Header].ToArray()); } } internal class ListViewGroupComparer : IComparer<ListViewGroup> { public ListViewGroupComparer(SortOrder order) { this.sortOrder = order; } public int Compare(ListViewGroup x, ListViewGroup y) { int result = String.Compare(x.Header, y.Header, true); if (this.sortOrder == SortOrder.Descending) result = 0 - result; return result; } private SortOrder sortOrder; } internal class ColumnComparer : IComparer, IComparer<ListViewItem> { public ColumnComparer(int col, SortOrder order) { this.column = col; this.sortOrder = order; } public int Compare(object x, object y) { return this.Compare((ListViewItem)x, (ListViewItem)y); } public int Compare(ListViewItem x, ListViewItem y) { int result = String.Compare(x.SubItems[this.column].Text, y.SubItems[this.column].Text, true); if (this.sortOrder == SortOrder.Descending) result = 0 - result; return result; } private int column; private SortOrder sortOrder; } void CheckBox1CheckedChanged(object sender, EventArgs e) { this.listView1.ShowGroups = ((CheckBox)sender).Checked; this.Rebuild(); } } }
using DevExpress.Internal; using DevExpress.Mvvm.UI.Interactivity; using DevExpress.Mvvm.UI.Native; using System; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace DevExpress.Mvvm.UI { public enum NotificationSetting { Enabled = 0, DisabledForApplication = 1, DisabledForUser = 2, DisabledByGroupPolicy = 3, DisabledByManifest = 4 } public enum ToastDismissalReason : long { UserCanceled = 0, ApplicationHidden = 1, TimedOut = 2 } public enum PredefinedSound { Notification_Default, NoSound, Notification_IM, Notification_Mail, Notification_Reminder, Notification_SMS, Notification_Looping_Alarm, Notification_Looping_Alarm2, Notification_Looping_Alarm3, Notification_Looping_Alarm4, Notification_Looping_Alarm5, Notification_Looping_Alarm6, Notification_Looping_Alarm7, Notification_Looping_Alarm8, Notification_Looping_Alarm9, Notification_Looping_Alarm10, Notification_Looping_Call, Notification_Looping_Call2, Notification_Looping_Call3, Notification_Looping_Call4, Notification_Looping_Call5, Notification_Looping_Call6, Notification_Looping_Call7, Notification_Looping_Call8, Notification_Looping_Call9, Notification_Looping_Call10, } public enum PredefinedNotificationDuration { Default, Long } public enum NotificationTemplate { LongText, ShortHeaderAndLongText, LongHeaderAndShortText, ShortHeaderAndTwoTextFields } public enum NotificationPosition { BottomRight, TopRight } [TargetTypeAttribute(typeof(UserControl))] [TargetTypeAttribute(typeof(Window))] public class NotificationService : ServiceBase, INotificationService { class MvvmPredefinedNotification : INotification { public IPredefinedToastNotification Notification { get; set; } public Task<NotificationResult> ShowAsync() { return Notification.ShowAsync().ContinueWith(t => (NotificationResult)t.Result); } public void Hide() { Notification.Hide(); } } internal class MvvmCustomNotification : INotification { CustomNotifier notifier; CustomNotification notification; internal int duration; public MvvmCustomNotification(object viewModel, CustomNotifier notifier, int duration) { this.notifier = notifier; this.duration = duration; this.notification = new CustomNotification(viewModel, notifier); } public void Hide() { notifier.Hide(notification); } public Task<NotificationResult> ShowAsync() { return notifier.ShowAsync(notification, duration); } } public static readonly DependencyProperty UseWin8NotificationsIfAvailableProperty = DependencyProperty.Register("UseWin8NotificationsIfAvailable", typeof(bool), typeof(NotificationService), new PropertyMetadata(true, (d, e) => ((NotificationService)d).OnUseWin8NotificationsIfAvailableChanged())); public static readonly DependencyProperty CustomNotificationStyleProperty = DependencyProperty.Register("CustomNotificationStyle", typeof(Style), typeof(NotificationService), new PropertyMetadata(null, (d, e) => ((NotificationService)d).OnCustomNotificationStyleChanged())); public static readonly DependencyProperty CustomNotificationTemplateProperty = DependencyProperty.Register("CustomNotificationTemplate", typeof(DataTemplate), typeof(NotificationService), new PropertyMetadata(null, (d, e) => ((NotificationService)d).OnCustomNotificationTemplateChanged())); public static readonly DependencyProperty CustomNotificationTemplateSelectorProperty = DependencyProperty.Register("CustomNotificationTemplateSelector", typeof(DataTemplateSelector), typeof(NotificationService), new PropertyMetadata(null, (d, e) => ((NotificationService)d).OnCustomNotificationTemplateSelectorChanged())); public static readonly DependencyProperty CustomNotificationDurationProperty = DependencyProperty.Register("CustomNotificationDuration", typeof(TimeSpan), typeof(NotificationService), new PropertyMetadata(TimeSpan.FromMilliseconds(6000))); public static readonly DependencyProperty CustomNotificationPositionProperty = DependencyProperty.Register("CustomNotificationPosition", typeof(NotificationPosition), typeof(NotificationService), new PropertyMetadata(NotificationPosition.TopRight, (d, e) => ((NotificationService)d).UpdateCustomNotifierPositioner())); public static readonly DependencyProperty CustomNotificationVisibleMaxCountProperty = DependencyProperty.Register("CustomNotificationVisibleMaxCount", typeof(int), typeof(NotificationService), new PropertyMetadata(3, (d, e) => ((NotificationService)d).UpdateCustomNotifierPositioner())); public static readonly DependencyProperty PredefinedNotificationTemplateProperty = DependencyProperty.Register("PredefinedNotificationTemplate", typeof(NotificationTemplate), typeof(NotificationService), new PropertyMetadata(NotificationTemplate.LongText)); public static readonly DependencyProperty ApplicationIdProperty = DependencyProperty.Register("ApplicationId", typeof(string), typeof(NotificationService), new PropertyMetadata(null)); public static readonly DependencyProperty PredefinedNotificationDurationProperty = DependencyProperty.Register("PredefinedNotificationDuration", typeof(PredefinedNotificationDuration), typeof(NotificationService), new PropertyMetadata(PredefinedNotificationDuration.Default)); public static readonly DependencyProperty SoundProperty = DependencyProperty.Register("Sound", typeof(PredefinedSound), typeof(NotificationService), new PropertyMetadata(PredefinedSound.Notification_Default)); IPredefinedToastNotificationFactory factory; IPredefinedToastNotificationFactory Factory { get { if(factory == null) { if(UseWin8NotificationsIfAvailable && AreWin8NotificationsAvailable) { if(ApplicationId == null) throw new ArgumentNullException("ApplicationId"); factory = new WinRTToastNotificationFactory(ApplicationId); } else { factory = new WpfToastNotificationFactory(); } } return factory; } } CustomNotifier customNotifier; CustomNotifier CustomNotifier { get { if(customNotifier == null) { customNotifier = new CustomNotifier(); } return customNotifier; } } public bool UseWin8NotificationsIfAvailable { get { return (bool)GetValue(UseWin8NotificationsIfAvailableProperty); } set { SetValue(UseWin8NotificationsIfAvailableProperty, value); } } public Style CustomNotificationStyle { get { return (Style)GetValue(CustomNotificationStyleProperty); } set { SetValue(CustomNotificationStyleProperty, value); } } public DataTemplate CustomNotificationTemplate { get { return (DataTemplate)GetValue(CustomNotificationTemplateProperty); } set { SetValue(CustomNotificationTemplateProperty, value); } } public DataTemplateSelector CustomNotificationTemplateSelector { get { return (DataTemplateSelector)GetValue(CustomNotificationTemplateSelectorProperty); } set { SetValue(CustomNotificationTemplateSelectorProperty, value); } } public TimeSpan CustomNotificationDuration { get { return (TimeSpan)GetValue(CustomNotificationDurationProperty); } set { SetValue(CustomNotificationDurationProperty, value); } } public NotificationPosition CustomNotificationPosition { get { return (NotificationPosition)GetValue(CustomNotificationPositionProperty); } set { SetValue(CustomNotificationPositionProperty, value); } } public int CustomNotificationVisibleMaxCount { get { return (int)GetValue(CustomNotificationVisibleMaxCountProperty); } set { SetValue(CustomNotificationVisibleMaxCountProperty, value); } } void UpdateCustomNotifierPositioner() { CustomNotifier.UpdatePositioner(CustomNotificationPosition, CustomNotificationVisibleMaxCount); } void OnCustomNotificationTemplateChanged() { CustomNotifier.ContentTemplate = CustomNotificationTemplate; } void OnCustomNotificationTemplateSelectorChanged() { CustomNotifier.ContentTemplateSelector = CustomNotificationTemplateSelector; } void OnCustomNotificationStyleChanged() { CustomNotifier.Style = CustomNotificationStyle; } void OnUseWin8NotificationsIfAvailableChanged() { factory = null; } public string ApplicationId { get { return (string)GetValue(ApplicationIdProperty); } set { SetValue(ApplicationIdProperty, value); } } public NotificationTemplate PredefinedNotificationTemplate { get { return (NotificationTemplate)GetValue(PredefinedNotificationTemplateProperty); } set { SetValue(PredefinedNotificationTemplateProperty, value); } } public PredefinedSound Sound { get { return (PredefinedSound)GetValue(SoundProperty); } set { SetValue(SoundProperty, value); } } public PredefinedNotificationDuration PredefinedNotificationDuration { get { return (PredefinedNotificationDuration)GetValue(PredefinedNotificationDurationProperty); } set { SetValue(PredefinedNotificationDurationProperty, value); } } public bool AreWin8NotificationsAvailable { get { return DevExpress.Internal.WinApi.ToastNotificationManager.AreToastNotificationsSupported; } } public INotification CreateCustomNotification(object viewModel) { return new MvvmCustomNotification(viewModel, CustomNotifier, (int)Math.Max(0, Math.Min(int.MaxValue, CustomNotificationDuration.TotalMilliseconds))); } public INotification CreatePredefinedNotification( string text1, string text2, string text3, ImageSource image = null) { IPredefinedToastNotificationContentFactory cf = Factory.CreateContentFactory(); IPredefinedToastNotificationContent content = null; switch(PredefinedNotificationTemplate) { case NotificationTemplate.LongText: content = cf.CreateContent(text1); break; case NotificationTemplate.ShortHeaderAndLongText: content = cf.CreateOneLineHeaderContent(text1, text2); break; case NotificationTemplate.LongHeaderAndShortText: content = cf.CreateTwoLineHeaderContent(text1, text2); break; case NotificationTemplate.ShortHeaderAndTwoTextFields: content = cf.CreateOneLineHeaderContent(text1, text2, text3); break; } if(image != null) { content.SetImage(ImageLoader2.ImageToByteArray(image, GetBaseUri)); } content.SetDuration((DevExpress.Internal.NotificationDuration)PredefinedNotificationDuration); content.SetSound((DevExpress.Internal.PredefinedSound)Sound); return new MvvmPredefinedNotification { Notification = Factory.CreateToastNotification(content) }; } } }
using System; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; using Xunit; namespace AssignAll.Test.Verifiers { /// <summary> /// Superclass of all Unit Tests for DiagnosticAnalyzers /// </summary> public abstract partial class DiagnosticVerifier { #region Formatting Diagnostics /// <summary> /// Helper method to format a Diagnostic into an easily readable string /// </summary> /// <param name="analyzer">The analyzer that this verifier tests</param> /// <param name="diagnostics">The Diagnostics to be formatted</param> /// <returns>The Diagnostics formatted as a string</returns> private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics) { var builder = new StringBuilder(); for (var i = 0; i < diagnostics.Length; ++i) { builder.AppendLine("// " + diagnostics[i]); Type analyzerType = analyzer.GetType(); var rules = analyzer.SupportedDiagnostics; foreach (DiagnosticDescriptor rule in rules) if (rule != null && rule.Id == diagnostics[i].Id) { Location location = diagnostics[i].Location; if (location == Location.None) { builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id); } else { Assert.True(location.IsInSource, $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n"); var resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt"; LinePosition linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition; builder.AppendFormat("{0}({1}, {2}, {3}.{4})", resultMethodName, linePosition.Line + 1, linePosition.Character + 1, analyzerType.Name, rule.Id); } if (i != diagnostics.Length - 1) builder.Append(','); builder.AppendLine(); break; } } return builder.ToString(); } #endregion #region To be implemented by Test classes /// <summary> /// Get the CSharp analyzer being tested - to be implemented in non-abstract class /// </summary> protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return null; } #endregion #region Verifier wrappers /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="source">A class in the form of a string to run the analyzer on</param> /// <param name="expected"> DiagnosticResults that should appear after the analyzer is run on the source</param> protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected) { VerifyDiagnostics(new[] {source}, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source /// Note: input a DiagnosticResult for each Diagnostic expected /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected) { VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); } /// <summary> /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run, /// then verifies each of them. /// </summary> /// <param name="sources">An array of strings to create source documents from to run the analyzers on</param> /// <param name="language">The language of the classes represented by the source strings</param> /// <param name="analyzer">The analyzer to be run on the source code</param> /// <param name="expected">DiagnosticResults that should appear after the analyzer is run on the sources</param> private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected) { var diagnostics = GetSortedDiagnostics(sources, language, analyzer); VerifyDiagnosticResults(diagnostics, analyzer, expected); } #endregion #region Actual comparisons and verifications /// <summary> /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results. /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic. /// </summary> /// <param name="actualResults">The Diagnostics found by the compiler after running the analyzer on the source code</param> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="expectedResults">Diagnostic Results that should have appeared in the code</param> private static void VerifyDiagnosticResults(Diagnostic[] actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults) { var expectedCount = expectedResults.Length; var actualCount = actualResults.Length; if (expectedCount != actualCount) { var diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE."; Assert.True(false, $"Mismatch between number of diagnostics returned, expected \"{expectedCount}\" actual \"{actualCount}\"\r\n\r\nDiagnostics:\r\n{diagnosticsOutput}\r\n"); } for (var i = 0; i < expectedResults.Length; i++) { Diagnostic actual = actualResults.ElementAt(i); DiagnosticResult expected = expectedResults[i]; if (expected.Line == -1 && expected.Column == -1) { if (actual.Location != Location.None) Assert.True(false, $"Expected:\nA project diagnostic with No location\nActual:\n{FormatDiagnostics(analyzer, actual)}"); } else { VerifyDiagnosticLocation(analyzer, actual, actual.Location, expected.Locations.First()); var additionalLocations = actual.AdditionalLocations.ToArray(); if (additionalLocations.Length != expected.Locations.Length - 1) Assert.True(false, $"Expected {expected.Locations.Length - 1} additional locations but got {additionalLocations.Length} for Diagnostic:\r\n {FormatDiagnostics(analyzer, actual)}\r\n"); for (var j = 0; j < additionalLocations.Length; ++j) VerifyDiagnosticLocation(analyzer, actual, additionalLocations[j], expected.Locations[j + 1]); } if (actual.Id != expected.Id) Assert.True(false, $"Expected diagnostic id to be \"{expected.Id}\" was \"{actual.Id}\"\r\n\r\nDiagnostic:\r\n {FormatDiagnostics(analyzer, actual)}\r\n"); if (actual.Severity != expected.Severity) Assert.True(false, $"Expected diagnostic severity to be \"{expected.Severity}\" was \"{actual.Severity}\"\r\n\r\nDiagnostic:\r\n {FormatDiagnostics(analyzer, actual)}\r\n"); if (actual.GetMessage() != expected.Message) Assert.True(false, $"Expected diagnostic message to be \"{expected.Message}\" was \"{actual.GetMessage()}\"\r\n\r\nDiagnostic:\r\n {FormatDiagnostics(analyzer, actual)}\r\n"); } } /// <summary> /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult. /// </summary> /// <param name="analyzer">The analyzer that was being run on the sources</param> /// <param name="diagnostic">The diagnostic that was found in the code</param> /// <param name="actual">The Location of the Diagnostic found in the code</param> /// <param name="expected">The DiagnosticResultLocation that should have been found</param> private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected) { FileLinePositionSpan actualSpan = actual.GetLineSpan(); Assert.True(actualSpan.Path == expected.Path || actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test."), $"Expected diagnostic to be in file \"{expected.Path}\" was actually in file \"{actualSpan.Path}\"\r\n\r\nDiagnostic:\r\n {FormatDiagnostics(analyzer, diagnostic)}\r\n"); LinePosition actualLinePosition = actualSpan.StartLinePosition; // Only check line position if there is an actual line in the real diagnostic if (actualLinePosition.Line > 0) if (actualLinePosition.Line + 1 != expected.Line) Assert.True(false, $"Expected diagnostic to be on line \"{expected.Line}\" was actually on line \"{actualLinePosition.Line + 1}\"\r\n\r\nDiagnostic:\r\n {FormatDiagnostics(analyzer, diagnostic)}\r\n"); // Only check column position if there is an actual column position in the real diagnostic if (actualLinePosition.Character > 0) if (actualLinePosition.Character + 1 != expected.Column) Assert.True(false, $"Expected diagnostic to start at column \"{expected.Column}\" was actually at column \"{actualLinePosition.Character + 1}\"\r\n\r\nDiagnostic:\r\n {FormatDiagnostics(analyzer, diagnostic)}\r\n"); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Forms; using TribalWars.Controls; using TribalWars.Forms.Small; using TribalWars.Maps.AttackPlans.EventArg; using TribalWars.Tools; using TribalWars.Villages; using TribalWars.Villages.Units; using TribalWars.Worlds; namespace TribalWars.Maps.AttackPlans.Controls { /// <summary> /// Control with all <see cref="AttackPlan" />s /// </summary> public partial class AttackPlanCollectionControl : UserControl { #region Fields private readonly Dictionary<AttackPlan, Tuple<ToolStripMenuItem, AttackPlanControl>> _plans = new Dictionary<AttackPlan, Tuple<ToolStripMenuItem, AttackPlanControl>>(); private AttackPlanControl _activePlan; private readonly ToolStripItem[] _visibleWhenNoPlans; #endregion #region Properties private AttackPlanControl ActivePlan { get { return _activePlan; } set { if (_activePlan != value) { if (_activePlan != null) { _activePlan.SetActiveAttacker(null); _activePlan.Visible = false; } if (value != null) { value.Visible = true; } _activePlan = value; } } } private bool IsHelpVisible { get { return AllPlans.Controls.Count == 1 && AllPlans.Controls[0] is AttackHelpControl; } } #endregion #region Constructors public AttackPlanCollectionControl() { InitializeComponent(); _visibleWhenNoPlans = new ToolStripItem[] { VillageInput, VillageInputLabel, cmdAddTarget, cmdAddVillage }; World.Default.EventPublisher.SettingsLoaded += Default_SettingsLoaded; World.Default.Map.EventPublisher.TargetAdded += EventPublisherOnTargetAdded; World.Default.Map.EventPublisher.TargetUpdated += EventPublisherOnTargetUpdated; World.Default.Map.EventPublisher.TargetSelected += EventPublisherOnTargetSelected; World.Default.Map.EventPublisher.TargetRemoved += EventPublisherOnTargetRemoved; } #endregion #region World/Map Event Handlers private void EventPublisherOnTargetSelected(object sender, AttackEventArgs e) { if (ActivePlan == null || ActivePlan.Plan != e.Plan) { foreach (var attackDropDownItem in AttackDropDown.DropDownItems.OfType<ToolStripMenuItem>()) { attackDropDownItem.Checked = false; } if (e.Plan != null) { var selectedPlan = _plans[e.Plan]; selectedPlan.Item1.Checked = true; ActivePlan = selectedPlan.Item2; } else { ActivePlan = null; } } if (ActivePlan != null) { ActivePlan.SetActiveAttacker(e.Attacker); } } private void EventPublisherOnTargetUpdated(object sender, AttackUpdateEventArgs e) { switch (e.Action) { case AttackUpdateEventArgs.ActionKind.Add: e.AttackFrom.ForEach(x => ActivePlan.AddAttacker(x)); break; case AttackUpdateEventArgs.ActionKind.Delete: e.AttackFrom.ForEach(x => ActivePlan.RemoveAttacker(x)); break; case AttackUpdateEventArgs.ActionKind.Update: break; default: Debug.Assert(false); break; } if (e.AttackFrom.Any()) { var plan = e.AttackFrom.First().Plan; _plans[plan].Item1.Text = GetAttackToolstripText(plan); } if (ActivePlan != null) { Debug.Assert(!e.AttackFrom.Any() || ActivePlan.Plan == e.AttackFrom.First().Plan); ActivePlan.SetActiveAttacker(e.AttackFrom.FirstOrDefault()); ActivePlan.UpdateDisplay(); } } private void EventPublisherOnTargetRemoved(object sender, AttackEventArgs e) { RemovePlan(e.Plan); } private void EventPublisherOnTargetAdded(object sender, AttackEventArgs e) { AddPlan(e.Plan); } private void Default_SettingsLoaded(object sender, EventArgs e) { UnitInput.SetWorldUnits(true); UnitInput.Combobox.SelectedIndex = WorldUnits.Default[UnitTypes.Ram].Position + 1; // +1: First Image is null in the Combobox.ImageList World.Default.Map.Manipulators.AttackManipulator.DefaultSpeed = UnitTypes.Ram; VillageTypeInput.Combobox.ImageList = VillageTypeHelper.GetImageList(); _plans.Clear(); AttackDropDown.DropDownItems.Clear(); ActivePlan = null; AllPlans.Controls.Clear(); var plansFromXml = World.Default.Map.Manipulators.AttackManipulator.GetPlans(); foreach (AttackPlan plan in plansFromXml) { AddPlan(plan); } if (_plans.Any()) { World.Default.Map.EventPublisher.AttackSelect(this, _plans.Select(x => x.Key).First()); } else { ShowHelp(); } toolStrip2.Visible = _plans.Any(); foreach (var toolbarItem in toolStrip1.Items.OfType<ToolStripItem>().Where(x => x.Tag == null || x.Tag.ToString() != "OWN_VISIBILITY")) { if (_plans.Any()) { toolbarItem.Visible = true; } else { toolbarItem.Visible = _visibleWhenNoPlans.Contains(toolbarItem); } } } private void ShowHelp() { var attackHelpControl1 = new AttackHelpControl(); attackHelpControl1.Dock = DockStyle.Fill; attackHelpControl1.Location = new System.Drawing.Point(0, 0); attackHelpControl1.Margin = new Padding(0); AllPlans.Controls.Add(attackHelpControl1); } #endregion #region Local Event Handlers private void Timer_Tick(object sender, EventArgs e) { if (ActivePlan != null) ActivePlan.UpdateDisplay(); } private void cmdAddVillage_Click(object sender, EventArgs e) { Village village = VillageInput.Village; if (village != null) { var attackEventArgs = AttackUpdateEventArgs.AddAttackFrom(new AttackPlanFrom(ActivePlan.Plan, village, WorldUnits.Default[UnitTypes.Ram])); World.Default.Map.EventPublisher.AttackUpdateTarget(this, attackEventArgs); } } private void cmdAddTarget_Click(object sender, EventArgs e) { Village village = VillageInput.Village; if (village != null) { World.Default.Map.EventPublisher.AttackAddTarget(this, village); } } private void cmdFind_Click(object sender, EventArgs e) { if (World.Default.You.Empty) { ActivePlayerForm.AskToSetSelf(); } else if (ActivePlan != null) { VillageType? villageType = GetSelectedVillageTypeFilter(); var searchIn = World.Default.Map.Manipulators.AttackManipulator.GetAttackersFromYou(ActivePlan.Plan, UnitInput.Unit, villageType); foreach (var attacker in searchIn) { var attackEventArgs = AttackUpdateEventArgs.AddAttackFrom(new AttackPlanFrom(ActivePlan.Plan, attacker.Village, attacker.Speed)); World.Default.Map.EventPublisher.AttackUpdateTarget(this, attackEventArgs); } ActivePlan.SortOnTimeLeft(); } } private VillageType? GetSelectedVillageTypeFilter() { if (VillageTypeInput.Combobox.SelectedIndex > 0) { return VillageTypeHelper.GetVillageType(VillageTypeInput.Combobox.SelectedIndex); } return null; } private void cmdFindPool_Click(object sender, EventArgs e) { if (World.Default.Map.Manipulators.AttackManipulator.IsAttackersPoolEmpty) { MessageBox.Show(ControlsRes.AttackPlanCollectionControl_EmptyAttackersPool, ControlsRes.AttackPlanCollectionControl_AttackersPoolTitle); } else if (ActivePlan != null && UnitInput.Unit != null) { VillageType? villageType = GetSelectedVillageTypeFilter(); bool depleted; var searchIn = World.Default.Map.Manipulators.AttackManipulator.GetAttackersFromPool(ActivePlan.Plan, UnitInput.Unit, villageType, out depleted); if (depleted) { MessageBox.Show(ControlsRes.AttackPlanCollectionControl_AttackersPoolDepleted, ControlsRes.AttackPlanCollectionControl_AttackersPoolTitle); } foreach (var attacker in searchIn) { var attackEventArgs = AttackUpdateEventArgs.AddAttackFrom(new AttackPlanFrom(ActivePlan.Plan, attacker.Village, attacker.Speed)); World.Default.Map.EventPublisher.AttackUpdateTarget(this, attackEventArgs); } ActivePlan.SortOnTimeLeft(); } } private void cmdClear_Click(object sender, EventArgs e) { if (ActivePlan != null) { World.Default.Map.EventPublisher.AttackUpdateTarget(this, AttackUpdateEventArgs.DeleteAttacksFrom(ActivePlan.Plan.Attacks)); } } private void cmdSort_Click(object sender, EventArgs e) { if (ActivePlan != null) ActivePlan.SortOnTimeLeft(); } #endregion #region AttackPlans private string GetAttackToolstripText(AttackPlan plan) { Village vil = plan.Target; string attackDesc = string.Format(ControlsRes.AttackPlanCollectionControl_PlanExportCaption, vil.LocationString, vil.Name, Common.GetPrettyNumber(vil.Points), plan.Attacks.Count()); if (vil.HasPlayer) attackDesc += string.Format(ControlsRes.AttackPlanCollectionControl_PlanExportCaption_OnPlayer, vil.Player.Name); return attackDesc; } private void AddPlan(AttackPlan plan) { if (IsHelpVisible) { toolStrip1.Items.OfType<ToolStripItem>().Where(x => x.Tag == null || x.Tag.ToString() != "OWN_VISIBILITY").ForEach(x => x.Visible = true); toolStrip2.Visible = true; AllPlans.Controls.Clear(); } var newPlanDropdownItm = new ToolStripMenuItem("", null, SelectPlan); newPlanDropdownItm.Text = GetAttackToolstripText(plan); AttackDropDown.DropDownItems.Add(newPlanDropdownItm); var newPlan = new AttackPlanControl(WorldUnits.Default.ImageList, plan); newPlan.Visible = false; newPlan.Dock = DockStyle.Fill; _plans.Add(plan, new Tuple<ToolStripMenuItem, AttackPlanControl>(newPlanDropdownItm, newPlan)); AllPlans.Controls.Add(newPlan); foreach (AttackPlanFrom attack in plan.Attacks) { newPlan.AddAttacker(attack); } Timer.Enabled = true; } private void RemovePlan(AttackPlan plan) { var attackControls = _plans[plan]; AllPlans.Controls.Remove(attackControls.Item2); AttackDropDown.DropDownItems.Remove(attackControls.Item1); _plans.Remove(plan); if (ActivePlan == attackControls.Item2) { if (AttackDropDown.DropDownItems.Count > 0) { SelectPlan(AttackDropDown.DropDownItems[0], EventArgs.Empty); } else { SelectPlan(null, EventArgs.Empty); } } if (!_plans.Any()) { ShowHelp(); } } private void SelectPlan(object sender, EventArgs e) { var selectedPlan =_plans.Where(x => x.Value.Item1 == sender).ToArray(); World.Default.Map.EventPublisher.AttackSelect(this, !selectedPlan.Any() ? null : selectedPlan.First().Key); } #endregion #region TextOutput private void cmdClipboardText_Click(object sender, EventArgs e) { if (ActivePlan != null) { string export = AttackPlanExporter.GetSinglePlanTextExport(ActivePlan.Plan); WinForms.ToClipboard(export); } } private void cmdClipboardBBCode_Click(object sender, EventArgs e) { if (ActivePlan != null) { string export = AttackPlanExporter.GetSinglePlanBbCodeExport(ActivePlan.Plan); WinForms.ToClipboard(export); } } private void cmdClipboardTextAll_Click(object sender, EventArgs e) { IEnumerable<AttackPlanFrom> plans = GetAllAttacks(); string export = AttackPlanExporter.GetMultiPlanTextExport(plans); WinForms.ToClipboard(export); } private void cmdClipboardBBCodeAll_Click(object sender, EventArgs e) { IEnumerable<AttackPlanFrom> plans = GetAllAttacks(); string export = AttackPlanExporter.GetMultiPlanBbCodeExport(plans); WinForms.ToClipboard(export); } private IEnumerable<AttackPlanFrom> GetAllAttacks() { return _plans.Keys.SelectMany(x => x.Attacks); } #endregion private void UnitInput_Click(object sender, EventArgs e) { if (UnitInput.Unit != null) { World.Default.Map.Manipulators.AttackManipulator.DefaultSpeed = UnitInput.Unit.Type; } } private void VillageInput_TextChanged(object sender, EventArgs e) { cmdAddTarget.Visible = VillageInput.Village != null; cmdAddVillage.Visible = VillageInput.Village != null && _activePlan != null; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace AutofacOwinAuth.WebAPI.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Payroll Transaction History /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class PEFH : EduHubEntity { #region Navigation Property Cache private PE Cache_CODE_PE; private PI Cache_PAYITEM_PI; private PC Cache_TRCENTRE_PC; private PS Cache_PAY_STEP_PS; private KGLSUB Cache_SUBPROGRAM_KGLSUB; private KGLINIT Cache_INITIATIVE_KGLINIT; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// &lt;No documentation available&gt; /// </summary> public int TID { get; internal set; } /// <summary> /// Employee code /// [Uppercase Alphanumeric (10)] /// </summary> public string CODE { get; internal set; } /// <summary> /// Pay item code /// </summary> public short? PAYITEM { get; internal set; } /// <summary> /// Cost centre /// [Uppercase Alphanumeric (10)] /// </summary> public string TRCENTRE { get; internal set; } /// <summary> /// E = Employee pay /// [Uppercase Alphanumeric (1)] /// </summary> public string TRTYPE { get; internal set; } /// <summary> /// Batch number /// </summary> public int? TRBATCH { get; internal set; } /// <summary> /// Payroll group /// </summary> public short? TRPAYCODE { get; internal set; } /// <summary> /// Payroll period number /// </summary> public int? TRPAYPERD { get; internal set; } /// <summary> /// Transaction period (not used) /// </summary> public int? TRPERD { get; internal set; } /// <summary> /// Transaction date /// </summary> public DateTime? TRDATE { get; internal set; } /// <summary> /// Reference /// [Alphanumeric (10)] /// </summary> public string TRREF { get; internal set; } /// <summary> /// Pay rate /// </summary> public double? TRCOST { get; internal set; } /// <summary> /// Hours /// </summary> public double? TRQTY { get; internal set; } /// <summary> /// Dollar value (always positive) /// </summary> public decimal? TRAMT { get; internal set; } /// <summary> /// Addition or Deduction. This controls the arithmetic of TRAMT /// [Uppercase Alphanumeric (1)] /// </summary> public string TRPITYPE { get; internal set; } /// <summary> /// Hrs, Kms, Day, Prd, etc /// [Alphanumeric (3)] /// </summary> public string TRUNIT { get; internal set; } /// <summary> /// Detail /// [Alphanumeric (30)] /// </summary> public string TRDET { get; internal set; } /// <summary> /// Next pay date for employee /// </summary> public DateTime? TRNEXTPAYDATE { get; internal set; } /// <summary> /// Next pay period /// </summary> public int? TRNEXTPAYPERD { get; internal set; } /// <summary> /// No. of pay spans /// </summary> public short? TRPAYSPAN { get; internal set; } /// <summary> /// No. of tax spans /// </summary> public double? TRTAXSPAN { get; internal set; } /// <summary> /// Next pay date for this payroll group /// </summary> public DateTime? PNNEXTPAYDATE { get; internal set; } /// <summary> /// Super fund key (SGL or Personal) /// [Uppercase Alphanumeric (10)] /// </summary> public string SUPER_FUND { get; internal set; } /// <summary> /// Super fund member number /// [Uppercase Alphanumeric (20)] /// </summary> public string SUPER_MEMBER { get; internal set; } /// <summary> /// Field for format only /// </summary> public double? WORKED_HOURS { get; internal set; } /// <summary> /// Pay Rate Step number /// </summary> public short? PAY_STEP { get; internal set; } /// <summary> /// Not used (required for a financial table) /// </summary> public decimal? TRNETT { get; internal set; } /// <summary> /// Not used (required for a financial table) /// </summary> public decimal? GST_AMOUNT { get; internal set; } /// <summary> /// Not used (required for a financial table) /// </summary> public decimal? TRGROSS { get; internal set; } /// <summary> /// "A" Addition or "D" Deduction /// [Uppercase Alphanumeric (1)] /// </summary> public string PAYSIGNTYPE { get; internal set; } /// <summary> /// Indicates which record is tax record /// [Uppercase Alphanumeric (1)] /// </summary> public string SYSTEM_TAX { get; internal set; } /// <summary> /// Line number in the batch /// </summary> public int? LINE_NO { get; internal set; } /// <summary> /// Determines through posts. 0 = Don't show T/P. 1 = Show T/P /// </summary> public int? FLAG { get; internal set; } /// <summary> /// For every transaction there is a subprogram /// [Uppercase Alphanumeric (4)] /// </summary> public string SUBPROGRAM { get; internal set; } /// <summary> /// A subprogram always belongs to a program /// [Uppercase Alphanumeric (3)] /// </summary> public string GLPROGRAM { get; internal set; } /// <summary> /// Transaction might belong to an Initiative /// [Uppercase Alphanumeric (3)] /// </summary> public string INITIATIVE { get; internal set; } /// <summary> /// Holiday pay split precentage, Normal or LPA. Used for leave accruals /// </summary> public double? SPLIT_PERCENT { get; internal set; } /// <summary> /// Alter hours, used in PE31001 to assist with LPA/Annual split calc /// </summary> public double? ALTER_TRQTY { get; internal set; } /// <summary> /// Record annulaised loading percetage used in loading calculation /// </summary> public double? ANNUALISED_LOADING { 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 operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Navigation Properties /// <summary> /// PE (Employees) related entity by [PEFH.CODE]-&gt;[PE.PEKEY] /// Employee code /// </summary> public PE CODE_PE { get { if (Cache_CODE_PE == null) { Cache_CODE_PE = Context.PE.FindByPEKEY(CODE); } return Cache_CODE_PE; } } /// <summary> /// PI (Pay Items) related entity by [PEFH.PAYITEM]-&gt;[PI.PIKEY] /// Pay item code /// </summary> public PI PAYITEM_PI { get { if (PAYITEM == null) { return null; } if (Cache_PAYITEM_PI == null) { Cache_PAYITEM_PI = Context.PI.FindByPIKEY(PAYITEM.Value); } return Cache_PAYITEM_PI; } } /// <summary> /// PC (Cost Centres) related entity by [PEFH.TRCENTRE]-&gt;[PC.PCKEY] /// Cost centre /// </summary> public PC TRCENTRE_PC { get { if (TRCENTRE == null) { return null; } if (Cache_TRCENTRE_PC == null) { Cache_TRCENTRE_PC = Context.PC.FindByPCKEY(TRCENTRE); } return Cache_TRCENTRE_PC; } } /// <summary> /// PS (Pay Steps or Pay Class) related entity by [PEFH.PAY_STEP]-&gt;[PS.PSKEY] /// Pay Rate Step number /// </summary> public PS PAY_STEP_PS { get { if (PAY_STEP == null) { return null; } if (Cache_PAY_STEP_PS == null) { Cache_PAY_STEP_PS = Context.PS.FindByPSKEY(PAY_STEP.Value); } return Cache_PAY_STEP_PS; } } /// <summary> /// KGLSUB (General Ledger Sub Programs) related entity by [PEFH.SUBPROGRAM]-&gt;[KGLSUB.SUBPROGRAM] /// For every transaction there is a subprogram /// </summary> public KGLSUB SUBPROGRAM_KGLSUB { get { if (SUBPROGRAM == null) { return null; } if (Cache_SUBPROGRAM_KGLSUB == null) { Cache_SUBPROGRAM_KGLSUB = Context.KGLSUB.FindBySUBPROGRAM(SUBPROGRAM); } return Cache_SUBPROGRAM_KGLSUB; } } /// <summary> /// KGLINIT (General Ledger Initiatives) related entity by [PEFH.INITIATIVE]-&gt;[KGLINIT.INITIATIVE] /// Transaction might belong to an Initiative /// </summary> public KGLINIT INITIATIVE_KGLINIT { get { if (INITIATIVE == null) { return null; } if (Cache_INITIATIVE_KGLINIT == null) { Cache_INITIATIVE_KGLINIT = Context.KGLINIT.FindByINITIATIVE(INITIATIVE); } return Cache_INITIATIVE_KGLINIT; } } #endregion } }
using System; using System.Collections.ObjectModel; using System.Collections.Generic; using SpriteEditor.SEPositionedObjects; using FlatRedBall; using FlatRedBall.Gui; using FlatRedBall.ManagedSpriteGroups; using FlatRedBall.Math; //using FlatRedBall.Texture; using FlatRedBall.Graphics; using FlatRedBall.Graphics.Model; using FlatRedBall.Collections; using FlatRedBall.Utilities; using FlatRedBall.Input; using EditorObjects; using Microsoft.DirectX; using Microsoft.DirectX.DirectInput; using SpriteEditor.Gui; using FlatRedBall.Graphics.Animation; using EditorObjects.EditorSettings; namespace SpriteEditor { /// <summary> /// Summary description for SECursor. /// </summary> public class SECursor : Cursor { #region Fields SpriteFrameManager sfMan; SpriteList currentSprites; AttachableList<SpriteFrame> currentSpriteFrames; EditAxes axes; public bool axesClicked; public bool soloEdit = false; #region variables for Shift-Move /* Shift-Moving Sprites will only allow movement on one axis. When a Sprite is moved with Shift held down, * either the y or x values are not changed. Which is changed depends on the position of the cursor * vs. the original starting point. If dX is greater than dY, then the Y is constant and x changes. * Whenever we do shift movement, we need to make sure we keep track of the old location. That means when * clicking on a Sprite in move mode, mark the original position by storing it in this value. */ Vector3 accumulatedMovement = new Vector3(0,0,0); List<Vector3> startingPosition; #endregion // When dealing with only one kind of object it's common to use the ObjectGrabbed // property that belongs in the base Cursor class. However, in this application we // deal with a variety of types. Therefore, we use lists for each type. The ObjectGrabbed // should never be used in this class. SpriteList mSpritesOver = new SpriteList(); SpriteList mSpritesGrabbed = new SpriteList(); ReadOnlyCollection<Sprite> mSpritesOverReadOnly; ReadOnlyCollection<Sprite> mSpritesGrabbedReadOnly; PositionedObjectList<SpriteFrame> mSpriteFramesOver = new PositionedObjectList<SpriteFrame>(); PositionedObjectList<SpriteFrame> mSpriteFramesGrabbed = new PositionedObjectList<SpriteFrame>(); ReadOnlyCollection<SpriteFrame> mSpriteFramesOverReadOnly; PositionedObjectList<PositionedModel> mPositionedModelsOver = new PositionedObjectList<PositionedModel>(); PositionedObjectList<PositionedModel> mPositionedModelsGrabbed = new PositionedObjectList<PositionedModel>(); ReadOnlyCollection<PositionedModel> mPositionedModelsOverReadOnly; PositionedObjectList<Text> mTextsOver = new PositionedObjectList<Text>(); PositionedObjectList<Text> mTextsGrabbed = new PositionedObjectList<Text>(); ReadOnlyCollection<Text> mTextsOverReadOnly; // keeps track of if a Sprite has been copied during during this click by control click/drag public bool mCtrlPushCopyThisFrame = false; EditorObjects.RectangleSelector rectangleSelector; #endregion #region Properties #region Public Properties public ReadOnlyCollection<PositionedModel> PositionedModelsOver { get { return mPositionedModelsOverReadOnly; } } public ReadOnlyCollection<Sprite> SpritesOver { get { return mSpritesOverReadOnly; } } public ReadOnlyCollection<SpriteFrame> SpriteFramesOver { get { return mSpriteFramesOverReadOnly; } } public ReadOnlyCollection<Text> TextsOver { get { return mTextsOverReadOnly; } } public ReadOnlyCollection<Sprite> SpritesGrabbed { get { return mSpritesGrabbedReadOnly; } } #endregion #region Private Properties private bool HasObjectGrabbed { get { return mSpritesGrabbed.Count != 0 || mSpriteFramesGrabbed.Count != 0 || mTextsGrabbed.Count != 0 || mPositionedModelsGrabbed.Count != 0 || GameData.sesgMan.SpriteGrabbed != null; } } #endregion #endregion #region Methods #region Constructor public SECursor(EditorCamera cameraTouse, System.Windows.Forms.Form formToUse) : base(cameraTouse, formToUse) { PositionedObjectMover.AllowZMovement = true; startingPosition = new List<Vector3>(); #region Create the read only collections mSpritesOverReadOnly = new ReadOnlyCollection<Sprite>(mSpritesOver); mSpriteFramesOverReadOnly = new ReadOnlyCollection<SpriteFrame>(mSpriteFramesOver); mPositionedModelsOverReadOnly = new ReadOnlyCollection<PositionedModel>(mPositionedModelsOver); mTextsOverReadOnly = new ReadOnlyCollection<Text>(mTextsOver); mSpritesGrabbedReadOnly = new ReadOnlyCollection<Sprite>(mSpritesGrabbed); #endregion } #endregion #region Public Methods public void Initialize() { sfMan = GameData.sfMan; axes = GameData.EditorLogic.EditAxes; currentSprites = GameData.EditorLogic.CurrentSprites; currentSpriteFrames = GameData.EditorLogic.CurrentSpriteFrames; rectangleSelector = new EditorObjects.RectangleSelector(); } public void Activity() { GetObjectOver(); GrabObjects(); // now move the grabbed object ControlGrabbedObject(); SelectOnClick(); TestObjectGrabbedRelease(); } public void ClickSprite(Sprite spriteClicked) { ClickObject(spriteClicked, GameData.EditorLogic.CurrentSprites, false, false); } public void ClickObject<T>(T objectClicked, AttachableList<T> currentObjects, bool simulateShiftDown) where T : PositionedObject, ICursorSelectable, IAttachable, new() { ClickObject(objectClicked, currentObjects, simulateShiftDown, false); } public void ClickObject<T>(T objectClicked, AttachableList<T> currentObjects, bool simulateShiftDown, bool forceSelection) where T : PositionedObject, ICursorSelectable, IAttachable, new() { bool performSelection = forceSelection || ( (WindowOver == null && PrimaryPush) || (WindowOver == null && SecondaryPush) || (WindowOver != null && PrimaryClick) || (WindowOver != null && PrimaryPush) || // on list boxes PrimaryDoubleClick ) && this.axesClicked == false; mCtrlPushCopyThisFrame = false; #region Clicking activity (when the mouse is released rather than pushed if (PrimaryClick) { #region Dragging an attribute from the Attribute List to an object if (GuiManager.CollapseItemDraggedOff != null && GuiManager.CollapseItemDraggedOff.parentBox.Name == "Attributes ListBox" && objectClicked != null) { if (objectClicked.Name.Contains(GuiManager.CollapseItemDraggedOff.Text) == false) { // The objectClicked doesn't have this attribute so add it. // Remove the number, add the attribute, append the number, then make sure this name is unique string temporaryString = StringFunctions.RemoveNumberAtEnd(objectClicked.Name); int numberAtEnd = StringFunctions.GetIntAfter(temporaryString, objectClicked.Name); temporaryString += GuiManager.CollapseItemDraggedOff.Text + numberAtEnd; objectClicked.Name = GameData.GetUniqueNameForObject(temporaryString, objectClicked); GuiData.ListWindow.UpdateItemName(objectClicked); } } #endregion } #endregion #region Didn't click on anything. Get rid of the target box and axes if (objectClicked == null && axes.CursorPushedOnAxis == false && axesClicked == false) { if (simulateShiftDown == false && InputManager.Keyboard.KeyDown(Key.LeftShift) == false && InputManager.Keyboard.KeyDown(Key.RightShift) == false) { // deselect all Sprites if any are selected GameData.DeselectCurrentObjects(currentObjects); return; } } #endregion #region We clicked on the axes, so return. else if (objectClicked == null && axes.CursorPushedOnAxis) { return; } #endregion #region ATTACH - We are going to attach a sprite else if (GuiData.ToolsWindow.attachSprite.IsPressed && currentObjects.Count != 0 && currentObjects[0] != objectClicked) { foreach (PositionedObject positionedObject in currentObjects) { GameData.AttachObjects(positionedObject as PositionedObject, objectClicked); } } #endregion #region Painting else if (GuiData.ToolsWindow.paintButton.IsPressed) { PaintObjectClicked(objectClicked); } #endregion #region Eyedropper - we are retreiving the texture of the Sprite with the eyedropper else if (GuiData.ToolsWindow.eyedropper.IsPressed) { UseEyedropperOnObject(objectClicked); } #endregion #region clicking on a Sprite that has a control point parent else if (objectClicked is ISpriteEditorObject && ((ISpriteEditorObject)objectClicked).type == "Root Control") { ClickSprite(objectClicked.TopParent as Sprite); } #endregion #region simply clicking on an object to select it else if(performSelection) { #region Add the ObjectGrabbed to the UndoManager if (mSpritesGrabbed.Count != 0) { UndoManager.AddToWatch(mSpritesGrabbed[0] as Sprite); } else { // Clear out the objects that the UndoManager is watching UndoManager.RecordUndos<Sprite>(); } #endregion #region if the spriteClicked is already in currentSprites // only when pushing if (currentObjects.Contains(objectClicked) && PrimaryPush) { // If shift is down, remove the Sprite from the group. if ((InputManager.Keyboard.KeyDown(Key.LeftShift) || InputManager.Keyboard.KeyDown(Key.RightShift)) && objectClicked is ISpriteEditorObject) { GameData.DeselectSprite(objectClicked as Sprite); } // Clicking a Sprite in the group brings it to index 0. // This allows the user to click on a Sprite in a group and // display the properties of the just-clicked Sprite in the Properties Window. else if (currentObjects.IndexOf(objectClicked) != 0) { currentObjects.Remove(objectClicked); currentObjects.Insert(0, objectClicked); GuiData.SpritePropertyGrid.SelectedObject = currentObjects[0] as Sprite; } return; } #endregion #region Either Add Sprite to current Sprites if shift clicking or clear out current Sprites and select this one else if ( (SpriteEditorSettings.EditingSprites || SpriteEditorSettings.EditingSpriteFrames || SpriteEditorSettings.EditingModels || SpriteEditorSettings.EditingTexts) && // only consider shift click on push (simulateShiftDown || InputManager.Keyboard.KeyDown(Key.LeftShift) || InputManager.Keyboard.KeyDown(Key.RightShift))) { // If we hit this code shift is either pressed or simulated. currentObjects.AddUnique(objectClicked); } else { GameData.DeselectCurrentObjects(currentObjects); if (currentObjects.Count == 0) currentObjects.Add(objectClicked); else currentObjects[0] = objectClicked; GuiData.ListWindow.Highlight(currentObjects[0]); } #endregion #region if the selected Sprite is an ISpriteEditorObject (regular, as opposed to a Sprite in a SpriteGrid) update collision, pixelSizeExemption, and stored variables ISpriteEditorObject es = currentObjects[0] as ISpriteEditorObject; #endregion #region update the GUI to the new Sprite #region properties window updates if (currentObjects[0] is Sprite) { GuiData.SpritePropertyGrid.SelectedObject = currentObjects[0] as Sprite; GuiManager.BringToFront(GuiData.SpritePropertyGrid); } #endregion if (SpriteEditorSettings.EditingSpriteGrids == false) { GuiData.ToolsWindow.attachSprite.Enabled = true; } if (currentObjects[0].Parent == null) GuiData.ToolsWindow.detachSpriteButton.Enabled = false; else GuiData.ToolsWindow.detachSpriteButton.Enabled = true; if (currentObjects[0].Parent != null || currentObjects[0].Children.Count != 0) GuiData.ToolsWindow.setRootAsControlPoint.Enabled = true; else GuiData.ToolsWindow.setRootAsControlPoint.Enabled = false; GuiData.ToolsWindow.convertToSpriteGridButton.Enabled = true; GuiData.ToolsWindow.convertToSpriteFrame.Enabled = true; if (currentObjects[0] is ISpriteEditorObject && ((ISpriteEditorObject)( currentObjects[0])).type == "Top Root Control") { GuiData.ToolsWindow.setRootAsControlPoint.Text = "Clear Root Control Point"; } else { GuiData.ToolsWindow.setRootAsControlPoint.Text = "Set Root As Control Point"; } #region attach axes, target box, and set the current sprites if(objectClicked is Sprite) SetObjectRelativePosition(objectClicked as Sprite); if (objectClicked is Sprite) { axes.CurrentObject = currentObjects[0]; } #endregion #endregion } #endregion } public void ClickSpriteFrame(SpriteFrame spriteFrameClicked) { if (true) { ClickObject<SpriteFrame>(spriteFrameClicked, GameData.EditorLogic.CurrentSpriteFrames, false); return; } #region Didn't click on anything. Get rid of the target box and axes if (spriteFrameClicked == null && axes.CursorPushedOnAxis == false) { GameData.DeselectCurrentSpriteFrames(); return; } #endregion #region We clicked on the axes, so return. else if (spriteFrameClicked == null && axes.CursorPushedOnAxis) { return; } #endregion #region Painting the SpriteFrame else if (GuiData.ToolsWindow.paintButton.IsPressed && GuiData.ListWindow.HighlightedTexture != null) { spriteFrameClicked.Texture = GuiData.ListWindow.HighlightedTexture; } #endregion #region simply clicking on a SpriteFrame to select it else { #region if the spriteClicked is already in currentSprites, update target boxes and return if (GameData.EditorLogic.CurrentSpriteFrames.Contains(spriteFrameClicked)) { if (GameData.EditorLogic.CurrentSpriteFrames.IndexOf(spriteFrameClicked) != 0) { GameData.EditorLogic.CurrentSpriteFrames.Remove(spriteFrameClicked); GameData.EditorLogic.CurrentSpriteFrames.Insert(0, spriteFrameClicked); } return; } #endregion #region Update the listWindow to reflect the newly-selected object else if (SpriteEditorSettings.EditingSprites && (InputManager.Keyboard.KeyDown(Key.LeftShift) || InputManager.Keyboard.KeyDown(Key.RightShift))) { GameData.EditorLogic.CurrentSpriteFrames.Add(spriteFrameClicked); GuiData.ListWindow.SpriteFrameListBox.HighlightObject(spriteFrameClicked, true); } else { GameData.DeselectCurrentSpriteFrames(); if (GameData.EditorLogic.CurrentSpriteFrames.Count == 0) GameData.EditorLogic.CurrentSpriteFrames.Add(spriteFrameClicked); else GameData.EditorLogic.CurrentSpriteFrames[0] = spriteFrameClicked; GuiData.ListWindow.SpriteFrameListBox.HighlightObject(GameData.EditorLogic.CurrentSpriteFrames[0], false); // why was this next line here? Commented out to see if removing it causes problems // ihMan.SetWatch(sfMan.currentSpriteFrames); } #endregion #region update the GUI to the new SpriteFrame if (SpriteEditorSettings.EditingSpriteGrids == false) { GuiData.ToolsWindow.attachSprite.Enabled = true; } if (GameData.EditorLogic.CurrentSpriteFrames[0].Parent == null) GuiData.ToolsWindow.detachSpriteButton.Enabled = false; else GuiData.ToolsWindow.detachSpriteButton.Enabled = true; if (GameData.EditorLogic.CurrentSpriteFrames[0].Parent != null || GameData.EditorLogic.CurrentSpriteFrames[0].Children.Count != 0) GuiData.ToolsWindow.setRootAsControlPoint.Enabled = true; else GuiData.ToolsWindow.setRootAsControlPoint.Enabled = false; GuiData.ToolsWindow.convertToSpriteGridButton.Enabled = true; GuiData.ToolsWindow.convertToSpriteFrame.Enabled = true; #region set the border side buttons SpriteFrame.BorderSides borderSides = GameData.EditorLogic.CurrentSpriteFrames[0].Borders; // FlatRedBall.MSG.SpriteFram borders = #endregion #region attach axes, target box, and set the current sprites SetObjectRelativePosition(GameData.EditorLogic.CurrentSpriteFrames[0]); axes.Visible = true; axes.origin.AttachTo(GameData.EditorLogic.CurrentSpriteFrames[0], false); #endregion #endregion } #endregion } private int GetObjectIndexOver<T>(AttachableList<T> allSprites, AttachableList<T> currentSpriteArray) where T: PositionedObject, IAttachable, ICursorSelectable { if (axes.CursorPushedOnAxis == true) return -1; #region checking to see which object we are over, considering double clicking, inactives, and the current object selected // this is a temporary object that we will use T temporaryObjectOver = default(T); // first see if we are over the current sprites. They have prescedence over the other sprites, except when the attachSprite is Pressed // When the attachSprite is pressed, we don't want to highlight any of the currentSprites, since they can't be attached to themselves. Highlighting // other Sprites makes attachment eaiser for the user. if (GuiData.ToolsWindow.attachSprite.IsPressed == false) { foreach (T s in currentSpriteArray) { bool isOn = false; if(s is Text) isOn = IsOn3D(s as Text); else isOn = IsOn3D(s); if (isOn) { temporaryObjectOver = s; break; } } } // if we are over the current object, but we double clicked, we need to see if there is a different // object that the cursor is over. // Double clicking tells the SE to "skip" over the current object and grab the next, // allowing the user to grab overlapped objects. Also // if the attachSprite button is pressed, we want to skip over our currentSprite if ((temporaryObjectOver != null && PrimaryDoubleClick == true) || GuiData.ToolsWindow.attachSprite.IsPressed == true) { // what we want to do is remove the Sprite from the spriteArray, then search through it, then insert it back where it // belongs // store the index int index = allSprites.IndexOf(temporaryObjectOver); // store the Sprite (since tempSpriteGrabbed will be overwritten) T temporarilyRemovedSprite = temporaryObjectOver; if (temporaryObjectOver != null) { // remove the sprite from the array allSprites.Remove(temporaryObjectOver); // now, see what the cursor is over temporaryObjectOver = GetSpriteOver(allSprites); // finally, put the Sprite back allSprites.Insert(index, temporarilyRemovedSprite); } else { // skip over our current Sprite if (currentSpriteArray.Count != 0) { temporarilyRemovedSprite = currentSpriteArray[0]; index = allSprites.IndexOf(temporarilyRemovedSprite); allSprites.Remove(temporarilyRemovedSprite); // now, see what the cursor is over temporaryObjectOver = GetSpriteOver(allSprites); // finally, put the Sprite back allSprites.Insert(index, temporarilyRemovedSprite); } } } // even though we are not over our current object, we need to test for double // clicks, because double clicking also allows // the user to select inactive sprites else if (temporaryObjectOver == null) { if (InputManager.Keyboard.KeyDown(Key.D)) { int m = 3; } temporaryObjectOver = GetSpriteOver(allSprites, PrimaryDoubleClick); } #endregion return allSprites.IndexOf(temporaryObjectOver); } public void ToggleSoloEdit() { if(currentSprites.Count != 0) { soloEdit = !soloEdit; } } public string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(base.ToString()).Append("\n").Append("# spriteGrabbed: ").Append(mSpritesGrabbed.Count); sb.Append("\n").Append(rectangleSelector.ToString()); return sb.ToString(); } public void VerifyAndUpdateGrabbedAgainstCurrent() { if (mSpritesGrabbed.Count != 0 && GameData.EditorLogic.CurrentSprites.Count != 0 && GameData.EditorLogic.CurrentSprites.Contains(mSpritesGrabbed[0]) == false) { mSpritesGrabbed.Clear(); mSpritesGrabbed.Add(GameData.EditorLogic.CurrentSprites[0]); } } #endregion #region Private Methods #region XML Docs /// <summary> /// Moves, scales, and rotates grabbed objects. /// </summary> #endregion private void ControlGrabbedObject() { if (HasObjectGrabbed && axes.CursorPushedOnAxis == false) // if we have a sprite grabbed { #region Get distanceFromCamera float distanceFromCamera = 0; if (mSpritesGrabbed.Count != 0) { distanceFromCamera = (float)(mSpritesGrabbed[0].Z - mCamera.Z); } else if (mSpriteFramesGrabbed.Count != 0) { distanceFromCamera = (float)(mSpriteFramesGrabbed[0].Z - mCamera.Z); } else if (mTextsGrabbed.Count != 0) { distanceFromCamera = (float)(mTextsGrabbed[0].Z - mCamera.Z); } else if (mPositionedModelsGrabbed.Count != 0) { distanceFromCamera = (float)(mPositionedModelsGrabbed[0].Z - mCamera.Z); } #endregion if (GuiData.ToolsWindow.MoveButton.IsPressed) MoveGrabbedObject(); else if (GuiData.ToolsWindow.RotateButton.IsPressed) RotateObjects(); else if (GuiData.ToolsWindow.ScaleButton.IsPressed) ScaleObjects(distanceFromCamera); } } private MovementStyle GetCurrentMovementStyle() { bool isAltDown = InputManager.Keyboard.KeyDown(Key.LeftAlt) || InputManager.Keyboard.KeyDown(Key.RightAlt); // default to Hierarchy - change if appropriate MovementStyle movementStyle = MovementStyle.Hierarchy; if (isAltDown) { movementStyle = MovementStyle.IgnoreAttachments; } else if (GuiData.ToolsWindow.groupHierarchyControlButton.IsPressed) { movementStyle = MovementStyle.Hierarchy; } else { movementStyle = MovementStyle.Group; } return movementStyle; } private Sprite GetSpriteOver() { int index = GetObjectIndexOver<Sprite>(GameData.Scene.Sprites, currentSprites); if (index != -1) { return GameData.Scene.Sprites[index]; } else { return null; } } private SpriteFrame GetSpriteFrameOver() { int index = GetObjectIndexOver(GameData.Scene.SpriteFrames, GameData.EditorLogic.CurrentSpriteFrames); if (index != -1) return GameData.Scene.SpriteFrames[index]; else return null; } private Text GetTextOver() { int index = GetObjectIndexOver(GameData.Scene.Texts, GameData.EditorLogic.CurrentTexts); if (index != -1) return GameData.Scene.Texts[index]; else return null; } private PositionedModel GetPositionedModelOver() { int index = GetObjectIndexOver(GameData.Scene.PositionedModels, GameData.EditorLogic.CurrentPositionedModels); if (index != -1) return GameData.Scene.PositionedModels[index]; else return null; } private void GetObjectOver() { GetSpritesOver(); GetSpriteFramesOver(); GetPositionedModelsOver(); GetTextsOver(); } private void GetSpritesOver() { mSpritesOver.Clear(); if (SpriteEditorSettings.EditingSprites) { if (this.WindowPushed == null && !HasObjectGrabbed && axes.CursorPushedOnAxis == false) { rectangleSelector.Control(); rectangleSelector.GetObjectsOver(GameData.Scene.Sprites, mSpritesOver); } if (mSpritesOver.Count == 0) { Sprite spriteOver = GetSpriteOver(); if (spriteOver != null) mSpritesOver.Add(spriteOver); } } } private void GetSpriteFramesOver() { mSpriteFramesOver.Clear(); if (SpriteEditorSettings.EditingSpriteFrames) { if (this.WindowPushed == null && HasObjectGrabbed == false && axes.CursorPushedOnAxis == false) { rectangleSelector.Control(); rectangleSelector.GetObjectsOver(GameData.Scene.SpriteFrames, mSpriteFramesOver); } if (mSpriteFramesOver.Count == 0) { SpriteFrame spriteFrameOver = GetSpriteFrameOver(); if (spriteFrameOver != null) mSpriteFramesOver.Add(spriteFrameOver); } } } private void GetPositionedModelsOver() { mPositionedModelsOver.Clear(); if (SpriteEditorSettings.EditingModels) { if (this.WindowPushed == null && HasObjectGrabbed == false && axes.CursorPushedOnAxis == false) { rectangleSelector.Control(); rectangleSelector.GetObjectsOver(GameData.Scene.PositionedModels, mPositionedModelsOver); } if (mPositionedModelsOver.Count == 0) { PositionedModel positionedModelOver = GetPositionedModelOver(); if (positionedModelOver != null) mPositionedModelsOver.Add(positionedModelOver); } } } private void GetTextsOver() { mTextsOver.Clear(); if (SpriteEditorSettings.EditingTexts) { if (this.WindowPushed == null && HasObjectGrabbed == false && axes.CursorPushedOnAxis == false) { rectangleSelector.Control(); rectangleSelector.GetObjectsOver(GameData.Scene.Texts, mTextsOver); } if (mTextsOver.Count == 0) { Text text = GetTextOver(); if (text != null) mTextsOver.Add(text); } } } private void GrabObjects() { GrabSprites(); GrabSpriteFrames(); GrabPositionedModels(); GrabTexts(); } private void GrabPositionedModels() { Cursor cursor = GuiManager.Cursor; if (SpriteEditorSettings.EditingModels && cursor.WindowOver == null && cursor.PrimaryPush) { mPositionedModelsGrabbed.Clear(); mPositionedModelsGrabbed.AddRange(mPositionedModelsOver); if (mPositionedModelsOver.Count != 0) { PositionedObjectMover.SetStartPosition(mPositionedModelsOver[0]); bool shouldDeselect = true; // If the user selects a PositionedModel that is already selected, then don't deselect. if (mPositionedModelsOver.Count == 1 && GameData.EditorLogic.CurrentPositionedModels.Contains(mPositionedModelsOver[0])) shouldDeselect = false; if (GuiData.ToolsWindow.attachSprite.IsPressed) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentObjects<PositionedModel>(GameData.EditorLogic.CurrentPositionedModels); // See GrabSprites for info on this call foreach (PositionedModel positionedModel in mPositionedModelsOver) this.ClickObject(positionedModel, GameData.EditorLogic.CurrentPositionedModels, true, true); } } } private void GrabSprites() { Cursor cursor = GuiManager.Cursor; if (SpriteEditorSettings.EditingSprites && cursor.WindowOver == null && (cursor.PrimaryPush || cursor.SecondaryPush)) { mSpritesGrabbed.Clear(); mSpritesGrabbed.AddRange(mSpritesOver); if (mSpritesOver.Count != 0) { PositionedObjectMover.SetStartPosition(mSpritesOver[0]); bool shouldDeselect = true; // If the user selects a Sprite that is already selected, then don't deselect. if (mSpritesOver.Count == 1 && GameData.EditorLogic.CurrentSprites.Contains(mSpritesOver[0])) shouldDeselect = false; if (GuiData.ToolsWindow.attachSprite.IsPressed) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentSprites(); // This selects all Sprites in the rectangle selector. // the arguments are as follows: // s - The Sprite to select // GameData.EditorLogic.CurrentSprites - the list of objects which contains the current object. This is used to determine // the type of the object to select // true (first) - Whether to simulate shift down. This simulates the behavior of selecting every // sprite in newlySelectedSprites with the Shift key down. // true (second) - This tells the ClickObject method that we are performing a valid selection. Normally selections // are only performed when pushing the mouse button and not on a in-SpriteEditor Window or when clicking the // mouse button when on a window. This code is only reached when clicking when not in a window. Basically // we are telling the ClickObject method "I know you normally don't select objects in this kind of situation, // but just trust us this time." foreach (Sprite sprite in mSpritesOver) this.ClickObject(sprite, GameData.EditorLogic.CurrentSprites, true, true); } } } private void GrabSpriteFrames() { Cursor cursor = GuiManager.Cursor; if (SpriteEditorSettings.EditingSpriteFrames && cursor.WindowOver == null && cursor.PrimaryPush) { mSpriteFramesGrabbed.Clear(); mSpriteFramesGrabbed.AddRange(mSpriteFramesOver); if (mSpriteFramesOver.Count != 0) { PositionedObjectMover.SetStartPosition(mSpriteFramesOver[0]); bool shouldDeselect = true; // If the user selects a Sprite that is already selected, then don't deselect. if (mSpriteFramesOver.Count == 1 && GameData.EditorLogic.CurrentSpriteFrames.Contains(mSpriteFramesOver[0])) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentSpriteFrames(); // See GrabSprites for info on this call foreach (SpriteFrame spriteFrame in mSpriteFramesOver) this.ClickObject(spriteFrame, GameData.EditorLogic.CurrentSpriteFrames, true, true); } } } private void GrabTexts() { Cursor cursor = GuiManager.Cursor; if (SpriteEditorSettings.EditingTexts && cursor.WindowOver == null && cursor.PrimaryPush) { mTextsGrabbed.Clear(); mTextsGrabbed.AddRange(mTextsOver); if (mTextsOver.Count != 0) { PositionedObjectMover.SetStartPosition(mTextsOver[0]); bool shouldDeselect = true; // If the user selects a Sprite that is already selected, then don't deselect. if (mTextsOver.Count == 1 && GameData.EditorLogic.CurrentTexts.Contains(mTextsOver[0])) shouldDeselect = false; if (GuiData.ToolsWindow.attachSprite.IsPressed) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentTexts(); // See GrabSprites for info on this call foreach (Text text in mTextsOver) this.ClickObject(text, GameData.EditorLogic.CurrentTexts, true, true); } } } #region Move/Scale/Rotate private void MoveGrabbedObject() { if (PrimaryDown || SecondaryDown) { #region ctrl + click occured, so copy the object grabbed if (mCtrlPushCopyThisFrame == false && PrimaryPush && (InputManager.Keyboard.KeyDown(Key.LeftControl) || InputManager.Keyboard.KeyDown(Key.RightControl)) && (mSpritesGrabbed.Count != 0 || mSpriteFramesGrabbed.Count != 0 || mPositionedModelsGrabbed.Count != 0 || mTextsGrabbed.Count != 0) ) { GuiData.ToolsWindow.DuplicateClick(); mCtrlPushCopyThisFrame = true; } #endregion AttachableList<PositionedObject> objectsMoving = null; #region If editing SpriteGrids if(SpriteEditorSettings.EditingSpriteGrids) { PositionedObject spriteToMove2 = GameData.sesgMan.SpriteGrabbed; #region when pushing down button, reset the accumulatedMovement vector to 0 if (PrimaryPush || SecondaryPush || startingPosition.Count == 0) { accumulatedMovement = new Vector3(0, 0, 0); startingPosition.Clear(); if (HasObjectGrabbed) startingPosition.Add(new Vector3(spriteToMove2.X, spriteToMove2.Y, spriteToMove2.Z)); } #endregion Vector3 movementVector = new Vector3(0, 0, 0); #region get the movementVector depending on whether cursorPlaneXY is pressed Sprite objectGrabbed = GameData.sesgMan.SpriteGrabbed; if (PrimaryDown) { movementVector.X = WorldXChangeAt(objectGrabbed.Z); movementVector.Y = WorldYChangeAt(objectGrabbed.Z); } else if (SecondaryDown) { StaticPosition = true; if (YVelocity != 0) { movementVector.Z = YVelocity / 10.0f; } } #endregion #region if G is not down, move the entire grid if (!InputManager.Keyboard.KeyDown(Key.G)) { SpriteGrid spriteGrid = SESpriteGridManager.CurrentSpriteGrid; spriteGrid.Shift(movementVector.X, movementVector.Y, movementVector.Z); spriteGrid.XLeftBound += movementVector.X; spriteGrid.XRightBound += movementVector.X; spriteGrid.YTopBound += movementVector.Y; spriteGrid.YBottomBound += movementVector.Y; spriteGrid.ZCloseBound += movementVector.Z; spriteGrid.ZFarBound += movementVector.Z; SESpriteGridManager.oldPosition.X = currentSprites[0].X; SESpriteGridManager.oldPosition.Y = currentSprites[0].Y; SESpriteGridManager.oldPosition.Z = currentSprites[0].Z; } #endregion #region G is down, so move just one Sprite else { accumulatedMovement.X += movementVector.X; accumulatedMovement.Y += movementVector.Y; accumulatedMovement.Z += movementVector.Z; spriteToMove2.X = startingPosition[0].X + accumulatedMovement.X; spriteToMove2.Y = startingPosition[0].Y + accumulatedMovement.Y; if (accumulatedMovement.Z != 0) { spriteToMove2.Z = startingPosition[0].Z + accumulatedMovement.Z; GameData.Scene.Sprites.SortZInsertionDescending(); } } #endregion } #endregion #region else editing something else else { MovementStyle movementStyle = GetCurrentMovementStyle(); if (SpriteEditorSettings.EditingSprites) { PositionedObjectMover.MouseMoveObjects(GameData.EditorLogic.CurrentSprites, movementStyle); } else if (SpriteEditorSettings.EditingSpriteFrames) { PositionedObjectMover.MouseMoveObjects(GameData.EditorLogic.CurrentSpriteFrames, movementStyle); } else if (SpriteEditorSettings.EditingModels) { PositionedObjectMover.MouseMoveObjects(GameData.EditorLogic.CurrentPositionedModels, movementStyle); } else if (SpriteEditorSettings.EditingTexts) { PositionedObjectMover.MouseMoveObjects(GameData.EditorLogic.CurrentTexts, movementStyle); } } #endregion } } private void ApplyMovementVector(Vector3 movementVector, AttachableList<PositionedObject> spritesToApplyTo) { for (int i = 0; i < spritesToApplyTo.Count; i++) { spritesToApplyTo[i].X = startingPosition[i].X + movementVector.X; spritesToApplyTo[i].Y = startingPosition[i].Y + movementVector.Y; spritesToApplyTo[i].Z = startingPosition[i].Z + movementVector.Z; } } private void RotateObjects() { if (YVelocity == 0) return; MovementStyle movementStyle = GetCurrentMovementStyle(); if (SpriteEditorSettings.EditingSprites) { PositionedObjectRotator.MouseRotateObjects(GameData.EditorLogic.CurrentSprites, movementStyle); } else if (SpriteEditorSettings.EditingSpriteFrames) { PositionedObjectRotator.MouseRotateObjects(GameData.EditorLogic.CurrentSpriteFrames, movementStyle); } else if (SpriteEditorSettings.EditingModels) { PositionedObjectRotator.MouseRotateObjects(GameData.EditorLogic.CurrentPositionedModels, movementStyle); } else if (SpriteEditorSettings.EditingTexts) { PositionedObjectRotator.MouseRotateObjects(GameData.EditorLogic.CurrentTexts, movementStyle); } } private void ScaleObjects(float distanceFromCamera) { if (GameData.Cursor.XVelocity == 0 && GameData.Cursor.YVelocity == 0) return; #region loop through all currentSprites foreach (Sprite s in GameData.EditorLogic.CurrentSprites) { #region T key is not down, so we are not doing sticky scaling if (InputManager.Keyboard.KeyDown(Key.T) == false) { StaticPosition = true; #region Current Sprite is ISpriteEditorObject if (s as ISpriteEditorObject != null) { if (PrimaryDown) { float xMultiplier; float yMultiplier; if ((s.RotationZ > (float)System.Math.PI * 0.25f && s.RotationZ < (float)System.Math.PI * 0.75f) || (s.RotationZ > (float)System.Math.PI * 1.25f && s.RotationZ < (float)System.Math.PI * 1.75f)) { // Since the object is rotated us the Y for ScaleX and X for Scaley xMultiplier = YVelocity / 100.0f; yMultiplier = XVelocity / 100.0f; } else { xMultiplier = XVelocity / 100.0f; yMultiplier = YVelocity / 100.0f; } (s).ScaleX *= xMultiplier + 1; (s).ScaleY *= yMultiplier + 1; if (InputManager.Keyboard.KeyDown(Key.LeftShift) || InputManager.Keyboard.KeyDown(Key.RightShift)) { (s).ScaleX = (s).ScaleY * GameData.EditorLogic.xToY; xMultiplier = yMultiplier; } if (mSpritesGrabbed.Count != 0 && (((EditorSprite)mSpritesGrabbed[0]).type == "Top Root Control")) { for (int i = s.Children.Count - 1; i > -1; i--) { GameData.ApplyRelativeScale((Sprite)s.Children[i], xMultiplier, yMultiplier); } } } else // secondary down { /* if (spriteGrabbed.type == "Top Root Control") { foreach (PositionedObject po in s.Children) { GameData.ApplyRelativeScale((Sprite)po, 0, 0, yVelocity / 4.0f); } } */ } } #endregion #region Current Sprite is not ISpriteEditorObject else { if (s.RotationZ == (float)System.Math.PI * .5f || s.RotationZ == (float)System.Math.PI * 1.5f) { s.ScaleX *= 1 + YVelocity / 100.0f; s.ScaleY *= 1 + XVelocity / 100.0f; } else { s.ScaleX *= 1 + XVelocity / 100.0f; s.ScaleY *= 1 + YVelocity / 100.0f; } if (InputManager.Keyboard.KeyDown(Key.LeftShift) || InputManager.Keyboard.KeyDown(Key.RightShift)) s.ScaleX = s.ScaleY * GameData.EditorLogic.xToY; } #endregion } #endregion #region Sticky is down so don't make the cursor static else StaticPosition = false; #endregion } #endregion #region loop through all SpriteFrames foreach (SpriteFrame sf in GameData.EditorLogic.CurrentSpriteFrames) { if (sf.RotationZ == (float)System.Math.PI * .5f || sf.RotationZ == (float)System.Math.PI * 1.5f) { sf.ScaleX *= 1 + YVelocity / 100.0f; sf.ScaleY *= 1 + XVelocity / 100.0f; } else { sf.ScaleX *= 1 + XVelocity / 100.0f; sf.ScaleY *= 1 + YVelocity / 100.0f; } if (InputManager.Keyboard.KeyDown(Key.LeftShift) || InputManager.Keyboard.KeyDown(Key.RightShift)) sf.ScaleX = sf.ScaleY * GameData.EditorLogic.xToY; StaticPosition = true; } #endregion foreach (Text text in GameData.EditorLogic.CurrentTexts) { float scaleAmount = 1 + YVelocity / 100.0f; text.Scale *= scaleAmount; text.Spacing *= scaleAmount; text.NewLineDistance *= scaleAmount; StaticPosition = true; } #region Loop through all Models foreach (PositionedModel model in GameData.EditorLogic.CurrentPositionedModels) { if (PrimaryDown) { model.ScaleX *= 1 + XVelocity / 100.0f; model.ScaleY *= 1 + YVelocity / 100.0f; } else if (SecondaryDown) { model.ScaleZ *= 1 + YVelocity / 100.0f; } StaticPosition = true; } #endregion } #endregion private void PaintObjectClicked<T>(T objectClicked) where T : PositionedObject, ICursorSelectable, IAttachable, new() { // painting SpriteGrid is handled in the sesgManager's grabGridSprite method if (SESpriteGridManager.CurrentSpriteGrid == null) { #region If editing Sprites if (objectClicked is EditorSprite) { EditorSprite asEditorSprite = objectClicked as EditorSprite; #region Painting AnimationChain if (GameData.EditorLogic.CurrentAnimationChainList != null) { // make sure the same AnimationChainList isn't being applied if (GameData.EditorLogic.CurrentAnimationChainList.Name != asEditorSprite.AnimationChains.Name) { asEditorSprite.AnimationChains = GameData.EditorLogic.CurrentAnimationChainList.Clone(); // Start the animation too if (asEditorSprite.AnimationChains.Count != 0) { asEditorSprite.SetAnimationChain(asEditorSprite.AnimationChains[0]); asEditorSprite.Animate = true; } } } #endregion #region else, painting Texture with possible display region else if(GuiData.ListWindow.HighlightedTexture != null) { // In case it's animated, stop the animation asEditorSprite.Animate = false; if (asEditorSprite.ColorOperation == Microsoft.DirectX.Direct3D.TextureOperation.SelectArg2 && asEditorSprite.Texture == null) { // This thing was an untextured Sprite. Let's give it a texture AND change its color // operation so the texture shows up asEditorSprite.ColorOperation = Microsoft.DirectX.Direct3D.TextureOperation.SelectArg1; } asEditorSprite.Texture = GuiData.ListWindow.HighlightedTexture; DisplayRegion displayRegion = GuiData.ListWindow.HighlightedDisplayRegion; if (displayRegion != null) { asEditorSprite.TopTextureCoordinate = displayRegion.Top; asEditorSprite.BottomTextureCoordinate = displayRegion.Bottom; asEditorSprite.LeftTextureCoordinate = displayRegion.Left; asEditorSprite.RightTextureCoordinate = displayRegion.Right; } else { asEditorSprite.TopTextureCoordinate = 0; asEditorSprite.BottomTextureCoordinate = 1; asEditorSprite.LeftTextureCoordinate = 0; asEditorSprite.RightTextureCoordinate = 1; } } #endregion } #endregion #region If editing SpriteFrames else if (objectClicked is SpriteFrame) { if (GuiData.ListWindow.HighlightedTexture != null) { SpriteFrame asSpriteFrame = objectClicked as SpriteFrame; asSpriteFrame.Texture = GuiData.ListWindow.HighlightedTexture; } } #endregion } } private void SelectOnClick() { if (this.WindowPushed == null && PrimaryClick && axesClicked == false && soloEdit == false) { #region Sprite select on click bool shouldDeselect = true; // If the user selects a Sprite that is already selected, then don't deselect. if (mSpritesOver.Count == 1 && GameData.EditorLogic.CurrentSprites.Contains(mSpritesOver[0])) shouldDeselect = false; if (SESpriteGridManager.CurrentSpriteGrid != null) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentSprites(); // This selects all Sprites in the rectangle selector. // the arguments are as follows: // s - The Sprite to select // GameData.EditorLogic.CurrentSprites - the list of objects which contains the current object. This is used to determine // the type of the object to select // true (first) - Whether to simulate shift down. This simulates the behavior of selecting every // sprite in newlySelectedSprites with the Shift key down. // true (second) - This tells the ClickObject method that we are performing a valid selection. Normally selections // are only performed when pushing the mouse button and not on a in-SpriteEditor Window or when clicking the // mouse button when on a window. This code is only reached when clicking when not in a window. Basically // we are telling the ClickObject method "I know you normally don't select objects in this kind of situation, // but just trust us this time." foreach (Sprite s in mSpritesOver) this.ClickObject(s, GameData.EditorLogic.CurrentSprites, true, true); #endregion #region SpriteFrame select on click shouldDeselect = true; // If the user selects a Sprite that is already selected, then don't deselect. if (mSpriteFramesOver.Count == 1 && GameData.EditorLogic.CurrentSpriteFrames.Contains(mSpriteFramesOver[0])) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentSpriteFrames(); foreach (SpriteFrame spriteFrame in mSpriteFramesOver) this.ClickObject(spriteFrame, GameData.EditorLogic.CurrentSpriteFrames, true, true); #endregion #region PositionedModels select on click shouldDeselect = true; // If the user selects a Sprite that is already selected, then don't deselect. if (mPositionedModelsOver.Count == 1 && GameData.EditorLogic.CurrentPositionedModels.Contains(mPositionedModelsOver[0])) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentObjects<PositionedModel>(GameData.EditorLogic.CurrentPositionedModels); foreach (PositionedModel positionedModel in mPositionedModelsOver) this.ClickObject(positionedModel, GameData.EditorLogic.CurrentPositionedModels, true, true); #endregion #region Text select on click shouldDeselect = true; // If the user selects a Text that is already selected, then don't deselect. if (mTextsOver.Count == 1 && GameData.EditorLogic.CurrentTexts.Contains(this.mTextsOver[0])) shouldDeselect = false; if (shouldDeselect && !InputManager.Keyboard.KeyDown(Key.LeftShift) && !InputManager.Keyboard.KeyDown(Key.RightShift)) GameData.DeselectCurrentObjects<Text>(GameData.EditorLogic.CurrentTexts); foreach (Text text in mTextsOver) this.ClickObject(text, GameData.EditorLogic.CurrentTexts, true, true); #endregion } } private void TestObjectGrabbedRelease() { if (!PrimaryDown && !SecondaryDown) { #region Release logic for Sprites if (mSpritesGrabbed.Count != 0) { if (SpriteEditorSettings.EditingSprites) { if (GameData.EditorLogic.SnappingManager.ShouldSnap) { // later will want to consider parents and multiple Sprites. mSpritesGrabbed[0].Position = GameData.EditorLogic.SnappingManager.SnappingPosition; } } UndoManager.RecordUndos<Sprite>(); UndoManager.ClearObjectsWatching<Sprite>(); mSpritesGrabbed.Clear(); } #endregion if (mSpriteFramesGrabbed.Count != 0) { if (SpriteEditorSettings.EditingSpriteFrames) { if (GameData.EditorLogic.SnappingManager.ShouldSnap) { // later will want to consider parents and multiple Sprites. mSpriteFramesGrabbed[0].Position = GameData.EditorLogic.SnappingManager.SnappingPosition; } } UndoManager.RecordUndos<SpriteFrame>(); UndoManager.ClearObjectsWatching<SpriteFrame>(); mSpriteFramesGrabbed.Clear(); } if (mTextsGrabbed.Count != 0) { UndoManager.RecordUndos<Text>(); UndoManager.ClearObjectsWatching<Text>(); mTextsGrabbed.Clear(); } if (mPositionedModelsGrabbed.Count != 0) { UndoManager.RecordUndos<PositionedModel>(); UndoManager.ClearObjectsWatching<PositionedModel>(); mPositionedModelsGrabbed.Clear(); } } } private void UseEyedropperOnObject<T>(T target) where T : PositionedObject, ICursorSelectable, IAttachable, new() { #region First check if the object has an AnimationChainList IAnimationChainAnimatable animationChainAnimatable = target as IAnimationChainAnimatable; if (animationChainAnimatable != null && animationChainAnimatable.Animate && animationChainAnimatable.AnimationChains != null && animationChainAnimatable.AnimationChains.Count != 0) { GuiData.ListWindow.HighlightAnimationChainListByName( animationChainAnimatable.AnimationChains.Name); GuiData.ListWindow.ViewingAnimationChains = true; } #endregion #region else, try to get the object's texture else if (target is ITexturable) { ITexturable texturable = target as ITexturable; GuiData.ListWindow.Highlight(texturable.Texture); if (texturable.Texture != null) { GuiData.ToolsWindow.currentTextureDisplay.SetOverlayTextures(texturable.Texture, null); // and set the texture coordinates if(texturable is Sprite) { Sprite asSprite = texturable as Sprite; GuiData.TextureCoordinatesSelectionWindow.LeftTU = asSprite.LeftTextureCoordinate; GuiData.TextureCoordinatesSelectionWindow.RightTU = asSprite.RightTextureCoordinate; GuiData.TextureCoordinatesSelectionWindow.TopTV = asSprite.TopTextureCoordinate; GuiData.TextureCoordinatesSelectionWindow.BottomTV = asSprite.BottomTextureCoordinate; } } else GuiData.ToolsWindow.currentTextureDisplay.SetOverlayTextures(null, null); } #endregion } #endregion #endregion } }
using System; using System.IO; using System.Net; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using Zeus; using Zeus.Projects; using Zeus.Serializers; using Zeus.UserInterface; using Zeus.UserInterface.WinForms; using MyMeta; using WeifenLuo.WinFormsUI.Docking; namespace MyGeneration { public delegate void TextChangedEventHandler(string text, string tabText, string filename); public delegate void ProjectExecutionStatusHandler(bool isRunning, string message); public partial class ProjectBrowserControl : UserControl { private const int INDEX_CLOSED_FOLDER = 0; private const int INDEX_OPEN_FOLDER = 1; private ZeusProcessStatusDelegate _executionCallback; private ProjectTreeNode _rootNode; private FormAddEditModule _formEditModule = new FormAddEditModule(); private FormAddEditSavedObject _formEditSavedObject; private bool _isDirty = false; private bool _collectInChildProcess = false; public event TextChangedEventHandler TabTextChanged; public event ProjectExecutionStatusHandler ExecutionStatusUpdate; public event EventHandler ErrorsOccurred; public event EventHandler ExecutionStarted; public ProjectBrowserControl() { InitializeComponent(); _executionCallback = new ZeusProcessStatusDelegate(ExecutionCallback); _formEditSavedObject = new FormAddEditSavedObject(_collectInChildProcess); } protected void OnExecutionStatusUpdate(bool isRunning, string message) { if (ExecutionStatusUpdate != null) { ExecutionStatusUpdate(isRunning, message); } } protected void OnExecutionStarted() { if (ExecutionStarted != null) { ExecutionStarted(this, EventArgs.Empty); } } protected void OnErrorsOccurred(Exception ex) { if (ErrorsOccurred != null) { ErrorsOccurred(ex, EventArgs.Empty); } } protected void OnTextChanged(string text, string tabText, string filename) { if (TabTextChanged != null) { TabTextChanged(text, tabText, filename); } } public bool CollectInChildProcess { get { return _collectInChildProcess; } set { _collectInChildProcess = value; } } public string GetPersistString() { if (this._rootNode != null && this._rootNode.Project != null && this._rootNode.Project.FilePath != null) { return "file," + this._rootNode.Project.FilePath; } else { return "type," + ProjectEditorManager.MYGEN_PROJECT; } } public void SetToolTip(string str) { this.toolTipProjectBrowser.SetToolTip(treeViewProject, str); } public string DocumentIndentity { get { return (this.FileName == string.Empty) ? this._rootNode.Project.Name : this.FileName; } } public string FileName { get { if (_rootNode.Project.FilePath != null) { return _rootNode.Project.FilePath; } else { return string.Empty; } } } public string CompleteFilePath { get { string tmp = this.FileName; if (tmp != string.Empty) { FileInfo attr = new FileInfo(tmp); tmp = attr.FullName; } return tmp; } } public bool IsDirty { get { return this._isDirty; } } public bool CanClose(bool allowPrevent) { return PromptForSave(allowPrevent); } private bool PromptForSave(bool allowPrevent) { bool canClose = true; if (this.IsDirty) { DialogResult result; if (allowPrevent) { result = MessageBox.Show("This project has been modified, Do you wish to save before closing?", this.FileName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); } else { result = MessageBox.Show("This project has been modified, Do you wish to save before closing?", this.FileName, MessageBoxButtons.YesNo, MessageBoxIcon.Question); } switch (result) { case DialogResult.Yes: this.Save(); break; case DialogResult.Cancel: canClose = false; break; } } return canClose; } #region TreeView Event Handlers private void treeViewProject_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e) { if ((e.Node is ProjectTreeNode) || (e.Node is ModuleTreeNode)) { e.Node.SelectedImageIndex = INDEX_OPEN_FOLDER; e.Node.ImageIndex = INDEX_OPEN_FOLDER; } } private void treeViewProject_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e) { if ((e.Node is ProjectTreeNode) || (e.Node is ModuleTreeNode)) { e.Node.SelectedImageIndex = INDEX_CLOSED_FOLDER; e.Node.ImageIndex = INDEX_CLOSED_FOLDER; } } private void treeViewProject_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { TreeNode node = (TreeNode)treeViewProject.GetNodeAt(e.X, e.Y); treeViewProject.SelectedNode = node; } //TODO: Add keypress events private void treeViewProject_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F5) { //------------------ } } private void treeViewProject_DoubleClick(object sender, System.EventArgs e) { Edit(false); } private object lastObject = null; private void treeViewProject_MouseMove(object sender, MouseEventArgs e) { object obj = treeViewProject.GetNodeAt(e.X, e.Y); if (object.Equals(obj, lastObject) || (obj == null && lastObject == null)) { return; } else { if (obj is SavedObjectTreeNode) { this.toolTipProjectBrowser.SetToolTip(treeViewProject, ((SavedObjectTreeNode)obj).SavedObject.SavedObjectName); } else if (obj is ProjectTreeNode) { this.toolTipProjectBrowser.SetToolTip(treeViewProject, ((ProjectTreeNode)obj).Project.Description); } else if (obj is ModuleTreeNode) { this.toolTipProjectBrowser.SetToolTip(treeViewProject, ((ModuleTreeNode)obj).Module.Description); } else { this.toolTipProjectBrowser.SetToolTip(treeViewProject, string.Empty); } lastObject = obj; } } #endregion #region ContextMenu Event Handlers private void contextMenuTree_Popup(object sender, System.EventArgs e) { this.contextItemAddModule.Visible = this.contextItemAddSavedObject.Visible = this.contextItemEdit.Visible = this.contextItemExecute.Visible = this.contextItemRemove.Visible = this.contextItemSave.Visible = this.contextItemCopy.Visible = this.contextItemSaveAs.Visible = this.contextItemCacheSettings.Visible = this.menuItemSep01.Visible = this.menuItemSep02.Visible = this.menuItemSep03.Visible = false; SortedProjectTreeNode node = this.treeViewProject.SelectedNode as SortedProjectTreeNode; if (node is ProjectTreeNode) { this.contextItemSave.Visible = this.contextItemSaveAs.Visible = this.contextItemAddModule.Visible = this.contextItemAddSavedObject.Visible = this.contextItemEdit.Visible = this.contextItemExecute.Visible = this.contextItemCacheSettings.Visible = true; this.menuItemSep01.Visible = true; this.menuItemSep02.Visible = true; this.menuItemSep03.Visible = true; } else if (node is ModuleTreeNode) { this.contextItemAddModule.Visible = this.contextItemAddSavedObject.Visible = this.contextItemEdit.Visible = this.contextItemExecute.Visible = this.contextItemRemove.Visible = this.contextItemCacheSettings.Visible = true; this.menuItemSep01.Visible = true; this.menuItemSep02.Visible = true; this.menuItemSep03.Visible = false; } else if (node is SavedObjectTreeNode) { this.contextItemEdit.Visible = this.contextItemExecute.Visible = this.contextItemCopy.Visible = this.contextItemRemove.Visible = true; this.menuItemSep01.Visible = true; this.menuItemSep02.Visible = false; this.menuItemSep03.Visible = false; } } private void contextItemEdit_Click(object sender, System.EventArgs e) { Edit(); } private void contextItemAddModule_Click(object sender, System.EventArgs e) { SortedProjectTreeNode node = this.treeViewProject.SelectedNode as SortedProjectTreeNode; if ((node is ModuleTreeNode) || (node is ProjectTreeNode)) { ZeusModule module = node.Tag as ZeusModule; ZeusModule newmodule = new ZeusModule(); this._formEditModule.Module = newmodule; if (this._formEditModule.ShowDialog() == DialogResult.OK) { this._isDirty = true; module.ChildModules.Add(newmodule); ModuleTreeNode newNode = new ModuleTreeNode(newmodule); node.AddSorted(newNode); node.Expand(); } } } private void contextItemAddSavedObject_Click(object sender, System.EventArgs e) { SortedProjectTreeNode node = this.treeViewProject.SelectedNode as SortedProjectTreeNode; if ((node is ModuleTreeNode) || (node is ProjectTreeNode)) { ZeusModule module = node.Tag as ZeusModule; SavedTemplateInput savedInput = new SavedTemplateInput(); this._formEditSavedObject.Module = module; this._formEditSavedObject.SavedObject = savedInput; if (this._formEditSavedObject.ShowDialog() == DialogResult.OK) { this._isDirty = true; module.SavedObjects.Add(savedInput); SavedObjectTreeNode newNode = new SavedObjectTreeNode(savedInput); node.AddSorted(newNode); node.Expand(); this.treeViewProject.SelectedNode = newNode; } } } private void contextItemCopy_Click(object sender, System.EventArgs e) { SortedProjectTreeNode node = this.treeViewProject.SelectedNode as SortedProjectTreeNode; if (node is SavedObjectTreeNode) { SavedTemplateInput input = node.Tag as SavedTemplateInput; SavedTemplateInput copy = input.Copy(); SortedProjectTreeNode moduleNode = node.Parent as SortedProjectTreeNode; ZeusModule module = moduleNode.Tag as ZeusModule; string copyName = copy.SavedObjectName; string newName = copyName; int count = 1; bool found; do { found = false; foreach (SavedTemplateInput tmp in module.SavedObjects) { if (tmp.SavedObjectName == newName) { found = true; newName = copyName + " " + count++; break; } } } while (found); copy.SavedObjectName = newName; module.SavedObjects.Add(copy); SavedObjectTreeNode copiedNode = new SavedObjectTreeNode(copy); moduleNode.AddSorted(copiedNode); this._isDirty = true; } } private void contextItemCacheSettings_Click(object sender, System.EventArgs e) { SortedProjectTreeNode node = this.treeViewProject.SelectedNode as SortedProjectTreeNode; if ((node is ModuleTreeNode) || (node is ProjectTreeNode)) { ZeusModule module = node.Tag as ZeusModule; ZeusContext context = new ZeusContext(); DefaultSettings settings = DefaultSettings.Instance; settings.PopulateZeusContext(context); module.SavedItems.Add(context.Input); } } private void contextItemRemove_Click(object sender, System.EventArgs e) { SortedProjectTreeNode node = this.treeViewProject.SelectedNode as SortedProjectTreeNode; SortedProjectTreeNode parentnode; if (node is ModuleTreeNode) { parentnode = node.Parent as SortedProjectTreeNode; ZeusModule parentmodule = parentnode.Tag as ZeusModule; ZeusModule module = node.Tag as ZeusModule; parentmodule.ChildModules.Remove(module); parentnode.Nodes.Remove(node); this._isDirty = true; } else if (node is SavedObjectTreeNode) { parentnode = node.Parent as SortedProjectTreeNode; ZeusModule parentmodule = parentnode.Tag as ZeusModule; SavedTemplateInput savedobj = node.Tag as SavedTemplateInput; parentmodule.SavedObjects.Remove(savedobj); parentnode.Nodes.Remove(node); this._isDirty = true; } } private void contextItemSave_Click(object sender, System.EventArgs e) { Save(); } private void contextItemSaveAs_Click(object sender, System.EventArgs e) { SaveAs(); } private void contextItemExecute_Click(object sender, System.EventArgs e) { this.Execute(); } #endregion #region Load Project Tree public void CreateNewProject() { this.treeViewProject.Nodes.Clear(); ZeusProject proj = new ZeusProject(); proj.DefaultSettingsDelegate = new GetDefaultSettingsDelegate(GetDefaultSettingsDictionary); proj.Name = "New Project"; proj.Description = "New Zeus Project file"; _rootNode = new ProjectTreeNode(proj); _rootNode.Expand(); OnTextChanged("Project: " + proj.Name, proj.Name, null); this.treeViewProject.Nodes.Add(_rootNode); } public void LoadProject(string filename) { this.treeViewProject.Nodes.Clear(); ZeusProject proj = new ZeusProject(filename); proj.DefaultSettingsDelegate = new GetDefaultSettingsDelegate(GetDefaultSettingsDictionary); if (proj.Load()) { OnTextChanged("Project: " + proj.Name, proj.Name, filename); _rootNode = new ProjectTreeNode(proj); foreach (ZeusModule module in proj.ChildModules) { LoadModule(_rootNode, module); } foreach (SavedTemplateInput input in proj.SavedObjects) { _rootNode.AddSorted(new SavedObjectTreeNode(input)); } } _rootNode.Expand(); this.treeViewProject.Nodes.Add(_rootNode); } public Dictionary<string, string> GetDefaultSettingsDictionary() { Dictionary<string, string> ds = new Dictionary<string, string>(); DefaultSettings.Instance.PopulateDictionary(ds); return ds; } private void LoadModule(SortedProjectTreeNode parentNode, ZeusModule childModule) { ModuleTreeNode childNode = new ModuleTreeNode(childModule); parentNode.AddSorted(childNode); foreach (ZeusModule grandchildModule in childModule.ChildModules) { LoadModule(childNode, grandchildModule); } foreach (SavedTemplateInput input in childModule.SavedObjects) { childNode.AddSorted(new SavedObjectTreeNode(input)); } } #endregion #region Execute, Save, SaveAs, Edit public void Execute() { this.Save(); ZeusProject proj = this._rootNode.Project; Cursor.Current = Cursors.WaitCursor; TreeNode node = this.treeViewProject.SelectedNode; DefaultSettings settings = DefaultSettings.Instance; if (node is ProjectTreeNode) { OnExecutionStarted(); ZeusProcessManager.ExecuteProject(proj.FilePath, ExecutionCallback); } else if (node is ModuleTreeNode) { ZeusModule module = node.Tag as ZeusModule; OnExecutionStarted(); ZeusProcessManager.ExecuteModule(proj.FilePath, module.ProjectPath, ExecutionCallback); //module.Execute(settings.ScriptTimeout, log); } else if (node is SavedObjectTreeNode) { SavedTemplateInput savedinput = node.Tag as SavedTemplateInput; ZeusModule module = node.Parent.Tag as ZeusModule; OnExecutionStarted(); ZeusProcessManager.ExecuteProjectItem(proj.FilePath, module.ProjectPath + "/" + savedinput.SavedObjectName, ExecutionCallback); //savedinput.Execute(settings.ScriptTimeout, log); } } private void ExecutionCallback(ZeusProcessStatusEventArgs args) { if (args.Message != null) { if (this.InvokeRequired) { this.Invoke(_executionCallback, args); } else { this.OnExecutionStatusUpdate(args.IsRunning, args.Message); if (!args.IsRunning) { Cursor.Current = Cursors.Default; } } } } public void Save() { if (this._rootNode.Project.FilePath != null) { _isDirty = false; this._rootNode.Project.Save(); } else { this.SaveAs(); } } public void SaveAs() { Stream myStream; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Zeus Project (*.zprj)|*.zprj|All files (*.*)|*.*"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; ZeusProject proj = this._rootNode.Project; if (proj.FilePath != null) { saveFileDialog.FileName = proj.FilePath; } if (saveFileDialog.ShowDialog() == DialogResult.OK) { myStream = saveFileDialog.OpenFile(); if (null != myStream) { _isDirty = false; myStream.Close(); proj.FilePath = saveFileDialog.FileName; proj.Save(); } } } public void Edit() { Edit(true); } public void Edit(bool allowEditFolders) { SortedProjectTreeNode node = this.treeViewProject.SelectedNode as SortedProjectTreeNode; SortedProjectTreeNode parentnode; if ( allowEditFolders && ((node is ModuleTreeNode) || (node is ProjectTreeNode)) ) { ZeusModule module = node.Tag as ZeusModule; this._formEditModule.Module = module; if (this._formEditModule.ShowDialog() == DialogResult.OK) { this._isDirty = true; node.Text = module.Name; parentnode = node.Parent as SortedProjectTreeNode; if (parentnode != null) { node.Remove(); parentnode.AddSorted(node); this.treeViewProject.SelectedNode = node; } if (node is ProjectTreeNode) { OnTextChanged("Project: " + module.Name, module.Name, _rootNode.Project.FilePath); } } } else if (node is SavedObjectTreeNode) { if (_collectInChildProcess) Save(); SavedTemplateInput input = node.Tag as SavedTemplateInput; ZeusModule parentMod = node.Parent.Tag as ZeusModule; this._formEditSavedObject.Module = parentMod; this._formEditSavedObject.SavedObject = input; if (this._formEditSavedObject.ShowDialog() == DialogResult.OK) { this._isDirty = true; node.Text = input.SavedObjectName; parentnode = node.Parent as SortedProjectTreeNode; if (parentnode != null) { node.Remove(); parentnode.AddSorted(node); this.treeViewProject.SelectedNode = node; } } } } #endregion } #region Project Browser Tree Node Classes public abstract class SortedProjectTreeNode : TreeNode { public int AddSorted(TreeNode newnode) { int insertIndex = -1; for (int i = 0; i < this.Nodes.Count; i++) { TreeNode node = this.Nodes[i]; if (node.GetType() == newnode.GetType()) { if (newnode.Text.CompareTo(node.Text) <= 0) { insertIndex = i; break; } } else if (newnode is SavedObjectTreeNode) { continue; } else { insertIndex = i; break; } } if (insertIndex == -1) { insertIndex = this.Nodes.Add(newnode); } else { this.Nodes.Insert(insertIndex, newnode); } return insertIndex; } } public class ProjectTreeNode : SortedProjectTreeNode { public ProjectTreeNode(ZeusProject proj) { this.Tag = proj; this.Text = proj.Name; this.ImageIndex = 1; this.SelectedImageIndex = 1; } public ZeusProject Project { get { return this.Tag as ZeusProject; } } } public class ModuleTreeNode : SortedProjectTreeNode { public ModuleTreeNode(ZeusModule module) { this.Tag = module; this.Text = module.Name; this.ImageIndex = 0; this.SelectedImageIndex = 0; } public ZeusModule Module { get { return this.Tag as ZeusModule; } } } public class SavedObjectTreeNode : SortedProjectTreeNode { public SavedObjectTreeNode(SavedTemplateInput templateInput) { this.Tag = templateInput; this.ForeColor = Color.Blue; this.Text = templateInput.SavedObjectName; this.ImageIndex = 2; this.SelectedImageIndex = 2; } public SavedTemplateInput SavedObject { get { return this.Tag as SavedTemplateInput; } } } #endregion }
using UnityEngine; using UnityEditor; using System.IO; using System; using System.Diagnostics; using System.Threading; using System.Text; using System.Xml; using System.Linq; public static class AndroidPostProcessor { class KeyStoreInfo { public string KeyStoreFile; public string StorePass; public string KeyPass; public string Alias; public KeyStoreInfo() { // Construct the default Android debug keystore info // http://developer.android.com/tools/publishing/app-signing.html KeyStoreFile = Path.Combine(AndroidPostProcessor.GetUserDir(), ".android/debug.keystore"); StorePass = "android"; KeyPass = "android"; Alias = "androiddebugkey"; } } private static string APKToolDir = null; private static string BuildToolsDir = ""; private static string BuildToolsVersion = "21.1.2"; private static string GetAPKToolDir() { if (!string.IsNullOrEmpty(APKToolDir)) { return APKToolDir; } string path = Path.Combine( Application.dataPath, "CoherentUI/Editor/apktool2.0.0"); if (!Directory.Exists(path)) { path = Path.Combine(Application.dataPath, "Editor/apktool2.0.0"); if (!Directory.Exists(path)) { UnityEngine.Debug.LogError("Unable to locate APKTool path!"); return null; } } APKToolDir = path; return APKToolDir; } public static string GetLatestBuildToolsDir() { if(!string.IsNullOrEmpty(BuildToolsDir)) { return BuildToolsDir; } string apkToolDir= GetAPKToolDir(); string searchDir = Path.Combine(GetAndroidSDKDir(), "build-tools"); if (!Directory.Exists(searchDir)) { UnityEngine.Debug.Log("build-tools folder not found in SDK folder." + " Falling back to packaged build tools."); BuildToolsDir = apkToolDir; return BuildToolsDir; } string[] buildToolsSubdirs = Directory.GetDirectories(searchDir); if (buildToolsSubdirs.Length == 0) { UnityEngine.Debug.Log( "No directories found in SDK/build-tools folder." + " Falling back to packaged build tools."); BuildToolsDir = apkToolDir; return BuildToolsDir; } Array.Sort(buildToolsSubdirs); var latestBuildTools = Array.FindLast( buildToolsSubdirs, (f) => { string[] version = Path.GetFileName(f).Split(new char[]{'.'}); if(version.Length > 0) { int versionMajorNumber = 0; return int.TryParse(version[0], out versionMajorNumber); } return false; }); if(String.IsNullOrEmpty(latestBuildTools)) { BuildToolsDir = apkToolDir; return BuildToolsDir; } var latestBuildToolsVersion = Path.GetFileName(latestBuildTools); if(string.Compare(latestBuildToolsVersion, BuildToolsVersion) < 0) { UnityEngine.Debug.Log( "The build tools found in SDK/build-tools" + " are older version than the packaged." + " Falling back to packaged build tools."); BuildToolsDir = apkToolDir; return BuildToolsDir; } BuildToolsDir = latestBuildTools; BuildToolsVersion = latestBuildToolsVersion; return BuildToolsDir; } public static void FindAndCopySdkAaptAndZipalign() { string buildTools = GetLatestBuildToolsDir(); string apkToolsDir = GetAPKToolDir(); if(string.Compare(apkToolsDir, BuildToolsDir) != 0) { var filesForCopy = Directory.GetFiles(buildTools, "aapt*"); filesForCopy = filesForCopy.Union( Directory.GetFiles(buildTools, "zipalign*")).ToArray(); if (filesForCopy.Count() == 0) { UnityEngine.Debug.Log( "aapt and zipalign not found in SDK/build-tools folder." + " Falling back to packaged aapt and zipalign."); return; } UnityEngine.Debug.Log("Using aapt and zipalign, version " + BuildToolsVersion); foreach(string file in filesForCopy) { File.Copy(file, Path.Combine(apkToolsDir, Path.GetFileName(file)), true); } } } private static bool IsWindowsHost() { return Environment.OSVersion.Platform == PlatformID.Win32NT || Environment.OSVersion.Platform == PlatformID.Win32S || Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Platform == PlatformID.WinCE; } private static string GetUserDir() { string path = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName; if (IsWindowsHost() && Environment.OSVersion.Version.Major >= 6) { path = Directory.GetParent(path).FullName; } return path; } private static KeyStoreInfo GetKeyStoreInfo() { KeyStoreInfo ksInfo = new KeyStoreInfo(); if (!string.IsNullOrEmpty(PlayerSettings.Android.keystoreName)) { ksInfo.KeyStoreFile = PlayerSettings.Android.keystoreName; ksInfo.StorePass = PlayerSettings.Android.keystorePass; ksInfo.KeyPass = PlayerSettings.Android.keyaliasPass; ksInfo.Alias = PlayerSettings.Android.keyaliasName; } return ksInfo; } private static void StartProcess(string processName, string args) { Process process = new Process(); process.StartInfo.FileName = processName; process.StartInfo.Arguments = args; process.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory(); string pathEnv = process.StartInfo.EnvironmentVariables["PATH"]; char pathSeparator = IsWindowsHost() ? ';' : ':'; pathEnv += pathSeparator + GetAPKToolDir(); process.StartInfo.EnvironmentVariables["PATH"] = pathEnv; //UnityEngine.Debug.Log (processName + " " + args); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); int timeout = 30000; using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) { using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputWaitHandle.Set(); } else { output.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { errorWaitHandle.Set(); } else { error.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // Process completed if (output.Length > 0) { UnityEngine.Debug.Log(processName + ": " + output.ToString()); } if (error.Length > 0) { UnityEngine.Debug.LogWarning(processName + ": " + error.ToString()); } } else { // Timed out UnityEngine.Debug.LogError(processName + " timed out!"); } } } } public static void ModifyManifestFile(string pathToManifest, bool apiLevel11OrGreater) { XmlDocument doc = new XmlDocument(); doc.Load(pathToManifest); XmlElement manifest = doc.DocumentElement; if (manifest.Name != "manifest") { throw new ApplicationException("Invalid Android.xml file: manifest element is not root!"); } XmlAttribute androidNamespace = manifest.Attributes["xmlns:android"]; if (androidNamespace == null) { throw new ApplicationException("Invalid Android.xml file: unable to determine android namespace!"); } XmlElement application = manifest["application"]; if (application == null) { throw new ApplicationException("Invalid Android.xml file: unable to locate application element!"); } if (apiLevel11OrGreater) { // Enable hardware acceleration XmlAttribute attr = doc.CreateAttribute("android", "hardwareAccelerated", androidNamespace.Value); attr.Value = "true"; application.Attributes.Append(attr); } // Enable forwarding native events to VM for native activities XmlNode nativeActivity = null; foreach (XmlNode child in application.ChildNodes) { if (child.Name == "activity") { XmlAttribute name = child.Attributes["android:name"]; if (name != null && name.Value.EndsWith("NativeActivity")) { nativeActivity = child; break; } } } if (nativeActivity != null) { XmlNode metaData = null; if (nativeActivity != null) { foreach (XmlNode child in nativeActivity.ChildNodes) { if (child.Name == "meta-data") { XmlAttribute name = child.Attributes["android:name"]; if (name != null && name.Value == "unityplayer.ForwardNativeEventsToDalvik") { metaData = child; } } } } if (metaData == null) { // Create and append element metaData = doc.CreateElement("meta-data"); XmlAttribute attr = doc.CreateAttribute("android", "name", androidNamespace.Value); attr.Value = "unityplayer.ForwardNativeEventsToDalvik"; metaData.Attributes.Append(attr); attr = doc.CreateAttribute("android", "value", androidNamespace.Value); attr.Value = "true"; metaData.Attributes.Append(attr); nativeActivity.AppendChild(metaData); } else { // Make sure the value is true XmlAttribute val = metaData.Attributes["android:value"]; if (val == null) { XmlAttribute attr = doc.CreateAttribute("android", "value", androidNamespace.Value); attr.Value = "true"; metaData.Attributes.Append(attr); } else { val.Value = "true"; } } } doc.Save(pathToManifest); } public static void UnpackAPK(string pathToApk, string dirToUnpack) { StartProcess("java", string.Format("-jar \"{0}\" d -f --aapt \"{1}\" \"{2}\" -o \"{3}\"", Path.Combine(GetAPKToolDir(), "apktool.jar"), GetAPKToolDir(), pathToApk, dirToUnpack)); } public static void RepackAPK(string pathToApk, string unpackedDir) { bool apiLevel11OrGreater = (PlayerSettings.Android.minSdkVersion >= AndroidSdkVersions.AndroidApiLevel11); ModifyManifestFile(Path.Combine(unpackedDir, "AndroidManifest.xml"), apiLevel11OrGreater); CleanStreamingAssets(Path.Combine(unpackedDir, "assets")); CopyMobileNetDll(Path.Combine(unpackedDir, "assets/bin/Data/Managed"), Path.Combine(Application.dataPath, "Plugins")); // Pack the unpacked apk StartProcess("java", string.Format("-jar \"{0}\" b \"{1}\"", Path.Combine(GetAPKToolDir(), "apktool.jar"), unpackedDir)); // Sign the apk string apkName = Path.GetFileName(pathToApk); string pathToRepackedApk = Path.Combine(Path.Combine(unpackedDir, "dist"), apkName); KeyStoreInfo ksInfo = GetKeyStoreInfo(); StartProcess("jarsigner", string.Format("-sigalg MD5withRSA -digestalg SHA1 -keystore \"{0}\" -storepass {1} -keypass {2} \"{3}\" {4}", ksInfo.KeyStoreFile, ksInfo.StorePass, ksInfo.KeyPass, pathToRepackedApk, ksInfo.Alias ) ); // Align the apk string zipalignExt = Application.platform == RuntimePlatform.WindowsEditor ? ".exe" : ""; string pathToZipAlign = Path.Combine(GetAPKToolDir(), "zipalign" + zipalignExt); StartProcess(pathToZipAlign, string.Format("-f 4 \"{0}\" \"{1}\"", pathToRepackedApk, pathToApk)); // Delete the temp dir Directory.Delete(unpackedDir, true); } private static string GetAndroidSDKDir() { const string AndroidSdkRootKey = "AndroidSdkRoot"; if (EditorPrefs.HasKey(AndroidSdkRootKey)) { return EditorPrefs.GetString(AndroidSdkRootKey); } else { string sdkRoot = EditorUtility.OpenFolderPanel("Please select Android SDK directory", "", ""); return sdkRoot; } } private static void CleanStreamingAssets(string dataFolder) { string[] dlls = { Path.Combine(dataFolder, "CoherentUINet.dll64"), Path.Combine(dataFolder, "CoherentUI64_Native.dll"), }; foreach (var file in dlls) { if (File.Exists(file)) { File.Delete(file); } } string hostDir = Path.Combine(dataFolder, "CoherentUI_Host"); if(Directory.Exists(hostDir)) { Directory.Delete(hostDir, true); } } internal static void CopyMobileNetDll( string managedResourcesFolder, string pluginsFolder) { // Overwrite the iOS MobileNet dll with the Android one string mobileDll = Path.Combine( managedResourcesFolder, "CoherentUIMobileNet.dll"); string androidNetDll = Path.Combine(pluginsFolder, "CoherentUIMobileNet.android"); if (File.Exists(androidNetDll)) { File.Copy(androidNetDll, mobileDll, true); } } public static void CleanUpForAndroid(string pluginsFolder) { DirectoryInfo dirInfo = new DirectoryInfo(pluginsFolder); if (dirInfo == null || !dirInfo.Exists) { return; } // Delete every directory != "Android" foreach (var item in dirInfo.GetDirectories()) { if (item.Name != "Android") { Directory.Delete(item.FullName, true); } } // Delete every file that doesn't match CoherentUIMobile* foreach (var item in dirInfo.GetFiles()) { if (!item.Name.StartsWith("CoherentUIMobile")) { File.Delete(item.FullName); } } } }
// Amplify Occlusion - Robust Ambient Occlusion for Unity Pro // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; [AddComponentMenu( "" )] public class AmplifyOcclusionBase : MonoBehaviour { public enum ApplicationMethod { PostEffect = 0, Deferred, Debug } public enum PerPixelNormalSource { None = 0, Camera, GBuffer, GBufferOctaEncoded, } public enum SampleCountLevel { Low = 0, Medium, High, VeryHigh } [Header( "Ambient Occlusion" )] public ApplicationMethod ApplyMethod = ApplicationMethod.PostEffect; public SampleCountLevel SampleCount = SampleCountLevel.Medium; public PerPixelNormalSource PerPixelNormals = PerPixelNormalSource.Camera; [Range( 0, 1 )] public float Intensity = 1.0f; public Color Tint = Color.black; [Range( 0, 16 )] public float Radius = 1.0f; [Range( 0, 16 )] public float PowerExponent = 1.8f; [Range( 0, 0.99f )] public float Bias = 0.05f; public bool CacheAware = false; public bool Downsample = false; [Header( "Bilateral Blur" )] public bool BlurEnabled = true; [Range( 1, 4 )] public int BlurRadius = 2; [Range( 1, 4 )] public int BlurPasses = 1; [Range( 0, 20 )] public float BlurSharpness = 10.0f; private const int PerPixelNormalSourceCount = 4; private int prevScreenWidth = 0; private int prevScreenHeight = 0; private bool prevHDR = false; private ApplicationMethod prevApplyMethod; private SampleCountLevel prevSampleCount; private PerPixelNormalSource prevPerPixelNormals; private bool prevCacheAware; private bool prevDownscale; private bool prevBlurEnabled; private int prevBlurRadius; private int prevBlurPasses; private Camera m_camera; private Material m_occlusionMat; private Material m_blurMat; private Material m_copyMat; private Texture2D m_randomTex; private const int RandomSize = 4; private const int DirectionCount = 8; private Color[] m_randomData; private string[] m_layerOffsetNames = null; private string[] m_layerRandomNames = null; private string[] m_layerDepthNames = null; private string[] m_layerNormalNames = null; private string[] m_layerOcclusionNames = null; private RenderTexture m_occlusionRT = null; private int[] m_depthLayerRT = null; private int[] m_normalLayerRT = null; private int[] m_occlusionLayerRT = null; private int m_mrtCount = 0; private RenderTargetIdentifier[] m_depthTargets = null; private RenderTargetIdentifier[] m_normalTargets = null; private int m_deinterleaveDepthPass = 0; private int m_deinterleaveNormalPass = 0; private RenderTargetIdentifier[] m_applyDeferredTargets = null; private Mesh m_blitMesh = null; private TargetDesc m_target = new TargetDesc(); private Dictionary<CameraEvent,CommandBuffer> m_registeredCommandBuffers = new Dictionary<CameraEvent,CommandBuffer>(); #if TRIAL private Texture2D watermark = null; #endif private static class ShaderPass { public const int FullDepth = 0; public const int FullNormal_None = 1; public const int FullNormal_Camera = 2; public const int FullNormal_GBuffer = 3; public const int FullNormal_GBufferOctaEncoded = 4; public const int DeinterleaveDepth1 = 5; public const int DeinterleaveNormal1_None = 6; public const int DeinterleaveNormal1_Camera = 7; public const int DeinterleaveNormal1_GBuffer = 8; public const int DeinterleaveNormal1_GBufferOctaEncoded = 9; public const int DeinterleaveDepth4 = 10; public const int DeinterleaveNormal4_None = 11; public const int DeinterleaveNormal4_Camera = 12; public const int DeinterleaveNormal4_GBuffer = 13; public const int DeinterleaveNormal4_GBufferOctaEncoded = 14; public const int OcclusionCache_Low = 15; public const int OcclusionCache_Medium = 16; public const int OcclusionCache_High = 17; public const int OcclusionCache_VeryHigh = 18; public const int Reinterleave = 19; public const int OcclusionLow_None = 20; public const int OcclusionLow_Camera = 21; public const int OcclusionLow_GBuffer = 22; public const int OcclusionLow_GBufferOctaEncoded = 23; public const int OcclusionMedium_None = 24; public const int OcclusionMedium_Camera = 25; public const int OcclusionMedium_GBuffer = 26; public const int OcclusionMedium_GBufferOctaEncoded = 27; public const int OcclusionHigh_None = 28; public const int OcclusionHigh_Camera = 29; public const int OcclusionHigh_GBuffer = 30; public const int OcclusionHigh_GBufferOctaEncoded = 31; public const int OcclusionVeryHigh_None = 32; public const int OcclusionVeryHigh_Camera = 33; public const int OcclusionVeryHigh_GBuffer = 34; public const int OcclusionVeryHigh_GBufferNormalEncoded = 35; public const int ApplyDebug = 36; public const int ApplyDeferred = 37; public const int ApplyDeferredLog = 38; public const int ApplyPostEffect = 39; public const int ApplyPostEffectLog = 40; public const int CombineDownsampledOcclusionDepth = 41; public const int BlurHorizontal1 = 0; public const int BlurVertical1 = 1; public const int BlurHorizontal2 = 2; public const int BlurVertical2 = 3; public const int BlurHorizontal3 = 4; public const int BlurVertical3 = 5; public const int BlurHorizontal4 = 6; public const int BlurVertical4 = 7; public const int Copy = 0; } private struct TargetDesc { public int fullWidth; public int fullHeight; public RenderTextureFormat format; public int width; public int height; public int quarterWidth; public int quarterHeight; public float padRatioWidth; public float padRatioHeight; } bool CheckParamsChanged() { bool changed = ( prevScreenWidth != m_camera.pixelWidth ) || ( prevScreenHeight != m_camera.pixelHeight ) || ( prevHDR != m_camera.hdr ) || ( prevApplyMethod != ApplyMethod ) || ( prevSampleCount != SampleCount ) || ( prevPerPixelNormals != PerPixelNormals ) || ( prevCacheAware != CacheAware ) || ( prevDownscale != Downsample ) || ( prevBlurEnabled != BlurEnabled ) || ( prevBlurRadius != BlurRadius ) || ( prevBlurPasses != BlurPasses ); return changed; } void UpdateParams() { prevScreenWidth = m_camera.pixelWidth; prevScreenHeight = m_camera.pixelHeight; prevHDR = m_camera.hdr; prevApplyMethod = ApplyMethod; prevSampleCount = SampleCount; prevPerPixelNormals = PerPixelNormals; prevCacheAware = CacheAware; prevDownscale = Downsample; prevBlurEnabled = BlurEnabled; prevBlurRadius = BlurRadius; prevBlurPasses = BlurPasses; } void Warmup() { CheckMaterial(); CheckRandomData(); m_depthLayerRT = new int[ 16 ]; m_normalLayerRT = new int[ 16 ]; m_occlusionLayerRT = new int[ 16 ]; m_mrtCount = Mathf.Min( SystemInfo.supportedRenderTargetCount, 4 ); m_layerOffsetNames = new string[ m_mrtCount ]; m_layerRandomNames = new string[ m_mrtCount ]; for ( int i = 0; i < m_mrtCount; i++ ) { m_layerOffsetNames[ i ] = "_AO_LayerOffset" + i; m_layerRandomNames[ i ] = "_AO_LayerRandom" + i; } m_layerDepthNames = new string[ 16 ]; m_layerNormalNames = new string[ 16 ]; m_layerOcclusionNames = new string[ 16 ]; for ( int i = 0; i < 16; i++ ) { m_layerDepthNames[ i ] = "_AO_DepthLayer" + i; m_layerNormalNames[ i ] = "_AO_NormalLayer" + i; m_layerOcclusionNames[ i ] = "_AO_OcclusionLayer" + i; } m_depthTargets = new RenderTargetIdentifier[ m_mrtCount ]; m_normalTargets = new RenderTargetIdentifier[ m_mrtCount ]; switch ( m_mrtCount ) { case 4: m_deinterleaveDepthPass = ShaderPass.DeinterleaveDepth4; m_deinterleaveNormalPass = ShaderPass.DeinterleaveNormal4_None; break; default: m_deinterleaveDepthPass = ShaderPass.DeinterleaveDepth1; m_deinterleaveNormalPass = ShaderPass.DeinterleaveNormal1_None; break; } m_applyDeferredTargets = new RenderTargetIdentifier[ 2 ]; if ( m_blitMesh != null ) DestroyImmediate( m_blitMesh ); m_blitMesh = new Mesh(); m_blitMesh.vertices = new Vector3[ 4 ] { new Vector3( 0, 0, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 1, 1, 0 ), new Vector3( 1, 0, 0 ) }; m_blitMesh.uv = new Vector2[ 4 ] { new Vector2( 0, 0 ), new Vector2( 0, 1 ), new Vector2( 1, 1 ), new Vector2( 1, 0 ) }; m_blitMesh.triangles = new int[ 6 ] { 0, 1, 2, 0, 2, 3 }; } void Shutdown() { CommandBuffer_UnregisterAll(); SafeReleaseRT( ref m_occlusionRT ); if ( m_occlusionMat != null ) DestroyImmediate( m_occlusionMat ); if ( m_blurMat != null ) DestroyImmediate( m_blurMat ); if ( m_copyMat != null ) DestroyImmediate( m_copyMat ); if ( m_randomTex != null ) DestroyImmediate( m_randomTex ); if ( m_blitMesh != null ) DestroyImmediate( m_blitMesh ); } void OnEnable() { m_camera = GetComponent<Camera>(); Warmup(); CommandBuffer_UnregisterAll(); #if TRIAL watermark = new Texture2D( 4, 4 ) { hideFlags = HideFlags.HideAndDontSave }; watermark.LoadImage( AmplifyOcclusion.Watermark.ImageData ); #endif } void OnDisable() { Shutdown(); #if TRIAL if ( watermark != null ) { DestroyImmediate( watermark ); watermark = null; } #endif } void OnDestroy() { Shutdown(); } void Update() { if ( m_camera.actualRenderingPath != RenderingPath.DeferredShading ) { if ( PerPixelNormals != PerPixelNormalSource.None && PerPixelNormals != PerPixelNormalSource.Camera ) { // NOTE: use inspector warning box instead? PerPixelNormals = PerPixelNormalSource.Camera; UnityEngine.Debug.LogWarning( "[AmplifyOcclusion] GBuffer Normals only available in Camera Deferred Shading mode. Switched to Camera source." ); } if ( ApplyMethod == ApplicationMethod.Deferred ) { // NOTE: use inspector warning box instead? ApplyMethod = ApplicationMethod.PostEffect; UnityEngine.Debug.LogWarning( "[AmplifyOcclusion] Deferred Method requires a Deferred Shading path. Switching to Post Effect Method." ); } } if ( ApplyMethod == ApplicationMethod.Deferred && PerPixelNormals == PerPixelNormalSource.Camera ) { // NOTE: use inspector warning box instead? PerPixelNormals = PerPixelNormalSource.GBuffer; UnityEngine.Debug.LogWarning( "[AmplifyOcclusion] Camera Normals not supported for Deferred Method. Switching to GBuffer Normals." ); } if ( ( m_camera.depthTextureMode & DepthTextureMode.Depth ) == 0 ) m_camera.depthTextureMode |= DepthTextureMode.Depth; if ( ( PerPixelNormals == PerPixelNormalSource.Camera ) && ( m_camera.depthTextureMode & DepthTextureMode.DepthNormals ) == 0 ) m_camera.depthTextureMode |= DepthTextureMode.DepthNormals; CheckMaterial(); CheckRandomData(); } void CheckMaterial() { if ( m_occlusionMat == null ) m_occlusionMat = new Material( Shader.Find( "Hidden/Amplify Occlusion/Occlusion" ) ) { hideFlags = HideFlags.DontSave }; if ( m_blurMat == null ) m_blurMat = new Material( Shader.Find( "Hidden/Amplify Occlusion/Blur" ) ) { hideFlags = HideFlags.DontSave }; if ( m_copyMat == null ) m_copyMat = new Material( Shader.Find( "Hidden/Amplify Occlusion/Copy" ) ) { hideFlags = HideFlags.DontSave }; } void CheckRandomData() { if ( m_randomData == null ) m_randomData = GenerateRandomizationData(); if ( m_randomTex == null ) m_randomTex = GenerateRandomizationTexture( m_randomData ); } static public Color[] GenerateRandomizationData() { Color[] randomPixels = new Color[ RandomSize * RandomSize ]; for ( int i = 0, j = 0; i < RandomSize * RandomSize; i++ ) { float r1 = RandomTable.Values[ j++ ]; float r2 = RandomTable.Values[ j++ ]; float angle = 2.0f * Mathf.PI * r1 / DirectionCount; randomPixels[ i ].r = Mathf.Cos( angle ); randomPixels[ i ].g = Mathf.Sin( angle ); randomPixels[ i ].b = r2; randomPixels[ i ].a = 0; } return randomPixels; } static public Texture2D GenerateRandomizationTexture( Color[] randomPixels ) { Texture2D tex = new Texture2D( RandomSize, RandomSize, TextureFormat.ARGB32, false, true ) { hideFlags = HideFlags.DontSave }; tex.name = "RandomTexture"; tex.filterMode = FilterMode.Point; tex.wrapMode = TextureWrapMode.Repeat; tex.SetPixels( randomPixels ); tex.Apply(); return tex; } RenderTexture SafeAllocateRT( string name, int width, int height, RenderTextureFormat format, RenderTextureReadWrite readWrite ) { width = Mathf.Max( width, 1 ); height = Mathf.Max( height, 1 ); RenderTexture rt = new RenderTexture( width, height, 0, format, readWrite ) { hideFlags = HideFlags.DontSave }; rt.name = name; rt.filterMode = FilterMode.Point; rt.wrapMode = TextureWrapMode.Clamp; rt.Create(); return rt; } void SafeReleaseRT( ref RenderTexture rt ) { if ( rt != null ) { RenderTexture.active = null; rt.Release(); RenderTexture.DestroyImmediate( rt ); rt = null; } } int SafeAllocateTemporaryRT( CommandBuffer cb, string propertyName, int width, int height, RenderTextureFormat format = RenderTextureFormat.Default, RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default, FilterMode filterMode = FilterMode.Point ) { int id = Shader.PropertyToID( propertyName ); cb.GetTemporaryRT( id, width, height, 0, filterMode, format, readWrite ); return id; } void SafeReleaseTemporaryRT( CommandBuffer cb, int id ) {cb.ReleaseTemporaryRT( id ); } void SetBlitTarget( CommandBuffer cb, RenderTargetIdentifier[] targets, int targetWidth, int targetHeight ) { cb.SetGlobalVector( "_AO_Target_TexelSize", new Vector4( 1.0f / targetWidth, 1.0f / targetHeight, targetWidth, targetHeight ) ); cb.SetGlobalVector( "_AO_Target_Position", Vector2.zero ); cb.SetRenderTarget( targets, targets[ 0 ] ); } void SetBlitTarget( CommandBuffer cb, RenderTargetIdentifier target, int targetWidth, int targetHeight ) { cb.SetGlobalVector( "_AO_Target_TexelSize", new Vector4( 1.0f / targetWidth, 1.0f / targetHeight, targetWidth, targetHeight ) ); cb.SetRenderTarget( target ); } void PerformBlit( CommandBuffer cb, Material mat, int pass ) { cb.DrawMesh( m_blitMesh, Matrix4x4.identity, mat, 0, pass ); } void PerformBlit( CommandBuffer cb, Material mat, int pass, int x, int y ) { cb.SetGlobalVector( "_AO_Target_Position", new Vector2( x, y ) ); PerformBlit( cb, mat, pass ); } void PerformBlit( CommandBuffer cb, RenderTargetIdentifier source, int sourceWidth, int sourceHeight, Material mat, int pass ) { cb.SetGlobalTexture( "_AO_Source", source ); cb.SetGlobalVector( "_AO_Source_TexelSize", new Vector4( 1.0f / sourceWidth, 1.0f / sourceHeight, sourceWidth, sourceHeight ) ); PerformBlit( cb, mat, pass ); } void PerformBlit( CommandBuffer cb, RenderTargetIdentifier source, int sourceWidth, int sourceHeight, Material mat, int pass, int x, int y ) { cb.SetGlobalVector( "_AO_Target_Position", new Vector2( x, y ) ); PerformBlit( cb, source, sourceWidth, sourceHeight, mat, pass ); } CommandBuffer CommandBuffer_Allocate( string name ) { CommandBuffer cb = new CommandBuffer(); cb.name = name; return cb; } void CommandBuffer_Register( CameraEvent cameraEvent, CommandBuffer commandBuffer ) { m_camera.AddCommandBuffer( cameraEvent, commandBuffer ); m_registeredCommandBuffers.Add( cameraEvent, commandBuffer ); } void CommandBuffer_Unregister( CameraEvent cameraEvent, CommandBuffer commandBuffer ) { if ( m_camera != null ) { CommandBuffer[] cbs = m_camera.GetCommandBuffers( cameraEvent ); foreach ( CommandBuffer cb in cbs ) { if ( cb.name == commandBuffer.name ) m_camera.RemoveCommandBuffer( cameraEvent, cb ); } } } CommandBuffer CommandBuffer_AllocateRegister( CameraEvent cameraEvent ) { string name = ""; if ( cameraEvent == CameraEvent.BeforeReflections ) name = "AO-BeforeRefl"; else if ( cameraEvent == CameraEvent.AfterLighting ) name = "AO-AfterLighting"; else if ( cameraEvent == CameraEvent.BeforeImageEffectsOpaque ) name = "AO-BeforePostOpaque"; else Debug.LogError( "[AmplifyOcclusion] Unsupported CameraEvent. Please contact support." ); CommandBuffer cb = CommandBuffer_Allocate( name ); CommandBuffer_Register( cameraEvent, cb ); return cb; } void CommandBuffer_UnregisterAll() { foreach ( KeyValuePair<CameraEvent,CommandBuffer> pair in m_registeredCommandBuffers ) CommandBuffer_Unregister( pair.Key, pair.Value ); m_registeredCommandBuffers.Clear(); } void UpdateGlobalShaderConstants( TargetDesc target ) { float fovRad = m_camera.fieldOfView * Mathf.Deg2Rad; Vector2 focalLen = new Vector2( 1.0f / Mathf.Tan( fovRad * 0.5f ) * ( target.height / ( float ) target.width ), 1.0f / Mathf.Tan( fovRad * 0.5f ) ); Vector2 invFocalLen = new Vector2( 1.0f / focalLen.x, 1.0f / focalLen.y ); float projScale; if ( m_camera.orthographic ) projScale = ( ( float ) target.height ) / m_camera.orthographicSize; else projScale = ( ( float ) target.height ) / ( Mathf.Tan( fovRad * 0.5f ) * 2.0f ); float bias = Mathf.Clamp( Bias, 0.0f, 1.0f ); Shader.SetGlobalMatrix( "_AO_CameraProj", GL.GetGPUProjectionMatrix( Matrix4x4.Ortho( 0, 1, 0, 1, -1, 100 ), false ) ); Shader.SetGlobalMatrix( "_AO_CameraView", m_camera.worldToCameraMatrix ); Shader.SetGlobalVector( "_AO_UVToView", new Vector4( 2.0f * invFocalLen.x, -2.0f * invFocalLen.y, -1.0f * invFocalLen.x, 1.0f * invFocalLen.y ) ); Shader.SetGlobalFloat( "_AO_NegRcpR2", -1.0f / ( Radius * Radius ) ); Shader.SetGlobalFloat( "_AO_RadiusToScreen", Radius * 0.5f * projScale ); Shader.SetGlobalFloat( "_AO_PowExponent", PowerExponent ); Shader.SetGlobalFloat( "_AO_Bias", bias ); Shader.SetGlobalFloat( "_AO_Multiplier", 1.0f / ( 1.0f - bias ) ); Shader.SetGlobalFloat( "_AO_BlurSharpness", BlurSharpness ); Shader.SetGlobalColor( "_AO_Levels", new Color( Tint.r, Tint.g, Tint.b, Intensity ) ); } void CommandBuffer_FillComputeOcclusion( CommandBuffer cb, TargetDesc target ) { CheckMaterial(); CheckRandomData(); cb.SetGlobalVector( "_AO_Buffer_PadScale", new Vector4( target.padRatioWidth, target.padRatioHeight, 1.0f / target.padRatioWidth, 1.0f / target.padRatioHeight ) ); cb.SetGlobalVector( "_AO_Buffer_TexelSize", new Vector4( 1.0f / target.width, 1.0f / target.height, target.width, target.height ) ); cb.SetGlobalVector( "_AO_QuarterBuffer_TexelSize", new Vector4( 1.0f / target.quarterWidth, 1.0f / target.quarterHeight, target.quarterWidth, target.quarterHeight ) ); cb.SetGlobalFloat( "_AO_MaxRadiusPixels", Mathf.Min( target.width, target.height ) ); if ( m_occlusionRT == null || m_occlusionRT.width != target.width || m_occlusionRT.height != target.height || !m_occlusionRT.IsCreated() ) { SafeReleaseRT( ref m_occlusionRT ); m_occlusionRT = SafeAllocateRT( "_AO_OcclusionTexture", target.width, target.height, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear ); } int smallOcclusionRT = -1; if ( Downsample ) smallOcclusionRT = SafeAllocateTemporaryRT( cb, "_AO_SmallOcclusionTexture", target.width / 2, target.height / 2, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear, FilterMode.Bilinear ); // Ambient Occlusion if ( CacheAware && !Downsample ) { int occlusionAtlasRT = SafeAllocateTemporaryRT( cb, "_AO_OcclusionAtlas", target.width, target.height, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear ); for ( int i = 0; i < 16; i++ ) { m_depthLayerRT[ i ] = SafeAllocateTemporaryRT( cb, m_layerDepthNames[ i ], target.quarterWidth, target.quarterHeight, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear ); m_normalLayerRT[ i ] = SafeAllocateTemporaryRT( cb, m_layerNormalNames[ i ], target.quarterWidth, target.quarterHeight, RenderTextureFormat.ARGB2101010, RenderTextureReadWrite.Linear ); m_occlusionLayerRT[ i ] = SafeAllocateTemporaryRT( cb, m_layerOcclusionNames[ i ], target.quarterWidth, target.quarterHeight, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear ); } // Deinterleaved Normal + Depth for ( int scan = 0; scan < 16; scan += m_mrtCount ) { for ( int i = 0; i < m_mrtCount; i++ ) { int layer = i + scan; int x = layer & 3; int y = layer >> 2; cb.SetGlobalVector( m_layerOffsetNames[ i ], new Vector2( x + 0.5f, y + 0.5f ) ); m_depthTargets[ i ] = m_depthLayerRT[ layer ]; m_normalTargets[ i ] = m_normalLayerRT[ layer ]; } SetBlitTarget( cb, m_depthTargets, target.quarterWidth, target.quarterHeight ); PerformBlit( cb, m_occlusionMat, m_deinterleaveDepthPass ); SetBlitTarget( cb, m_normalTargets, target.quarterWidth, target.quarterHeight ); PerformBlit( cb, m_occlusionMat, m_deinterleaveNormalPass + ( int ) PerPixelNormals ); } // Deinterleaved Occlusion for ( int i = 0; i < 16; i++ ) { cb.SetGlobalVector( "_AO_LayerOffset", new Vector2( ( i & 3 ) + 0.5f, ( i >> 2 ) + 0.5f ) ); cb.SetGlobalVector( "_AO_LayerRandom", m_randomData[ i ] ); cb.SetGlobalTexture( "_AO_NormalTexture", m_normalLayerRT[ i ] ); cb.SetGlobalTexture( "_AO_DepthTexture", m_depthLayerRT[ i ] ); SetBlitTarget( cb, m_occlusionLayerRT[ i ], target.quarterWidth, target.quarterHeight ); PerformBlit( cb, m_occlusionMat, ShaderPass.OcclusionCache_Low + ( int ) SampleCount ); } // Reinterleave SetBlitTarget( cb, occlusionAtlasRT, target.width, target.height ); for ( int i = 0; i < 16; i++ ) { int dst_x = ( i & 3 ) * target.quarterWidth; int dst_y = ( i >> 2 ) * target.quarterHeight; PerformBlit( cb, m_occlusionLayerRT[ i ], target.quarterWidth, target.quarterHeight, m_copyMat, ShaderPass.Copy, dst_x, dst_y ); } cb.SetGlobalTexture( "_AO_OcclusionAtlas", occlusionAtlasRT ); SetBlitTarget( cb, m_occlusionRT, target.width, target.height ); PerformBlit( cb, m_occlusionMat, ShaderPass.Reinterleave ); for ( int i = 0; i < 16; i++ ) { SafeReleaseTemporaryRT( cb, m_occlusionLayerRT[ i ] ); SafeReleaseTemporaryRT( cb, m_normalLayerRT[ i ] ); SafeReleaseTemporaryRT( cb, m_depthLayerRT[ i ] ); } SafeReleaseTemporaryRT( cb, occlusionAtlasRT ); } else { m_occlusionMat.SetTexture( "_AO_RandomTexture", m_randomTex ); int occlusionPass = ( ShaderPass.OcclusionLow_None + ( ( int ) SampleCount ) * PerPixelNormalSourceCount + ( ( int ) PerPixelNormals ) ); if ( Downsample ) { cb.Blit( (Texture) null, new RenderTargetIdentifier( smallOcclusionRT ), m_occlusionMat, occlusionPass ); SetBlitTarget( cb, m_occlusionRT, target.width, target.height ); PerformBlit( cb, smallOcclusionRT, target.width / 2, target.height / 2, m_occlusionMat, ShaderPass.CombineDownsampledOcclusionDepth ); } else { cb.Blit( (Texture) null, m_occlusionRT, m_occlusionMat, occlusionPass ); } } if ( BlurEnabled ) { int tempRT = SafeAllocateTemporaryRT( cb, "_AO_TEMP", target.width, target.height, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear ); // Apply Cross Bilateral Blur for ( int i = 0; i < BlurPasses; i++ ) { SetBlitTarget( cb, tempRT, target.width, target.height ); PerformBlit( cb, m_occlusionRT, target.width, target.height, m_blurMat, ShaderPass.BlurHorizontal1 + ( BlurRadius - 1 ) * 2 ); SetBlitTarget( cb, m_occlusionRT, target.width, target.height ); PerformBlit( cb, tempRT, target.width, target.height, m_blurMat, ShaderPass.BlurVertical1 + ( BlurRadius - 1 ) * 2 ); } SafeReleaseTemporaryRT( cb, tempRT ); } if ( Downsample && smallOcclusionRT >= 0 ) SafeReleaseTemporaryRT( cb, smallOcclusionRT ); cb.SetRenderTarget( default( RenderTexture ) ); } void CommandBuffer_FillApplyDeferred( CommandBuffer cb, TargetDesc target, bool logTarget ) { cb.SetGlobalTexture( "_AO_OcclusionTexture", m_occlusionRT ); m_applyDeferredTargets[ 0 ] = BuiltinRenderTextureType.GBuffer0; m_applyDeferredTargets[ 1 ] = logTarget ? BuiltinRenderTextureType.GBuffer3 : BuiltinRenderTextureType.CameraTarget; if ( !logTarget ) { SetBlitTarget( cb, m_applyDeferredTargets, target.fullWidth, target.fullHeight ); PerformBlit( cb, m_occlusionMat, ShaderPass.ApplyDeferred ); } else { int gbufferAlbedoRT = SafeAllocateTemporaryRT( cb, "_AO_GBufferAlbedo", target.fullWidth, target.fullHeight, RenderTextureFormat.ARGB32 ); int gbufferEmissionRT = SafeAllocateTemporaryRT( cb, "_AO_GBufferEmission", target.fullWidth, target.fullHeight, RenderTextureFormat.ARGB32 ); cb.Blit( m_applyDeferredTargets[ 0 ], gbufferAlbedoRT ); cb.Blit( m_applyDeferredTargets[ 1 ], gbufferEmissionRT ); cb.SetGlobalTexture( "_AO_GBufferAlbedo", gbufferAlbedoRT ); cb.SetGlobalTexture( "_AO_GBufferEmission", gbufferEmissionRT ); SetBlitTarget( cb, m_applyDeferredTargets, target.fullWidth, target.fullHeight ); PerformBlit( cb, m_occlusionMat, ShaderPass.ApplyDeferredLog ); SafeReleaseTemporaryRT( cb, gbufferAlbedoRT ); SafeReleaseTemporaryRT( cb, gbufferEmissionRT ); } cb.SetRenderTarget( default( RenderTexture ) ); } void CommandBuffer_FillApplyPostEffect( CommandBuffer cb, TargetDesc target, bool logTarget ) { cb.SetGlobalTexture( "_AO_OcclusionTexture", m_occlusionRT ); if ( !logTarget ) { SetBlitTarget( cb, BuiltinRenderTextureType.CameraTarget, target.fullWidth, target.fullHeight ); PerformBlit( cb, m_occlusionMat, ShaderPass.ApplyPostEffect ); } else { int gbufferEmissionRT = SafeAllocateTemporaryRT( cb, "_AO_GBufferEmission", target.fullWidth, target.fullHeight, RenderTextureFormat.ARGB32 ); cb.Blit( BuiltinRenderTextureType.GBuffer3, gbufferEmissionRT ); cb.SetGlobalTexture( "_AO_GBufferEmission", gbufferEmissionRT ); SetBlitTarget( cb, BuiltinRenderTextureType.GBuffer3, target.fullWidth, target.fullHeight ); PerformBlit( cb, m_occlusionMat, ShaderPass.ApplyPostEffectLog ); SafeReleaseTemporaryRT( cb, gbufferEmissionRT ); } cb.SetRenderTarget( default( RenderTexture ) ); } void CommandBuffer_FillApplyDebug( CommandBuffer cb, TargetDesc target ) { cb.SetGlobalTexture( "_AO_OcclusionTexture", m_occlusionRT ); SetBlitTarget( cb, BuiltinRenderTextureType.CameraTarget, target.fullWidth, target.fullHeight ); PerformBlit( cb, m_occlusionMat, ShaderPass.ApplyDebug ); cb.SetRenderTarget( default( RenderTexture ) ); } void CommandBuffer_Rebuild( TargetDesc target ) { bool gbufferSource = ( PerPixelNormals == PerPixelNormalSource.GBuffer || PerPixelNormals == PerPixelNormalSource.GBufferOctaEncoded ); CommandBuffer cb = null; CameraEvent stage = gbufferSource ? CameraEvent.AfterLighting : CameraEvent.BeforeImageEffectsOpaque; if ( ApplyMethod == ApplicationMethod.Debug ) { cb = CommandBuffer_AllocateRegister( stage ); CommandBuffer_FillComputeOcclusion( cb, target ); CommandBuffer_FillApplyDebug( cb, target ); } else { bool logTarget = ( !m_camera.hdr && gbufferSource ); stage = ( ApplyMethod == ApplicationMethod.Deferred ) ? CameraEvent.BeforeReflections : stage; cb = CommandBuffer_AllocateRegister( stage ); CommandBuffer_FillComputeOcclusion( cb, target ); if ( ApplyMethod == ApplicationMethod.PostEffect ) CommandBuffer_FillApplyPostEffect( cb, target, logTarget ); else if ( ApplyMethod == ApplicationMethod.Deferred ) CommandBuffer_FillApplyDeferred( cb, target, logTarget ); } } void OnPreRender() { m_target.fullWidth = m_camera.pixelWidth; m_target.fullHeight = m_camera.pixelHeight; m_target.format = m_camera.hdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32; m_target.width = CacheAware ? ( m_target.fullWidth + 3 ) & ~3 : m_target.fullWidth; m_target.height = CacheAware ? ( m_target.fullHeight + 3 ) & ~3 : m_target.fullHeight; m_target.quarterWidth = m_target.width / 4; m_target.quarterHeight = m_target.height / 4; m_target.padRatioWidth = m_target.width / ( float ) m_target.fullWidth; m_target.padRatioHeight = m_target.height / ( float ) m_target.fullHeight; UpdateGlobalShaderConstants( m_target ); if ( CheckParamsChanged() || m_registeredCommandBuffers.Count == 0 ) { CommandBuffer_UnregisterAll(); CommandBuffer_Rebuild( m_target ); UpdateParams(); } } #if TRIAL void OnGUI() { if ( watermark != null ) GUI.DrawTexture( new Rect( Screen.width - watermark.width - 15, Screen.height - watermark.height - 12, watermark.width, watermark.height ), watermark ); } #endif } public class RandomTable { public static float[] Values = new float[] { 0.4639f, 0.3400f, 0.2230f, 0.4684f, 0.3222f, 0.9792f, 0.0317f, 0.9733f, 0.7783f, 0.4561f, 0.2585f, 0.3300f, 0.3873f, 0.3801f, 0.1798f, 0.9107f, 0.5116f, 0.0929f, 0.1807f, 0.6201f, 0.1013f, 0.5563f, 0.6424f, 0.4420f, 0.2151f, 0.4752f, 0.1573f, 0.5688f, 0.5012f, 0.6292f, 0.6992f, 0.7077f, 0.5567f, 0.0055f, 0.7083f, 0.5831f, 0.2366f, 0.9923f, 0.9810f, 0.1198f, 0.5108f, 0.5604f, 0.9614f, 0.5578f, 0.5399f, 0.3328f, 0.4178f, 0.9207f, 0.7307f, 0.0766f, 0.0085f, 0.6601f, 0.4289f, 0.5113f, 0.5878f, 0.9064f, 0.4379f, 0.6203f, 0.0621f, 0.1194f, 0.2356f, 0.7958f, 0.0444f, 0.6173f, 0.8911f, 0.2631f, 0.2452f, 0.2765f, 0.7869f, 0.0597f, 0.4243f, 0.4333f, 0.0521f, 0.6999f, 0.1394f, 0.4028f, 0.7419f, 0.5579f, 0.1270f, 0.9463f, 0.2055f, 0.0928f, 0.4229f, 0.7151f, 0.7119f, 0.9260f, 0.3686f, 0.2865f, 0.2414f, 0.8316f, 0.2322f, 0.4786f, 0.3669f, 0.4320f, 0.2684f, 0.6191f, 0.3917f, 0.0566f, 0.0677f, 0.5090f, 0.9208f, 0.2983f, 0.7010f, 0.0443f, 0.9367f, 0.4859f, 0.2712f, 0.1087f, 0.3258f, 0.6823f, 0.9550f, 0.6581f, 0.2958f, 0.5625f, 0.8671f, 0.8105f, 0.4879f, 0.8695f, 0.2247f, 0.9626f, 0.6465f, 0.0037f, 0.2288f, 0.2636f, 0.3651f, 0.9583f, 0.6066f, 0.9018f, 0.7572f, 0.3060f, 0.6331f, 0.4076f, 0.4436f, 0.9799f, 0.9229f, 0.9464f, 0.5940f, 0.6043f, 0.8642f, 0.1875f, 0.8771f, 0.7920f, 0.9548f, 0.9767f, 0.3505f, 0.8347f, 0.9451f, 0.1558f, 0.4118f, 0.5523f, 0.8554f, 0.7413f, 0.7612f, 0.8962f, 0.7820f, 0.2662f, 0.1288f, 0.6457f, 0.5915f, 0.2473f, 0.2608f, 0.8119f, 0.6533f, 0.9767f, 0.2215f, 0.9574f, 0.2940f, 0.1590f, 0.8205f, 0.5696f, 0.9343f, 0.4671f, 0.7631f, 0.8357f, 0.2400f, 0.3898f, 0.9987f, 0.7837f, 0.7580f, 0.6143f, 0.2211f, 0.5024f, 0.9780f, 0.2477f, 0.6195f, 0.6583f, 0.7696f, 0.7684f, 0.3371f, 0.3706f, 0.0847f, 0.5105f, 0.5949f, 0.9946f, 0.1812f, 0.8681f, 0.3120f, 0.4804f, 0.1773f, 0.3673f, 0.7416f, 0.2029f, 0.2294f, 0.1081f, 0.0986f, 0.0104f, 0.7273f, 0.9422f, 0.0238f, 0.1106f, 0.9582f, 0.2089f, 0.5846f, 0.4918f, 0.2382f, 0.5915f, 0.2974f, 0.6814f, 0.2150f, 0.5877f, 0.7044f, 0.9789f, 0.9116f, 0.6926f, 0.4629f, 0.2732f, 0.8028f, 0.6516f, 0.7367f, 0.9862f, 0.4023f, 0.5240f, 0.7404f, 0.7990f, 0.9182f, 0.7053f, 0.4774f, 0.1022f, 0.8099f, 0.8606f, 0.1182f, 0.0095f, 0.2801f, 0.9484f, 0.0254f, 0.4581f, 0.5126f, 0.0820f, 0.5369f, 0.4725f, 0.8357f, 0.0785f, 0.3579f, 0.7975f, 0.5705f, 0.1627f, 0.8159f, 0.8741f, 0.9153f, 0.3920f, 0.3663f, 0.7662f, 0.4627f, 0.0876f, 0.4023f, 0.2776f, 0.2941f, 0.3927f, 0.5048f, 0.2634f, 0.5091f, 0.5189f, 0.7388f, 0.9658f, 0.0038f, 0.9768f, 0.2922f, 0.8371f, 0.5254f, 0.7437f, 0.3590f, 0.0606f, 0.5954f, 0.4831f, 0.9001f, 0.4232f, 0.9819f, 0.1549f, 0.0855f, 0.6815f, 0.8144f, 0.1059f, 0.9722f, 0.2070f, 0.9946f, 0.9892f, 0.6462f, 0.3302f, 0.4320f, 0.1399f, 0.9086f, 0.2715f, 0.5393f, 0.8451f, 0.1400f, 0.0014f, 0.3401f, 0.5822f, 0.6935f, 0.2931f, 0.7334f, 0.3755f, 0.6760f, 0.1306f, 0.6065f, 0.4410f, 0.1135f, 0.8444f, 0.3999f, 0.5510f, 0.4827f, 0.8948f, 0.1889f, 0.4310f, 0.0436f, 0.3946f, 0.5443f, 0.7987f, 0.0404f, 0.0222f, 0.6812f, 0.5983f, 0.0699f, 0.2556f, 0.1747f, 0.8808f, 0.4120f, 0.3979f, 0.9328f, 0.9794f, 0.2442f, 0.4880f, 0.3137f, 0.8581f, 0.3909f, 0.4261f, 0.7548f, 0.3607f, 0.8628f, 0.5264f, 0.0900f, 0.6739f, 0.7150f, 0.2374f, 0.2102f, 0.9528f, 0.4484f, 0.7380f, 0.0773f, 0.2606f, 0.5904f, 0.1275f, 0.6289f, 0.1362f, 0.8601f, 0.5967f, 0.5240f, 0.8971f, 0.6488f, 0.1167f, 0.6668f, 0.5369f, 0.8117f, 0.8549f, 0.8572f, 0.9450f, 0.4341f, 0.6023f, 0.8237f, 0.1094f, 0.6846f, 0.1955f, 0.2136f, 0.2835f, 0.3870f, 0.1820f, 0.8346f, 0.9489f, 0.3731f, 0.2497f, 0.1625f, 0.5878f, 0.1926f, 0.7378f, 0.7774f, 0.6514f, 0.5625f, 0.9183f, 0.0948f, 0.2606f, 0.6294f, 0.7513f, 0.3622f, 0.6496f, 0.3973f, 0.6706f, 0.2156f, 0.9254f, 0.9083f, 0.4868f, 0.1410f, 0.2361f, 0.9263f, 0.4160f, 0.7814f, 0.5385f, 0.1195f, 0.0041f, 0.8475f, 0.8767f, 0.9455f, 0.9350f, 0.4220f, 0.5028f, 0.9325f, 0.1166f, 0.7008f, 0.9955f, 0.3349f, 0.1746f, 0.9828f, 0.1741f, 0.7342f, 0.7693f, 0.9175f, 0.3826f, 0.7958f, 0.0518f, 0.5281f, 0.6919f, 0.3379f, 0.6756f, 0.9694f, 0.3549f, 0.0545f, 0.2542f, 0.9788f, 0.6112f, 0.8900f, 0.7126f, 0.2196f, 0.8264f, 0.3511f, 0.0873f, 0.8625f, 0.8054f, 0.4993f, 0.4821f, 0.0364f, 0.8156f, 0.0165f, 0.8759f, 0.3083f, 0.6500f, 0.4941f, 0.6159f, 0.3967f, 0.9216f, 0.1646f, 0.4727f, 0.5598f, 0.6756f, 0.0598f, 0.2957f, 0.8180f, 0.7693f, 0.1586f, 0.6481f, 0.2287f, 0.6274f, 0.1385f, 0.6394f, 0.2003f, 0.3523f, 0.4707f, 0.8886f, 0.3117f, 0.5711f, 0.9793f, 0.4572f, 0.1151f, 0.7256f, 0.6205f, 0.6293f, 0.8502f, 0.9499f, 0.2546f, 0.1423f, 0.6888f, 0.3072f, 0.2848f, 0.8476f, 0.6170f, 0.2074f, 0.5505f, 0.5418f, 0.1738f, 0.4748f, 0.6783f, 0.2891f, 0.5281f, 0.3065f, 0.8693f, 0.0402f, 0.4173f, 0.4725f, 0.8576f, 0.9174f, 0.8423f, 0.9868f, 0.6045f, 0.7311f, 0.6078f, 0.9046f, 0.3979f, 0.6278f, 0.5333f, 0.6567f, 0.6272f, 0.2235f, 0.2684f, 0.2548f, 0.8343f, 0.1310f, 0.8380f, 0.6135f, 0.8216f, 0.8597f, 0.4052f, 0.9099f, 0.0361f, 0.6430f, 0.1870f, 0.9457f, 0.3190f, 0.7090f, 0.8522f, 0.5595f, 0.8657f, 0.3688f, 0.8404f, 0.9505f, 0.3151f, 0.3317f, 0.5092f, 0.4686f, 0.1190f, 0.5418f, 0.9834f, 0.1155f, 0.2998f, 0.8403f, 0.4452f, 0.9007f, 0.6336f, 0.3041f, 0.9961f, 0.8440f, 0.4623f, 0.3144f, 0.8500f, 0.7736f, 0.9583f, 0.7653f, 0.5675f, 0.7226f, 0.0012f, 0.1896f, 0.3646f, 0.1923f, 0.8368f, 0.7836f, 0.0267f, 0.0652f, 0.5887f, 0.9377f, 0.9936f, 0.5974f, 0.8519f, 0.6703f, 0.3609f, 0.7556f, 0.5715f, 0.2319f, 0.4250f, 0.1164f, 0.3218f, 0.6296f, 0.7012f, 0.7169f, 0.1463f, 0.3605f, 0.4984f, 0.8460f, 0.3079f, 0.3234f, 0.2888f, 0.4779f, 0.2364f, 0.8765f, 0.6674f, 0.9771f, 0.1793f, 0.4794f, 0.6332f, 0.9576f, 0.3436f, 0.8718f, 0.4528f, 0.8954f, 0.3276f, 0.8677f, 0.5968f, 0.9070f, 0.4174f, 0.5307f, 0.5474f, 0.1410f, 0.7210f, 0.5876f, 0.8300f, 0.4608f, 0.5638f, 0.6737f, 0.0358f, 0.7558f, 0.3318f, 0.6534f, 0.9263f, 0.7245f, 0.9785f, 0.4952f, 0.0981f, 0.9367f, 0.1399f, 0.8513f, 0.8898f, 0.3765f, 0.6614f, 0.1564f, 0.6718f, 0.4878f, 0.0465f, 0.4419f, 0.0140f, 0.4404f, 0.2359f, 0.1637f, 0.0753f, 0.2547f, 0.2140f, 0.5548f, 0.7128f, 0.7957f, 0.4716f, 0.1050f, 0.3559f, 0.8344f, 0.4980f, 0.0183f, 0.3647f, 0.9188f, 0.9092f, 0.8585f, 0.9282f, 0.9463f, 0.7553f, 0.4087f, 0.1378f, 0.2478f, 0.3006f, 0.4700f, 0.2487f, 0.5216f, 0.0098f, 0.8915f, 0.9089f, 0.2275f, 0.7029f, 0.5967f, 0.5815f, 0.0999f, 0.8048f, 0.9474f, 0.0806f, 0.3757f, 0.8904f, 0.6891f, 0.6009f, 0.3822f, 0.8140f, 0.2583f, 0.2780f, 0.9073f, 0.6250f, 0.0166f, 0.5028f, 0.7430f, 0.2478f, 0.8462f, 0.6478f, 0.3798f, 0.5173f, 0.9214f, 0.9048f, 0.8056f, 0.6719f, 0.4872f, 0.6780f, 0.5756f, 0.9107f, 0.9476f, 0.5247f, 0.2312f, 0.2990f, 0.0681f, 0.5696f, 0.1210f, 0.7016f, 0.3119f, 0.4473f, 0.0140f, 0.0133f, 0.2578f, 0.4818f, 0.8088f, 0.6282f, 0.7802f, 0.2027f, 0.0249f, 0.7743f, 0.7830f, 0.3300f, 0.7888f, 0.3468f, 0.7787f, 0.2619f, 0.6966f, 0.2128f, 0.7138f, 0.8718f, 0.6397f, 0.7110f, 0.6512f, 0.0423f, 0.2369f, 0.7462f, 0.2350f, 0.4427f, 0.1954f, 0.1759f, 0.9879f, 0.0312f, 0.9754f, 0.2770f, 0.7526f, 0.6397f, 0.5078f, 0.8735f, 0.7753f, 0.3900f, 0.4159f, 0.2878f, 0.1893f, 0.8379f, 0.1862f, 0.3556f, 0.8037f, 0.0291f, 0.8020f, 0.2480f, 0.3540f, 0.4205f, 0.1095f, 0.7312f, 0.7006f, 0.7160f, 0.6515f, 0.2500f, 0.8842f, 0.3642f, 0.2449f, 0.4722f, 0.0806f, 0.3093f, 0.2506f, 0.5190f, 0.0661f, 0.0378f, 0.8657f, 0.7677f, 0.6173f, 0.5370f, 0.7439f, 0.4012f, 0.5954f, 0.8698f, 0.1939f, 0.6703f, 0.0184f, 0.7431f, 0.9795f, 0.3823f, 0.1910f, 0.9922f, 0.9461f, 0.3064f, 0.7937f, 0.6873f, 0.5562f, 0.9583f, 0.3909f, 0.3578f, 0.1102f, 0.9775f, 0.8314f, 0.4858f, 0.1486f, 0.8473f, 0.7331f, 0.3973f, 0.3763f, 0.3987f, 0.4638f, 0.9769f, 0.8447f, 0.0756f, 0.4738f, 0.4709f, 0.5481f, 0.3501f, 0.7274f, 0.1231f, 0.3477f, 0.8395f, 0.5627f, 0.0368f, 0.5647f, 0.9603f, 0.2205f, 0.9069f, 0.6776f, 0.8410f, 0.1115f, 0.0323f, 0.0277f, 0.4682f, 0.2291f, 0.5087f, 0.1996f, 0.2981f, 0.6772f, 0.5260f, 0.8282f, 0.4133f, 0.3051f, 0.2233f, 0.7780f, 0.1980f, 0.4149f, 0.0074f, 0.4642f, 0.7852f, 0.5344f, 0.0605f, 0.5724f, 0.6933f, 0.8658f, 0.0349f, 0.5868f, 0.1617f, 0.2037f, 0.6565f, 0.6043f, 0.6883f, 0.2572f, 0.2464f, 0.3382f, 0.8399f, 0.2684f, 0.9132f, 0.7595f, 0.2892f, 0.3472f, 0.5089f, 0.3615f, 0.5546f, 0.0864f, 0.0243f, 0.6616f, 0.9888f, 0.1106f, 0.1294f, 0.4059f, 0.7817f, 0.3039f, 0.5218f, 0.2362f, 0.2779f, 0.6992f, 0.7338f, 0.7720f, 0.6584f, 0.0563f, 0.1530f, 0.5368f, 0.7922f, 0.1652f, 0.5922f, 0.2283f, 0.1470f, 0.1160f, 0.3192f, 0.2934f, 0.8726f, 0.8422f, 0.3062f, 0.2287f, 0.7457f, 0.8213f, 0.7782f, 0.6113f, 0.9691f, 0.2976f, 0.3673f, 0.8150f, 0.9858f, 0.6932f, 0.4117f, 0.3666f, 0.3454f, 0.6090f, 0.7789f, 0.6408f, 0.3409f, 0.3284f, 0.8986f, 0.9523f, 0.2725f, 0.7589f, 0.1112f, 0.6134f, 0.8643f, 0.6076f, 0.3573f, 0.2276f, 0.1770f, 0.7738f, 0.3182f, 0.2983f, 0.6793f, 0.4546f, 0.9767f, 0.2445f, 0.8801f, 0.0462f, 0.4513f, 0.7092f, 0.7841f, 0.4883f, 0.2287f, 0.0412f, 0.0774f, 0.7188f, 0.4542f, 0.0391f, 0.6147f, 0.5386f, 0.8566f, 0.8889f, 0.1840f, 0.4879f, 0.8803f, 0.7268f, 0.1129f, 0.8357f, 0.9433f, 0.3400f, 0.1679f, 0.2412f, 0.1259f, 0.4601f, 0.7899f, 0.3138f, 0.6407f, 0.7959f, 0.1980f, 0.4073f, 0.6738f, 0.4143f, 0.1859f, 0.3534f, 0.7867f, 0.4221f, 0.1339f, 0.3632f, 0.3938f, 0.7487f, 0.3281f, 0.1156f, 0.2538f, 0.5269f, 0.6727f, 0.5174f, 0.6864f, 0.5328f, 0.5511f, 0.6674f, 0.3826f, 0.4087f, 0.6494f, 0.6139f, 0.6004f, 0.4854f, }; }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.Compression; using System.Reflection; using System.Net; using System.Text; using System.Web; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nini.Config; using log4net; namespace OpenSim.Server.Handlers.Simulation { public class AgentHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; public AgentHandler() { } public AgentHandler(ISimulationService sim) { m_SimulationService = sim; } public Hashtable Handler(Hashtable request) { // m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); // // m_log.Debug("---------------------------"); // m_log.Debug(" >> uri=" + request["uri"]); // m_log.Debug(" >> content-type=" + request["content-type"]); // m_log.Debug(" >> http-method=" + request["http-method"]); // m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; responsedata["keepalive"] = false; UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]); responsedata["int_response_code"] = 404; responsedata["str_response_string"] = "false"; return responsedata; } // Next, let's parse the verb string method = (string)request["http-method"]; if (method.Equals("DELETE")) { string auth_token = string.Empty; if (request.ContainsKey("auth")) auth_token = request["auth"].ToString(); DoAgentDelete(request, responsedata, agentID, action, regionID, auth_token); return responsedata; } else if (method.Equals("QUERYACCESS")) { DoQueryAccess(request, responsedata, agentID, regionID); return responsedata; } else { m_log.ErrorFormat("[AGENT HANDLER]: method {0} not supported in agent message {1} (caller is {2})", method, (string)request["uri"], Util.GetCallerIP(request)); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; return responsedata; } } protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID) { Culture.SetCurrentCulture(); EntityTransferContext ctx = new EntityTransferContext(); if (m_SimulationService == null) { m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless."); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.NotImplemented; responsedata["str_response_string"] = string.Empty; return; } // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]); OSDMap args = Utils.GetOSDMap((string)request["body"]); bool viaTeleport = true; if (args.ContainsKey("viaTeleport")) viaTeleport = args["viaTeleport"].AsBoolean(); Vector3 position = Vector3.Zero; if (args.ContainsKey("position")) position = Vector3.Parse(args["position"].AsString()); string agentHomeURI = null; if (args.ContainsKey("agent_home_uri")) agentHomeURI = args["agent_home_uri"].AsString(); // Decode the legacy (string) version and extract the number float theirVersion = 0f; if (args.ContainsKey("my_version")) { string theirVersionStr = args["my_version"].AsString(); string[] parts = theirVersionStr.Split(new char[] {'/'}); if (parts.Length > 1) theirVersion = float.Parse(parts[1], Culture.FormatProvider); } if (args.ContainsKey("context")) ctx.Unpack((OSDMap)args["context"]); // Decode the new versioning data float minVersionRequired = 0f; float maxVersionRequired = 0f; float minVersionProvided = 0f; float maxVersionProvided = 0f; if (args.ContainsKey("simulation_service_supported_min")) minVersionProvided = (float)args["simulation_service_supported_min"].AsReal(); if (args.ContainsKey("simulation_service_supported_max")) maxVersionProvided = (float)args["simulation_service_supported_max"].AsReal(); if (args.ContainsKey("simulation_service_accepted_min")) minVersionRequired = (float)args["simulation_service_accepted_min"].AsReal(); if (args.ContainsKey("simulation_service_accepted_max")) maxVersionRequired = (float)args["simulation_service_accepted_max"].AsReal(); responsedata["int_response_code"] = HttpStatusCode.OK; OSDMap resp = new OSDMap(3); float version = 0f; float outboundVersion = 0f; float inboundVersion = 0f; if (minVersionProvided == 0f) // string version or older { // If there is no version in the packet at all we're looking at 0.6 or // even more ancient. Refuse it. if(theirVersion == 0f) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString("Your region is running a old version of opensim no longer supported. Consider updating it"); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } version = theirVersion; if (version < VersionInfo.SimulationServiceVersionAcceptedMin || version > VersionInfo.SimulationServiceVersionAcceptedMax ) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString(String.Format("Your region protocol version is {0} and we accept only {1} - {2}. No version overlap.", theirVersion, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax)); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } } else { // Test for no overlap if (minVersionProvided > VersionInfo.SimulationServiceVersionAcceptedMax || maxVersionProvided < VersionInfo.SimulationServiceVersionAcceptedMin) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString(String.Format("Your region provide protocol versions {0} - {1} and we accept only {2} - {3}. No version overlap.", minVersionProvided, maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax)); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } if (minVersionRequired > VersionInfo.SimulationServiceVersionSupportedMax || maxVersionRequired < VersionInfo.SimulationServiceVersionSupportedMin) { resp["success"] = OSD.FromBoolean(false); resp["reason"] = OSD.FromString(String.Format("You require region protocol versions {0} - {1} and we provide only {2} - {3}. No version overlap.", minVersionRequired, maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax)); responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); return; } // Determine versions to use // This is intentionally inverted. Inbound and Outbound refer to the direction of the transfer. // Therefore outbound means from the sender to the receier and inbound means from the receiver to the sender. // So outbound is what we will accept and inbound is what we will send. Confused yet? outboundVersion = Math.Min(maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMax); inboundVersion = Math.Min(maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMax); } List<UUID> features = new List<UUID>(); if (args.ContainsKey("features")) { OSDArray array = (OSDArray)args["features"]; foreach (OSD o in array) features.Add(new UUID(o.AsString())); } GridRegion destination = new GridRegion(); destination.RegionID = regionID; string reason; // We're sending the version numbers down to the local connector to do the varregion check. ctx.InboundVersion = inboundVersion; ctx.OutboundVersion = outboundVersion; if (minVersionProvided == 0f) { ctx.InboundVersion = version; ctx.OutboundVersion = version; } bool result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason); m_log.DebugFormat("[AGENT HANDLER]: QueryAccess returned {0} ({1}). Version={2}, {3}/{4}", result, reason, version, inboundVersion, outboundVersion); resp["success"] = OSD.FromBoolean(result); resp["reason"] = OSD.FromString(reason); string legacyVersion = String.Format(Culture.FormatProvider,"SIMULATION/{0}", version); resp["version"] = OSD.FromString(legacyVersion); resp["negotiated_inbound_version"] = OSD.FromReal(inboundVersion); resp["negotiated_outbound_version"] = OSD.FromReal(outboundVersion); OSDArray featuresWanted = new OSDArray(); foreach (UUID feature in features) featuresWanted.Add(OSD.FromString(feature.ToString())); resp["features"] = featuresWanted; // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map! responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); // Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]); } protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID, string auth_token) { if (string.IsNullOrEmpty(action)) m_log.DebugFormat("[AGENT HANDLER]: >>> DELETE <<< RegionID: {0}; from: {1}; auth_code: {2}", regionID, Util.GetCallerIP(request), auth_token); else m_log.DebugFormat("[AGENT HANDLER]: Release {0} to RegionID: {1}", id, regionID); GridRegion destination = new GridRegion(); destination.RegionID = regionID; if (action.Equals("release")) ReleaseAgent(regionID, id); else Util.FireAndForget( o => m_SimulationService.CloseAgent(destination, id, auth_token), null, "AgentHandler.DoAgentDelete"); responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = "OpenSim agent " + id.ToString(); //m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID); } protected virtual void ReleaseAgent(UUID regionID, UUID id) { m_SimulationService.ReleaseAgent(regionID, id, ""); } } public class AgentPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPostHandler(ISimulationService service) : base("POST", "/agent") { m_SimulationService = service; } public AgentPostHandler(string path) : base("POST", path) { m_SimulationService = null; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Encoding encoding = Encoding.UTF8; if (httpRequest.ContentType != "application/json") { httpResponse.StatusCode = 406; return encoding.GetBytes("false"); } string requestBody; Stream inputStream = request; Stream innerStream = null; try { if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) { innerStream = inputStream; inputStream = new GZipStream(innerStream, CompressionMode.Decompress); } using (StreamReader reader = new StreamReader(inputStream, encoding)) { requestBody = reader.ReadToEnd(); } } finally { if (innerStream != null) innerStream.Dispose(); inputStream.Dispose(); } keysvals.Add("body", requestBody); Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPost(keysvals, responsedata, agentID); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id) { EntityTransferContext ctx = new EntityTransferContext(); OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } if (args.ContainsKey("context")) ctx.Unpack((OSDMap)args["context"]); AgentDestinationData data = CreateAgentDestinationData(); UnpackData(args, data, request); GridRegion destination = new GridRegion(); destination.RegionID = data.uuid; destination.RegionLocX = data.x; destination.RegionLocY = data.y; destination.RegionName = data.name; GridRegion gatekeeper = ExtractGatekeeper(data); AgentCircuitData aCircuit = new AgentCircuitData(); try { aCircuit.UnpackAgentCircuitData(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } GridRegion source = null; if (args.ContainsKey("source_uuid")) { source = new GridRegion(); source.RegionLocX = Int32.Parse(args["source_x"].AsString()); source.RegionLocY = Int32.Parse(args["source_y"].AsString()); source.RegionName = args["source_name"].AsString(); source.RegionID = UUID.Parse(args["source_uuid"].AsString()); if (args.ContainsKey("source_server_uri")) source.RawServerURI = args["source_server_uri"].AsString(); else source.RawServerURI = null; } OSDMap resp = new OSDMap(2); string reason = String.Empty; // This is the meaning of POST agent //m_regionClient.AdjustUserInformation(aCircuit); //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, data.fromLogin, ctx, out reason); resp["reason"] = OSD.FromString(reason); resp["success"] = OSD.FromBoolean(result); // Let's also send out the IP address of the caller back to the caller (HG 1.5) resp["your_ip"] = OSD.FromString(GetCallerIP(request)); // TODO: add reason if not String.Empty? responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } protected virtual AgentDestinationData CreateAgentDestinationData() { return new AgentDestinationData(); } protected virtual void UnpackData(OSDMap args, AgentDestinationData data, Hashtable request) { // retrieve the input arguments if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out data.x); else m_log.WarnFormat(" -- request didn't have destination_x"); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out data.y); else m_log.WarnFormat(" -- request didn't have destination_y"); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out data.uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) data.name = args["destination_name"].ToString(); if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) data.flags = args["teleport_flags"].AsUInteger(); } protected virtual GridRegion ExtractGatekeeper(AgentDestinationData data) { return null; } protected string GetCallerIP(Hashtable request) { if (request.ContainsKey("headers")) { Hashtable headers = (Hashtable)request["headers"]; //// DEBUG //foreach (object o in headers.Keys) // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString())); string xff = "X-Forwarded-For"; if (!headers.ContainsKey(xff)) xff = xff.ToLower(); if (!headers.ContainsKey(xff) || headers[xff] == null) { // m_log.WarnFormat("[AGENT HANDLER]: No XFF header"); return Util.GetCallerIP(request); } // m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]); IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]); if (ep != null) return ep.Address.ToString(); } // Oops return Util.GetCallerIP(request); } // subclasses can override this protected virtual bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, EntityTransferContext ctx, out string reason) { reason = String.Empty; // The data and protocols are already defined so this is just a dummy to satisfy the interface // TODO: make this end-to-end /* this needs to be sync if ((teleportFlags & (uint)TeleportFlags.ViaLogin) == 0) { Util.FireAndForget(x => { string r; m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out r); m_log.DebugFormat("[AGENT HANDLER]: ASYNC CreateAgent {0}", r); }); return true; } else { */ bool ret = m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out reason); // m_log.DebugFormat("[AGENT HANDLER]: SYNC CreateAgent {0} {1}", ret.ToString(), reason); return ret; // } } } public class AgentPutHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; protected bool m_Proxy = false; public AgentPutHandler(ISimulationService service) : base("PUT", "/agent") { m_SimulationService = service; } public AgentPutHandler(string path) : base("PUT", path) { m_SimulationService = null; } protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); Hashtable keysvals = new Hashtable(); Hashtable headervals = new Hashtable(); string[] querystringkeys = httpRequest.QueryString.AllKeys; string[] rHeaders = httpRequest.Headers.AllKeys; keysvals.Add("uri", httpRequest.RawUrl); keysvals.Add("content-type", httpRequest.ContentType); keysvals.Add("http-method", httpRequest.HttpMethod); foreach (string queryname in querystringkeys) keysvals.Add(queryname, httpRequest.QueryString[queryname]); foreach (string headername in rHeaders) headervals[headername] = httpRequest.Headers[headername]; keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); String requestBody; Encoding encoding = Encoding.UTF8; Stream inputStream = request; Stream innerStream = null; try { if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) { innerStream = inputStream; inputStream = new GZipStream(innerStream, CompressionMode.Decompress); } using (StreamReader reader = new StreamReader(inputStream, encoding)) { requestBody = reader.ReadToEnd(); } } finally { if (innerStream != null) innerStream.Dispose(); inputStream.Dispose(); } keysvals.Add("body", requestBody); httpResponse.StatusCode = 200; httpResponse.ContentType = "text/html"; httpResponse.KeepAlive = false; Hashtable responsedata = new Hashtable(); UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]); httpResponse.StatusCode = 404; return encoding.GetBytes("false"); } DoAgentPut(keysvals, responsedata); httpResponse.StatusCode = (int)responsedata["int_response_code"]; return encoding.GetBytes((string)responsedata["str_response_string"]); } protected void DoAgentPut(Hashtable request, Hashtable responsedata) { // TODO: Encode the ENtityTransferContext EntityTransferContext ctx = new EntityTransferContext(); OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); if (args.ContainsKey("context")) ctx.Unpack((OSDMap)args["context"]); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; string messageType; if (args["message_type"] != null) messageType = args["message_type"].AsString(); else { m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. "); messageType = "AgentData"; } bool result = true; if ("AgentData".Equals(messageType)) { AgentData agent = new AgentData(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID), ctx); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } //agent.Dump(); // This is one of the meanings of PUT agent result = UpdateAgent(destination, agent); } else if ("AgentPosition".Equals(messageType)) { AgentPosition agent = new AgentPosition(); try { agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID), ctx); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); return; } //agent.Dump(); // This is one of the meanings of PUT agent result = m_SimulationService.UpdateAgent(destination, agent); } responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = result.ToString(); //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead } // subclasses can override this protected virtual bool UpdateAgent(GridRegion destination, AgentData agent) { // The data and protocols are already defined so this is just a dummy to satisfy the interface // TODO: make this end-to-end EntityTransferContext ctx = new EntityTransferContext(); return m_SimulationService.UpdateAgent(destination, agent, ctx); } } public class AgentDestinationData { public int x; public int y; public string name; public UUID uuid; public uint flags; public bool fromLogin; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.GrainDirectory; using Orleans.Hosting; using Orleans.Runtime.Scheduler; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Configuration; namespace Orleans.Runtime.GrainDirectory { internal class LocalGrainDirectory : MarshalByRefObject, ILocalGrainDirectory, ISiloStatusListener { /// <summary> /// list of silo members sorted by the hash value of their address /// </summary> private readonly List<SiloAddress> membershipRingList; private readonly HashSet<SiloAddress> membershipCache; private readonly DedicatedAsynchAgent maintainer; private readonly ILogger log; private readonly SiloAddress seed; private readonly RegistrarManager registrarManager; private readonly ISiloStatusOracle siloStatusOracle; private readonly IMultiClusterOracle multiClusterOracle; private readonly IInternalGrainFactory grainFactory; private Action<SiloAddress, SiloStatus> catalogOnSiloRemoved; // Consider: move these constants into an apropriate place internal const int HOP_LIMIT = 3; // forward a remote request no more than two times public static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(5); // Pause 5 seconds between forwards to let the membership directory settle down protected SiloAddress Seed { get { return seed; } } internal ILogger Logger { get { return log; } } // logger is shared with classes that manage grain directory internal bool Running; internal SiloAddress MyAddress { get; private set; } internal IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> DirectoryCache { get; private set; } internal GrainDirectoryPartition DirectoryPartition { get; private set; } public RemoteGrainDirectory RemoteGrainDirectory { get; private set; } public RemoteGrainDirectory CacheValidator { get; private set; } public ClusterGrainDirectory RemoteClusterGrainDirectory { get; private set; } internal OrleansTaskScheduler Scheduler { get; private set; } internal GrainDirectoryHandoffManager HandoffManager { get; private set; } public string ClusterId { get; } internal GlobalSingleInstanceActivationMaintainer GsiActivationMaintainer { get; private set; } private readonly CounterStatistic localLookups; private readonly CounterStatistic localSuccesses; private readonly CounterStatistic fullLookups; private readonly CounterStatistic cacheLookups; private readonly CounterStatistic cacheSuccesses; private readonly CounterStatistic registrationsIssued; private readonly CounterStatistic registrationsSingleActIssued; private readonly CounterStatistic unregistrationsIssued; private readonly CounterStatistic unregistrationsManyIssued; private readonly IntValueStatistic directoryPartitionCount; internal readonly CounterStatistic RemoteLookupsSent; internal readonly CounterStatistic RemoteLookupsReceived; internal readonly CounterStatistic LocalDirectoryLookups; internal readonly CounterStatistic LocalDirectorySuccesses; internal readonly CounterStatistic CacheValidationsSent; internal readonly CounterStatistic CacheValidationsReceived; internal readonly CounterStatistic RegistrationsLocal; internal readonly CounterStatistic RegistrationsRemoteSent; internal readonly CounterStatistic RegistrationsRemoteReceived; internal readonly CounterStatistic RegistrationsSingleActLocal; internal readonly CounterStatistic RegistrationsSingleActRemoteSent; internal readonly CounterStatistic RegistrationsSingleActRemoteReceived; internal readonly CounterStatistic UnregistrationsLocal; internal readonly CounterStatistic UnregistrationsRemoteSent; internal readonly CounterStatistic UnregistrationsRemoteReceived; internal readonly CounterStatistic UnregistrationsManyRemoteSent; internal readonly CounterStatistic UnregistrationsManyRemoteReceived; public LocalGrainDirectory( ILocalSiloDetails siloDetails, OrleansTaskScheduler scheduler, ISiloStatusOracle siloStatusOracle, IMultiClusterOracle multiClusterOracle, IInternalGrainFactory grainFactory, Factory<GrainDirectoryPartition> grainDirectoryPartitionFactory, RegistrarManager registrarManager, ExecutorService executorService, IOptions<DevelopmentClusterMembershipOptions> developmentClusterMembershipOptions, IOptions<MultiClusterOptions> multiClusterOptions, IOptions<GrainDirectoryOptions> grainDirectoryOptions, ILoggerFactory loggerFactory) { this.log = loggerFactory.CreateLogger<LocalGrainDirectory>(); var clusterId = multiClusterOptions.Value.HasMultiClusterNetwork ? siloDetails.ClusterId : null; MyAddress = siloDetails.SiloAddress; Scheduler = scheduler; this.siloStatusOracle = siloStatusOracle; this.multiClusterOracle = multiClusterOracle; this.grainFactory = grainFactory; membershipRingList = new List<SiloAddress>(); membershipCache = new HashSet<SiloAddress>(); ClusterId = clusterId; DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(grainDirectoryOptions.Value); /* TODO - investigate dynamic config changes using IOptions - jbragg clusterConfig.OnConfigChange("Globals/Caching", () => { lock (membershipCache) { DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(globalConfig); } }); */ maintainer = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCacheMaintainer( this, this.DirectoryCache, activations => activations.Select(a => Tuple.Create(a.Silo, a.Activation)).ToList().AsReadOnly(), grainFactory, executorService, loggerFactory); GsiActivationMaintainer = new GlobalSingleInstanceActivationMaintainer(this, this.Logger, grainFactory, multiClusterOracle, executorService, siloDetails, multiClusterOptions, loggerFactory, registrarManager); var primarySiloEndPoint = developmentClusterMembershipOptions.Value.PrimarySiloEndpoint; if (primarySiloEndPoint != null) { this.seed = this.MyAddress.Endpoint.Equals(primarySiloEndPoint) ? this.MyAddress : SiloAddress.New(primarySiloEndPoint, 0); } DirectoryPartition = grainDirectoryPartitionFactory(); HandoffManager = new GrainDirectoryHandoffManager(this, siloStatusOracle, grainFactory, grainDirectoryPartitionFactory, loggerFactory); RemoteGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceId, loggerFactory); CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorId, loggerFactory); RemoteClusterGrainDirectory = new ClusterGrainDirectory(this, Constants.ClusterDirectoryServiceId, clusterId, grainFactory, multiClusterOracle, loggerFactory); // add myself to the list of members AddServer(MyAddress); Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) => String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode()); localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED); localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES); fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED); RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT); RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED); LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED); LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES); cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED); cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () => { long delta1, delta2; long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1); long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2); return String.Format("{0}, Delta={1}", (curr2 != 0 ? (float)curr1 / (float)curr2 : 0) ,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0)); }); CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT); CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED); registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED); RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL); RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT); RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED); registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED); RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL); RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT); RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED); unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED); UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL); UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT); UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED); unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED); UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT); UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED); directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor()); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)this.RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => this.membershipRingList.Count == 0 ? 0 : ((float)100 / (float)this.membershipRingList.Count)); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => this.membershipRingList.Count); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () => { lock (this.membershipCache) { return Utils.EnumerableToString(this.membershipRingList, siloAddressPrint); } }); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(this.FindPredecessors(this.MyAddress, 1), siloAddressPrint)); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(this.FindSuccessors(this.MyAddress, 1), siloAddressPrint)); this.registrarManager = registrarManager; } public void Start() { log.Info("Start"); Running = true; if (maintainer != null) { maintainer.Start(); } if (GsiActivationMaintainer != null) { GsiActivationMaintainer.Start(); } } // Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised. // This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of // grains (for update purposes), which could cause application requests that require a new activation to be created to time out. // The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes // would receive successful responses but would not be reflected in the eventual state of the directory. // It's easy to change this, if we think the trade-off is better the other way. public async Task Stop(bool doOnStopHandoff) { // This will cause remote write requests to be forwarded to the silo that will become the new owner. // Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the // new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've // begun stopping, which could cause them to not get handed off to the new owner. //mark Running as false will exclude myself from CalculateGrainDirectoryPartition(grainId) Running = false; if (maintainer != null) { maintainer.Stop(); } if (GsiActivationMaintainer != null) { GsiActivationMaintainer.Stop(); } if (doOnStopHandoff) { try { await HandoffManager.ProcessSiloStoppingEvent(); } catch (Exception exc) { this.log.LogWarning($"GrainDirectoryHandOffManager failed ProcessSiloStoppingEvent due to exception {exc}"); } } DirectoryPartition.Clear(); DirectoryCache.Clear(); } /// <inheritdoc /> public void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> callback) { if (callback == null) throw new ArgumentNullException(nameof(callback)); lock (membershipCache) { this.catalogOnSiloRemoved = callback; } } protected void AddServer(SiloAddress silo) { lock (membershipCache) { if (membershipCache.Contains(silo)) { // we have already cached this silo return; } membershipCache.Add(silo); // insert new silo in the sorted order long hash = silo.GetConsistentHashCode(); // Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former. // Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then // 'index' will get 0, as needed. int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1; membershipRingList.Insert(index, silo); HandoffManager.ProcessSiloAddEvent(silo); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} added silo {1}", MyAddress, silo); } } protected void RemoveServer(SiloAddress silo, SiloStatus status) { lock (membershipCache) { if (!membershipCache.Contains(silo)) { // we have already removed this silo return; } if (this.catalogOnSiloRemoved != null) { try { // Only notify the catalog once. Order is important: call BEFORE updating membershipRingList. this.catalogOnSiloRemoved(silo, status); } catch (Exception exc) { log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception, String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc); } } // the call order is important HandoffManager.ProcessSiloRemoveEvent(silo); membershipCache.Remove(silo); membershipRingList.Remove(silo); AdjustLocalDirectory(silo); AdjustLocalCache(silo); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} removed silo {1}", MyAddress, silo); } } /// <summary> /// Adjust local directory following the removal of a silo by dropping all activations located on the removed silo /// </summary> /// <param name="removedSilo"></param> protected void AdjustLocalDirectory(SiloAddress removedSilo) { var activationsToRemove = (from pair in DirectoryPartition.GetItems() from pair2 in pair.Value.Instances.Where(pair3 => pair3.Value.SiloAddress.Equals(removedSilo)) select new Tuple<GrainId, ActivationId>(pair.Key, pair2.Key)).ToList(); // drop all records of activations located on the removed silo foreach (var activation in activationsToRemove) { DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2); } } /// Adjust local cache following the removal of a silo by dropping: /// 1) entries that point to activations located on the removed silo /// 2) entries for grains that are now owned by this silo (me) /// 3) entries for grains that were owned by this removed silo - we currently do NOT do that. /// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership). /// We don't do that since first cache refresh handles that. /// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo. /// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner). protected void AdjustLocalCache(SiloAddress removedSilo) { // remove all records of activations located on the removed silo foreach (Tuple<GrainId, IReadOnlyList<Tuple<SiloAddress, ActivationId>>, int> tuple in DirectoryCache.KeyValues) { // 2) remove entries now owned by me (they should be retrieved from my directory partition) if (MyAddress.Equals(CalculateGrainDirectoryPartition(tuple.Item1))) { DirectoryCache.Remove(tuple.Item1); } // 1) remove entries that point to activations located on the removed silo RemoveActivations(DirectoryCache, tuple.Item1, tuple.Item2, tuple.Item3, t => t.Item1.Equals(removedSilo)); } } internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count) { lock (membershipCache) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--) { result.Add(membershipRingList[(i + numMembers) % numMembers]); } return result; } } internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count) { lock (membershipCache) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index + 1; i % numMembers != index && result.Count < count; i++) { result.Add(membershipRingList[i % numMembers]); } return result; } } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (!Equals(updatedSilo, MyAddress)) // Status change for some other silo { if (status.IsTerminating()) { // QueueAction up the "Remove" to run on a system turn Scheduler.QueueAction(() => RemoveServer(updatedSilo, status), CacheValidator.SchedulingContext).Ignore(); } else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active { // QueueAction up the "Remove" to run on a system turn Scheduler.QueueAction(() => AddServer(updatedSilo), CacheValidator.SchedulingContext).Ignore(); } } } private bool IsValidSilo(SiloAddress silo) { return this.siloStatusOracle.IsFunctionalDirectory(silo); } /// <summary> /// Finds the silo that owns the directory information for the given grain ID. /// This method will only be null when I'm the only silo in the cluster and I'm shutting down /// </summary> /// <param name="grainId"></param> /// <returns></returns> public SiloAddress CalculateGrainDirectoryPartition(GrainId grainId) { // give a special treatment for special grains if (grainId.IsSystemTarget) { if (Constants.SystemMembershipTableId.Equals(grainId)) { if (Seed == null) { var errorMsg = $"MembershipTable cannot run without Seed node. Please check your silo configuration make sure it specifies a SeedNode element. " + $"This is in either the configuration file or the {nameof(NetworkingOptions)} configuration. " + " Alternatively, you may want to use reliable membership, such as Azure Table."; throw new ArgumentException(errorMsg, "grainId = " + grainId); } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress); // every silo owns its system targets return MyAddress; } SiloAddress siloAddress = null; int hash = unchecked((int)grainId.GetUniformHashCode()); // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. // excludeThisSIloIfStopping flag was removed because we believe that flag complicates things unnecessarily. We can add it back if it turns out that flag // is doing something valuable. bool excludeMySelf = !Running; lock (membershipCache) { if (membershipRingList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return !Running ? null : MyAddress; } // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes for (var index = membershipRingList.Count - 1; index >= 0; --index) { var item = membershipRingList[index]; if (IsSiloNextInTheRing(item, hash, excludeMySelf)) { siloAddress = item; break; } } if (siloAddress == null) { // If not found in the traversal, last silo will do (we are on a ring). // We checked above to make sure that the list isn't empty, so this should always be safe. siloAddress = membershipRingList[membershipRingList.Count - 1]; // Make sure it's not us... if (siloAddress.Equals(MyAddress) && excludeMySelf) { siloAddress = membershipRingList.Count > 1 ? membershipRingList[membershipRingList.Count - 2] : null; } } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress?.GetConsistentHashCode()); return siloAddress; } public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription) { SiloAddress owner = CalculateGrainDirectoryPartition(grainId); if (owner == null) { // We don't know about any other silos, and we're stopping, so throw throw new InvalidOperationException("Grain directory is stopping"); } if (owner.Equals(MyAddress)) { // if I am the owner, perform the operation locally return null; } if (hopCount >= HOP_LIMIT) { // we are not forwarding because there were too many hops already throw new OrleansException(string.Format("Silo {0} is not owner of {1}, cannot forward {2} to owner {3} because hop limit is reached", MyAddress, grainId, operationDescription, owner)); } // forward to the silo that we think is the owner return owner; } public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation, int hopCount) { var counterStatistic = singleActivation ? (hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued) : (hopCount > 0 ? this.RegistrationsRemoteReceived : this.registrationsIssued); counterStatistic.Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync(recheck)"); } if (forwardAddress == null) { (singleActivation ? RegistrationsSingleActLocal : RegistrationsLocal).Increment(); // we are the owner var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain); if (log.IsEnabled(LogLevel.Trace)) log.Trace($"use registrar {registrar.GetType().Name} for activation {address}"); return registrar.IsSynchronous ? registrar.Register(address, singleActivation) : await registrar.RegisterAsync(address, singleActivation); } else { (singleActivation ? RegistrationsSingleActRemoteSent : RegistrationsRemoteSent).Increment(); // otherwise, notify the owner AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, singleActivation, hopCount + 1); if (singleActivation) { // Caching optimization: // cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation. // this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup! if (result.Address == null) return result; if (!address.Equals(result.Address) || !IsValidSilo(address.Silo)) return result; var cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) }; // update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup. DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag); } else { if (IsValidSilo(address.Silo)) { // Caching optimization: // cache the result of a successfull RegisterActivation call, only if it is not a duplicate activation. // this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup! IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached; if (!DirectoryCache.LookUp(address.Grain, out cached)) { cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) }; } else { var newcached = new List<Tuple<SiloAddress, ActivationId>>(cached.Count + 1); newcached.AddRange(cached); newcached.Add(Tuple.Create(address.Silo, address.Activation)); cached = newcached; } // update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup. DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag); } } return result; } } public Task UnregisterAfterNonexistingActivation(ActivationAddress addr, SiloAddress origin) { log.Trace("UnregisterAfterNonexistingActivation addr={0} origin={1}", addr, origin); if (origin == null || membershipCache.Contains(origin)) { // the request originated in this cluster, call unregister here return UnregisterAsync(addr, UnregistrationCause.NonexistentActivation, 0); } else { // the request originated in another cluster, call unregister there var remoteDirectory = GetDirectoryReference(origin); return remoteDirectory.UnregisterAsync(addr, UnregistrationCause.NonexistentActivation); } } public async Task UnregisterAsync(ActivationAddress address, UnregistrationCause cause, int hopCount) { (hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment(); if (hopCount == 0) InvalidateCacheEntry(address); // see if the owner is somewhere else (returns null if we are owner) var forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardaddress != null) { await Task.Delay(RETRY_DELAY); forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync(recheck)"); } if (forwardaddress == null) { // we are the owner UnregistrationsLocal.Increment(); var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain); if (registrar.IsSynchronous) registrar.Unregister(address, cause); else await registrar.UnregisterAsync(new List<ActivationAddress>() { address }, cause); } else { UnregistrationsRemoteSent.Increment(); // otherwise, notify the owner await GetDirectoryReference(forwardaddress).UnregisterAsync(address, cause, hopCount + 1); } } private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value) { if (dictionary == null) dictionary = new Dictionary<K,List<V>>(); List<V> list; if (! dictionary.TryGetValue(key, out list)) dictionary[key] = list = new List<V>(); list.Add(value); } // helper method to avoid code duplication inside UnregisterManyAsync private void UnregisterOrPutInForwardList(IEnumerable<ActivationAddress> addresses, UnregistrationCause cause, int hopCount, ref Dictionary<SiloAddress, List<ActivationAddress>> forward, List<Task> tasks, string context) { Dictionary<IGrainRegistrar, List<ActivationAddress>> unregisterBatches = new Dictionary<IGrainRegistrar, List<ActivationAddress>>(); foreach (var address in addresses) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, context); if (forwardAddress != null) { AddToDictionary(ref forward, forwardAddress, address); } else { // we are the owner UnregistrationsLocal.Increment(); var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain); if (registrar.IsSynchronous) { registrar.Unregister(address, cause); } else { List<ActivationAddress> list; if (!unregisterBatches.TryGetValue(registrar, out list)) unregisterBatches.Add(registrar, list = new List<ActivationAddress>()); list.Add(address); } } } // batch-unregister for each asynchronous registrar foreach (var kvp in unregisterBatches) { tasks.Add(kvp.Key.UnregisterAsync(kvp.Value, cause)); } } public async Task UnregisterManyAsync(List<ActivationAddress> addresses, UnregistrationCause cause, int hopCount) { (hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment(); Dictionary<SiloAddress, List<ActivationAddress>> forwardlist = null; var tasks = new List<Task>(); UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist, tasks, "UnregisterManyAsync"); // before forwarding to other silos, we insert a retry delay and re-check destination if (hopCount > 0 && forwardlist != null) { await Task.Delay(RETRY_DELAY); Dictionary<SiloAddress, List<ActivationAddress>> forwardlist2 = null; UnregisterOrPutInForwardList(forwardlist.SelectMany(kvp => kvp.Value), cause, hopCount, ref forwardlist2, tasks, "UnregisterManyAsync(recheck)"); forwardlist = forwardlist2; } // forward the requests if (forwardlist != null) { foreach (var kvp in forwardlist) { UnregistrationsManyRemoteSent.Increment(); tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, cause, hopCount + 1)); } } // wait for all the requests to finish await Task.WhenAll(tasks); } public bool LocalLookup(GrainId grain, out AddressesAndTag result) { localLookups.Increment(); SiloAddress silo = CalculateGrainDirectoryPartition(grain); if (log.IsEnabled(LogLevel.Debug)) log.Debug("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo?.GetConsistentHashCode()); //this will only happen if I'm the only silo in the cluster and I'm shutting down if (silo == null) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}=null", grain); result = new AddressesAndTag(); return false; } // check if we own the grain if (silo.Equals(MyAddress)) { LocalDirectoryLookups.Increment(); result = GetLocalDirectoryData(grain); if (result.Addresses == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}=null", grain); return false; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup mine {0}={1}", grain, result.Addresses.ToStrings()); LocalDirectorySuccesses.Increment(); localSuccesses.Increment(); return true; } // handle cache result = new AddressesAndTag(); cacheLookups.Increment(); result.Addresses = GetLocalCacheData(grain); if (result.Addresses == null) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("TryFullLookup else {0}=null", grain); return false; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("LocalLookup cache {0}={1}", grain, result.Addresses.ToStrings()); cacheSuccesses.Increment(); localSuccesses.Increment(); return true; } public AddressesAndTag GetLocalDirectoryData(GrainId grain) { return DirectoryPartition.LookUpActivations(grain); } public List<ActivationAddress> GetLocalCacheData(GrainId grain) { IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached; return DirectoryCache.LookUp(grain, out cached) ? cached.Select(elem => ActivationAddress.GetAddress(elem.Item1, grain, elem.Item2)).Where(addr => IsValidSilo(addr.Silo)).ToList() : null; } public Task<AddressesAndTag> LookupInCluster(GrainId grainId, string clusterId) { if (clusterId == null) throw new ArgumentNullException(nameof(clusterId)); if (clusterId == ClusterId) { return LookupAsync(grainId); } else { // find gateway var gossipOracle = this.multiClusterOracle; var clusterGatewayAddress = gossipOracle.GetRandomClusterGateway(clusterId); if (clusterGatewayAddress != null) { // call remote grain directory var remotedirectory = GetDirectoryReference(clusterGatewayAddress); return remotedirectory.LookupAsync(grainId); } else { return Task.FromResult(default(AddressesAndTag)); } } } public async Task<AddressesAndTag> LookupAsync(GrainId grainId, int hopCount = 0) { (hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync(recheck)"); } if (forwardAddress == null) { // we are the owner LocalDirectoryLookups.Increment(); var localResult = DirectoryPartition.LookUpActivations(grainId); if (localResult.Addresses == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}=none", grainId); localResult.Addresses = new List<ActivationAddress>(); localResult.VersionTag = GrainInfo.NO_ETAG; return localResult; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup mine {0}={1}", grainId, localResult.Addresses.ToStrings()); LocalDirectorySuccesses.Increment(); return localResult; } else { // Just a optimization. Why sending a message to someone we know is not valid. if (!IsValidSilo(forwardAddress)) { throw new OrleansException(String.Format("Current directory at {0} is not stable to perform the lookup for grainId {1} (it maps to {2}, which is not a valid silo). Retry later.", MyAddress, grainId, forwardAddress)); } RemoteLookupsSent.Increment(); var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1); // update the cache result.Addresses = result.Addresses.Where(t => IsValidSilo(t.Silo)).ToList(); if (log.IsEnabled(LogLevel.Trace)) log.Trace("FullLookup remote {0}={1}", grainId, result.Addresses.ToStrings()); var entries = result.Addresses.Select(t => Tuple.Create(t.Silo, t.Activation)).ToList(); if (entries.Count > 0) DirectoryCache.AddOrUpdate(grainId, entries, result.VersionTag); return result; } } public async Task DeleteGrainAsync(GrainId grainId, int hopCount) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync(recheck)"); } if (forwardAddress == null) { // we are the owner var registrar = this.registrarManager.GetRegistrarForGrain(grainId); if (registrar.IsSynchronous) registrar.Delete(grainId); else await registrar.DeleteAsync(grainId); } else { // otherwise, notify the owner DirectoryCache.Remove(grainId); await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1); } } public void InvalidateCacheEntry(ActivationAddress activationAddress, bool invalidateDirectoryAlso = false) { int version; IReadOnlyList<Tuple<SiloAddress, ActivationId>> list; var grainId = activationAddress.Grain; var activationId = activationAddress.Activation; // look up grainId activations if (DirectoryCache.LookUp(grainId, out list, out version)) { RemoveActivations(DirectoryCache, grainId, list, version, t => t.Item2.Equals(activationId)); } // for multi-cluster registration, the local directory may cache remote activations // and we need to remove them here, on the fast path, to avoid forwarding the message // to the wrong destination again if (invalidateDirectoryAlso && MyAddress.Equals(CalculateGrainDirectoryPartition(grainId))) { var registrar = this.registrarManager.GetRegistrarForGrain(grainId); registrar.InvalidateCache(activationAddress); } } /// <summary> /// For testing purposes only. /// Returns the silo that this silo thinks is the primary owner of directory information for /// the provided grain ID. /// </summary> /// <param name="grain"></param> /// <returns></returns> public SiloAddress GetPrimaryForGrain(GrainId grain) { return CalculateGrainDirectoryPartition(grain); } /// <summary> /// For testing purposes only. /// Returns the silos that this silo thinks hold copies of the directory information for /// the provided grain ID. /// </summary> /// <param name="grain"></param> /// <returns></returns> public List<SiloAddress> GetSilosHoldingDirectoryInformationForGrain(GrainId grain) { var primary = CalculateGrainDirectoryPartition(grain); return FindPredecessors(primary, 1); } /// <summary> /// For testing purposes only. /// Returns the directory information held by the local silo for the provided grain ID. /// The result will be null if no information is held. /// </summary> /// <param name="grain"></param> /// <param name="isPrimary"></param> /// <returns></returns> public List<ActivationAddress> GetLocalDataForGrain(GrainId grain, out bool isPrimary) { var primary = CalculateGrainDirectoryPartition(grain); List<ActivationAddress> backupData = HandoffManager.GetHandedOffInfo(grain); if (MyAddress.Equals(primary)) { log.Assert(ErrorCode.DirectoryBothPrimaryAndBackupForGrain, backupData == null, "Silo contains both primary and backup directory data for grain " + grain); isPrimary = true; return GetLocalDirectoryData(grain).Addresses; } isPrimary = false; return backupData; } public override string ToString() { var sb = new StringBuilder(); long localLookupsDelta; long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta); long localLookupsSucceededDelta; long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta); long fullLookupsDelta; long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta); long directoryPartitionSize = directoryPartitionCount.GetCurrentValue(); sb.AppendLine("Local Grain Directory:"); sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine(); sb.AppendLine(" Since last call:"); sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine(); if (localLookupsDelta > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine(); sb.AppendLine(" Since start:"); sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine(); if (localLookupsCurrent > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine(); sb.Append(DirectoryCache.ToString()); return sb.ToString(); } private long RingDistanceToSuccessor() { long distance; List<SiloAddress> successorList = FindSuccessors(MyAddress, 1); if (successorList == null || successorList.Count == 0) { distance = 0; } else { SiloAddress successor = successorList.First(); distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor); } return distance; } private string RingDistanceToSuccessor_2() { const long ringSize = int.MaxValue * 2L; long distance; List<SiloAddress> successorList = FindSuccessors(MyAddress, 1); if (successorList == null || successorList.Count == 0) { distance = 0; } else { SiloAddress successor = successorList.First(); distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor); } double averageRingSpace = membershipRingList.Count == 0 ? 0 : (1.0 / (double)membershipRingList.Count); return string.Format("RingDistance={0:X}, %Ring Space {1:0.00000}%, Average %Ring Space {2:0.00000}%", distance, ((double)distance / (double)ringSize) * 100.0, averageRingSpace * 100.0); } private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2) { const long ringSize = int.MaxValue * 2L; long hash1 = silo1.GetConsistentHashCode(); long hash2 = silo2.GetConsistentHashCode(); if (hash2 > hash1) return hash2 - hash1; if (hash2 < hash1) return ringSize - (hash1 - hash2); return 0; } public string RingStatusToString() { var sb = new StringBuilder(); sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine(); sb.AppendLine("Ring is:"); lock (membershipCache) { foreach (var silo in membershipRingList) sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine(); } sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine(); sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")); return sb.ToString(); } internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo) { return this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo); } private bool IsSiloNextInTheRing(SiloAddress siloAddr, int hash, bool excludeMySelf) { return siloAddr.GetConsistentHashCode() <= hash && (!excludeMySelf || !siloAddr.Equals(MyAddress)); } private static void RemoveActivations(IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> directoryCache, GrainId key, IReadOnlyList<Tuple<SiloAddress, ActivationId>> activations, int version, Func<Tuple<SiloAddress, ActivationId>, bool> doRemove) { int removeCount = activations.Count(doRemove); if (removeCount == 0) { return; // nothing to remove, done here } if (activations.Count > removeCount) // still some left, update activation list. Note: Most of the time there should be only one activation { var newList = new List<Tuple<SiloAddress, ActivationId>>(activations.Count - removeCount); newList.AddRange(activations.Where(t => !doRemove(t))); directoryCache.AddOrUpdate(key, newList, version); } else // no activations left, remove from cache { directoryCache.Remove(key); } } public bool IsSiloInCluster(SiloAddress silo) { lock (membershipCache) { return membershipCache.Contains(silo); } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS { using System; using System.Collections.Generic; using System.IO; /// <summary> /// Contain a GLOBCNT range. /// </summary> public struct GLOBCNTRange { /// <summary> /// The start GLOBCNT. /// </summary> private GLOBCNT startGLOBCNT; /// <summary> /// The end GLOBCNT. /// </summary> private GLOBCNT endGLOBCNT; /// <summary> /// Initializes a new instance of the GLOBCNTRange structure. /// </summary> /// <param name="start">The starting GLOBCNT of the range.</param> /// <param name="end">The end GLOBCNT of the range.</param> public GLOBCNTRange(GLOBCNT start, GLOBCNT end) { if (start > end) { AdapterHelper.Site.Assert.Fail("The start GLOBCNT should not large than the end GLOBCNT."); } this.startGLOBCNT = start; this.endGLOBCNT = end; } /// <summary> /// Gets or sets the start GLOBCNT. /// </summary> public GLOBCNT StartGLOBCNT { get { return this.startGLOBCNT; } set { this.startGLOBCNT = value; } } /// <summary> /// Gets or sets the end GLOBCNT. /// </summary> public GLOBCNT EndGLOBCNT { get { return this.endGLOBCNT; } set { this.endGLOBCNT = value; } } /// <summary> /// Gets a value indicating whether this range a singleton. /// </summary> public bool IsSingleton { get { return this.startGLOBCNT == this.endGLOBCNT; } } /// <summary> /// Indicates whether has the GLOBCNT. /// </summary> /// <param name="cnt">The GLOBCNT.</param> /// <returns>If the GLOBCNT is in this range, return true, else false.</returns> public bool Contains(GLOBCNT cnt) { return this.StartGLOBCNT <= cnt && this.EndGLOBCNT >= cnt; } /// <summary> /// Indicates whether has the GLOBCNTRange. /// </summary> /// <param name="range">A GLOBCNTRange.</param> /// <returns>If the GLOBCNTRange is in this range, return true, else false.</returns> public bool Contains(GLOBCNTRange range) { return range.StartGLOBCNT >= this.StartGLOBCNT && range.EndGLOBCNT <= this.EndGLOBCNT; } /// <summary> /// Get the same high order bytes of this range. /// </summary> /// <returns>The same high order bytes.</returns> public byte[] GetSameHighOrderValues() { int i = 0; byte[] tmp1 = StructureSerializer.Serialize(this.StartGLOBCNT); byte[] tmp2 = StructureSerializer.Serialize(this.EndGLOBCNT); while (i < tmp1.Length && tmp1[i] == tmp2[i]) { i++; } byte[] r = new byte[i]; Array.Copy(tmp1, r, i); return r; } } /// <summary> /// A GLOBSET is a set of GLOBCNT values /// that are typically reduced to one or more GLOBCNT ranges. /// </summary> [SerializableObjectAttribute(true, true)] public class GLOBSET : SerializableBase { /// <summary> /// Contains common bytes. /// </summary> private CommonByteStack stack; /// <summary> /// A stream instance which is used to deserialize object. /// </summary> private Stream stream; /// <summary> /// A list of GLOBCNTs. /// </summary> private List<GLOBCNT> globcntList; /// <summary> /// Contains GLOBCNTRanges in the stream. /// </summary> private List<GLOBCNTRange> globcntRangeList; /// <summary> /// A list of command generated while deserializing. /// </summary> private List<Command> deserializedcommandList; /// <summary> /// Indicates whether all GLOBCNTs in GLOBSET when serializing. /// </summary> private bool isAllGLOBCNTInGLOBSET; /// <summary> /// Gets a value indicating whether all Duplicate GLOBCNTs removed when serializing. /// </summary> private bool hasAllDuplicateGLOBCNTRemoved; /// <summary> /// Indicates whether all GLOBCNTs are arranged from lowest to highest. /// </summary> private bool isAllGLOBCNTRanged; /// <summary> /// Indicates whether GLOBCNT values are grouped into consecutive ranges /// with a low GLOBCNT value and a high GLOBCNT value. /// </summary> private bool hasGLOBCNTGroupedIntoRanges; /// <summary> /// Indicates whether GLOBCNT value which is disjoint is made into a singleton range /// with the low and high GLOBCNT values being the same. /// </summary> private bool isDisjointGLOBCNTMadeIntoSingleton; /// <summary> /// Command types. /// </summary> private enum Operation : byte { /// <summary> /// Represent the push1 command. /// </summary> Push1 = 0x01, /// <summary> /// Represent the push2 command. /// </summary> Push2 = 0x02, /// <summary> /// Represent the push3 command. /// </summary> Push3 = 0x03, /// <summary> /// Represent the push4 command. /// </summary> Push4 = 0x04, /// <summary> /// Represent the push5 command. /// </summary> Push5 = 0x05, /// <summary> /// Represent the push6 command. /// </summary> Push6 = 0x06, /// <summary> /// Represent the pop command. /// </summary> Pop = 0x50, /// <summary> /// Represent the bitmask command. /// </summary> Bitmask = 0x42, /// <summary> /// Represent the range command. /// </summary> Range = 0x52, /// <summary> /// Represent the end command. /// </summary> End = 0x00 } /// <summary> /// Gets a value indicating whether GLOBCNT value which is disjoint is made into a singleton range /// with the low and high GLOBCNT values being the same. /// </summary> public bool IsDisjointGLOBCNTMadeIntoSingleton { get { return this.isDisjointGLOBCNTMadeIntoSingleton; } } /// <summary> /// Gets or sets the GLOBCNTList. /// </summary> public List<GLOBCNT> GLOBCNTList { get { // Too many GLOBCNT from a range. if (this.globcntRangeList != null) { this.globcntList = GetGLOBCNTList(this.globcntRangeList); } return this.globcntList; } set { this.globcntList = value; } } /// <summary> /// Gets or sets the GLOBCNTRangeList which contains GLOBCNTRanges in the stream. /// </summary> public List<GLOBCNTRange> GLOBCNTRangeList { get { return this.globcntRangeList; } set { this.globcntRangeList = value; } } /// <summary> /// Gets a list of command generated while deserializing. /// </summary> public List<Command> DeserializedCommandList { get { return this.deserializedcommandList; } } /// <summary> /// Gets a value indicating whether all GLOBCNT in GLOBSET when serializing. /// </summary> public bool IsAllGLOBCNTInGLOBSET { get { return this.isAllGLOBCNTInGLOBSET; } } /// <summary> /// Gets a value indicating whether all Duplicate GLOBCNT removed when serializing. /// </summary> public bool HasAllDuplicateGLOBCNTRemoved { get { return this.hasAllDuplicateGLOBCNTRemoved; } } /// <summary> /// Gets a value indicating whether all GLOBCNTs are arranged from lowest to highest. /// </summary> public bool IsAllGLOBCNTRanged { get { return this.isAllGLOBCNTRanged; } } /// <summary> /// Gets a value indicating whether GLOBCNT values are grouped into consecutive ranges /// with a low GLOBCNT value and a high GLOBCNT value /// </summary> public bool HasGLOBCNTGroupedIntoRanges { get { return this.hasGLOBCNTGroupedIntoRanges; } } /// <summary> /// Get GLOBCNTs from a GLOBCNTRange list. /// </summary> /// <param name="rangeList">A GLOBCNTRange list.</param> /// <returns>A GLOBCNT list corresponding to the GLOBCNTRange list.</returns> public static List<GLOBCNT> GetGLOBCNTList(List<GLOBCNTRange> rangeList) { List<GLOBCNT> cnts = new List<GLOBCNT>(); foreach (GLOBCNTRange range in rangeList) { GLOBCNT tmp = range.StartGLOBCNT; cnts.Add(tmp); tmp = GLOBCNT.Inc(tmp); while (tmp <= range.EndGLOBCNT) { cnts.Add(tmp); tmp = GLOBCNT.Inc(tmp); } } return cnts; } /// <summary> /// Get GLOBCNTRanges from a GLOBCNT list. /// </summary> /// <param name="globcntList">A GLOBCNT list.</param> /// <returns>A GLOBCNTRange list corresponding to the GLOBCNT list.</returns> public static List<GLOBCNTRange> GetGLOBCNTRange(List<GLOBCNT> globcntList) { // _REPLID = id; int i, j; List<GLOBCNT> list = new List<GLOBCNT>(); List<GLOBCNTRange> globSETRangeList = new List<GLOBCNTRange>(); // Do a copy. for (i = 0; i < globcntList.Count; i++) { list.Add(globcntList[i]); } // Remove all the duplicate GLOBCNT values. for (i = 0; i < list.Count - 1; i++) { j = i + 1; while (j < list.Count) { if (list[i] == list[j]) { list.RemoveAt(j); continue; } else { j++; } } } // Sort GLOBCNT. list.Sort(new Comparison<GLOBCNT>(delegate(GLOBCNT c1, GLOBCNT c2) { if (c1 < c2) { return -1; } if (c1 > c2) { return 1; } return 0; })); // Make a GLOBCNTRange list. i = 0; while (i < list.Count) { GLOBCNT start = list[i]; GLOBCNT end = start; GLOBCNT next = end; j = i + 1; while (j < list.Count) { end = next; next = GLOBCNT.Inc(end); if (list[j] == next) { list.RemoveAt(j); continue; } else { break; } } globSETRangeList.Add(new GLOBCNTRange(start, end)); i++; } return globSETRangeList; } /// <summary> /// Serialize fields to a stream. /// </summary> /// <param name="stream">The stream where serialized instance will be wrote.</param> /// <returns>Bytes written to the stream.</returns> public override int Serialize(Stream stream) { int bytesWriren = 0; this.stream = stream; this.deserializedcommandList = null; this.stack = new CommonByteStack(); this.globcntRangeList = GetGLOBCNTRange(this.GLOBCNTList); this.isAllGLOBCNTInGLOBSET = true; this.isAllGLOBCNTRanged = true; this.isDisjointGLOBCNTMadeIntoSingleton = true; this.hasAllDuplicateGLOBCNTRemoved = true; this.hasGLOBCNTGroupedIntoRanges = true; bytesWriren += this.Compress(0, this.globcntRangeList.Count - 1); bytesWriren += this.End(stream); return bytesWriren; } /// <summary> /// Deserialize fields in this class from a stream. /// </summary> /// <param name="stream">Stream contains a serialized instance of this class.</param> /// <param name="size">How many bytes can read if -1, no limitation.MUST be -1.</param> /// <returns>Bytes have been read from the stream.</returns> public override int Deserialize(Stream stream, int size) { AdapterHelper.Site.Assert.AreEqual(-1, size, "The size value MUST be -1, but the actual value is {0}.", size); int bytesRead = 0; this.stream = stream; this.globcntList = new List<GLOBCNT>(); this.globcntRangeList = new List<GLOBCNTRange>(); this.stack = new CommonByteStack(); this.deserializedcommandList = new List<Command>(); Operation op = this.ReadOperation(); bytesRead += 1; while (op != Operation.End) { switch (op) { case Operation.Bitmask: if (this.stack.Bytes != 5) { AdapterHelper.Site.Assert.Fail("The deserialization operation should be successful."); } else { byte[] commonBytes = stack.GetCommonBytes(); byte startValue, bitmask; bytesRead += ReadBitmaskValue(out startValue, out bitmask); List<GLOBCNTRange> tmp = FromBitmask(commonBytes, startValue, bitmask); BitmaskCommand bmCmd = new BitmaskCommand((byte)op, startValue, bitmask) { CorrespondingGLOBCNTRangeList = tmp }; deserializedcommandList.Add(bmCmd); for (int i = 0; i < tmp.Count; i++) { globcntRangeList.Add(tmp[i]); } tmp = null; } break; case Operation.End: this.deserializedcommandList.Add(new EndCommand((byte)op)); return bytesRead; case Operation.Pop: this.deserializedcommandList.Add(new PopCommand((byte)op)); this.stack.Pop(); break; case Operation.Range: { byte[] lowValue, highValue; bytesRead += this.ReadRangeValue(out lowValue, out highValue); GLOBCNTRange range = this.FromRange( this.stack.GetCommonBytes(), lowValue, highValue); List<GLOBCNTRange> rangeList = new List<GLOBCNTRange> { range }; RangeCommand rngCmd = new RangeCommand((byte)op, lowValue, highValue) { CorrespondingGLOBCNTRangeList = rangeList }; this.deserializedcommandList.Add(rngCmd); this.globcntRangeList.Add(range); } break; case Operation.Push1: case Operation.Push2: case Operation.Push3: case Operation.Push4: case Operation.Push5: case Operation.Push6: int pushByteCount = (int)op; byte[] pushBytes; bytesRead += this.ReadPushedValue(pushByteCount, out pushBytes); PushCommand pshCmd = new PushCommand((byte)op, pushBytes); if (6 == pushByteCount + this.stack.Bytes) { List<GLOBCNTRange> rangeList = new List<GLOBCNTRange>(); GLOBCNTRange range = this.FromPush(this.stack.GetCommonBytes(), pushBytes); rangeList.Add(range); this.globcntRangeList.Add(range); pshCmd.CorrespondingGLOBCNTRangeList = rangeList; this.deserializedcommandList.Add(pshCmd); break; } this.deserializedcommandList.Add(pshCmd); this.stack.Push(pushBytes); break; default: AdapterHelper.Site.Assert.Fail("The operation get from the stream is invalid, its value is {0}.", op); break; } op = this.ReadOperation(); bytesRead += 1; } if (op == Operation.End) { this.deserializedcommandList.Add(new EndCommand((byte)op)); } this.isAllGLOBCNTInGLOBSET = true; this.isAllGLOBCNTRanged = true; this.isDisjointGLOBCNTMadeIntoSingleton = true; this.hasAllDuplicateGLOBCNTRemoved = true; this.hasGLOBCNTGroupedIntoRanges = true; return bytesRead; } /// <summary> /// Verifies a condition. /// </summary> /// <param name="condition">A boolean value.</param> private void Verify(bool condition) { AdapterHelper.Site.Assert.IsTrue(condition, "The condition should be true."); } /// <summary> /// Writes a push command. /// </summary> /// <param name="stream">A Stream object.</param> /// <param name="values">A byte array contains values of the push command.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int Push(Stream stream, byte[] values) { int size = 0; if (values == null || values.Length == 0 || values.Length > 6) { AdapterHelper.Site.Assert.Fail("The value of the parameter of \"values\" in Push method is invalid."); } stream.WriteByte((byte)values.Length); size += 1; stream.Write(values, 0, values.Length); size += values.Length; return size; } /// <summary> /// Writes a pop command to a stream. /// </summary> /// <param name="stream">A stream object.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int Pop(Stream stream) { stream.WriteByte((byte)Operation.Pop); return 1; } /// <summary> /// Writes an end command to a stream. /// </summary> /// <param name="stream">A stream object.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int End(Stream stream) { stream.WriteByte((byte)Operation.End); return 1; } /// <summary> /// Writes a bitmask command to a stream. /// </summary> /// <param name="stream">A Stream object.</param> /// <param name="startValue">The start value of the push command.</param> /// <param name="bitmask">The bitmask of the push command.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int Bitmask(Stream stream, byte startValue, byte bitmask) { stream.WriteByte((byte)Operation.Bitmask); stream.WriteByte(startValue); stream.WriteByte(bitmask); return 3; } /// <summary> /// Writes a range command to a stream. /// </summary> /// <param name="stream">A Stream object.</param> /// <param name="lowValue">The lowValue of a range command.</param> /// <param name="highValue">The highValue of a range command.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int Range(Stream stream, byte[] lowValue, byte[] highValue) { if (lowValue == null || highValue == null || lowValue.Length != highValue.Length || lowValue.Length == 0 || lowValue.Length > 6) { AdapterHelper.Site.Assert.Fail("The values of highValue or lowValue arguments in Range method are invalid."); } stream.WriteByte((byte)Operation.Range); stream.Write(lowValue, 0, lowValue.Length); stream.Write(highValue, 0, highValue.Length); return 1 + (2 * lowValue.Length); } /// <summary> /// Reads a byte from the stream. /// </summary> /// <returns>A byte value read from the stream.</returns> private byte ReadByte() { return StreamHelper.ReadUInt8(this.stream); } /// <summary> /// Reads a bitmask command from the stream. /// </summary> /// <param name="startingValue">The start value of the bitmask command.</param> /// <param name="bitmask">The bitmask of the bitmask command.</param> /// <returns>The count of bytes have been read.</returns> private int ReadBitmaskValue(out byte startingValue, out byte bitmask) { startingValue = this.ReadByte(); bitmask = this.ReadByte(); return 2; } /// <summary> /// Reads a range command from the stream. /// </summary> /// <param name="lowValue">The low value of the range command.</param> /// <param name="highValue">The high value of the range command.</param> /// <returns>The count of bytes have been read from the stream.</returns> private int ReadRangeValue(out byte[] lowValue, out byte[] highValue) { int size = 6 - this.stack.Bytes; lowValue = new byte[size]; highValue = new byte[size]; this.stream.Read(lowValue, 0, size); this.stream.Read(highValue, 0, size); return size * 2; } /// <summary> /// Reads a push command from the stream. /// </summary> /// <param name="size">The size of the push command.</param> /// <param name="commonBytes">The common bytes in the push command.</param> /// <returns>The count of bytes have been read from the stream.</returns> private int ReadPushedValue(int size, out byte[] commonBytes) { commonBytes = new byte[size]; this.stream.Read(commonBytes, 0, size); return size; } /// <summary> /// Reads an operation byte from a stream. /// </summary> /// <returns>An operation enumeration.</returns> private Operation ReadOperation() { return (Operation)this.ReadByte(); } /// <summary> /// Gets high order command bytes in the GLOBCNTRange list. /// </summary> /// <param name="startIndex">The start index of the GLOBCNTRange list to get high order common bytes.</param> /// <param name="endIndex">The end index of the GLOBCNTRange list to get high order common bytes.</param> /// <param name="byteIndex">Specifies the index of GLOBCNTRange's common bytes to compare from.</param> /// <param name="firstDiffIndex">The index of the first GLOBCNTRange which have different byte with previous ones.</param> /// <returns>A byte array contain common bytes.</returns> private byte[] HighOrderCommonBytes( int startIndex, int endIndex, int byteIndex, out int firstDiffIndex) { this.Verify(startIndex < endIndex); int len = 0; int i, j = endIndex; bool hasDiff = false; byte[] firstRangeCommonBytes = this.globcntRangeList[startIndex] .GetSameHighOrderValues(); for (i = byteIndex; i < firstRangeCommonBytes.Length && !hasDiff; i++) { byte common = firstRangeCommonBytes[i]; for (j = startIndex + 1; j <= endIndex; j++) { byte[] bytes = this.globcntRangeList[j] .GetSameHighOrderValues(); if (bytes[i] != common) { hasDiff = true; break; } } if (hasDiff) { break; } } len = hasDiff ? i - byteIndex : firstRangeCommonBytes.Length - byteIndex; firstDiffIndex = hasDiff ? j : endIndex + 1; byte[] r = new byte[len]; Array.Copy(firstRangeCommonBytes, byteIndex, r, 0, len); return r; } /// <summary> /// Compresses GLOBCNTRanges in the GLOBCNTRange list to as a bitmask command. /// </summary> /// <param name="startIndex">The start index of the GLOBCNTRange in the GLOBCNTRange list to compress.</param> /// <param name="endIndex">The end index of the GLOBCNTRange in the GLOBCNTRange list to compress.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int CompressBitmask(int startIndex, int endIndex) { this.Verify(startIndex <= endIndex); List<GLOBCNT> list = GetGLOBCNTList( this.globcntRangeList.GetRange(startIndex, endIndex - startIndex + 1)); byte bitmask = 0; GLOBCNT tmp = list[0]; byte startValue = tmp.Byte6; tmp = GLOBCNT.Inc(tmp); this.Verify(list.Count < 10); for (int i = 0; i < 9; i++) { if (list.Contains(tmp)) { bitmask |= checked((byte)(1 << i)); } tmp = GLOBCNT.Inc(tmp); } return this.Bitmask(this.stream, startValue, bitmask); } /// <summary> /// Compresses a GLOBCNTRange in the GLOBCNTRange list to as a bitmask command. /// </summary> /// <param name="index">The index of the GLOBCNTRange.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int CompressRange(int index) { int bytes = 6 - this.stack.Bytes; GLOBCNT cnt1 = this.globcntRangeList[index].StartGLOBCNT; GLOBCNT cnt2 = this.globcntRangeList[index].EndGLOBCNT; byte[] tmp1 = new byte[bytes]; Array.Copy( StructureSerializer.Serialize(cnt1), 6 - bytes, tmp1, 0, bytes); byte[] tmp2 = new byte[bytes]; Array.Copy( StructureSerializer.Serialize( cnt2), 6 - bytes, tmp2, 0, bytes); return this.Range(this.stream, tmp1, tmp2); } /// <summary> /// Compresses a singleton GLOBCNTRange. /// </summary> /// <param name="index">The index of the GLOBCNTRange.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int CompressSingleton(int index) { this.Verify(this.globcntRangeList[index].StartGLOBCNT == this.globcntRangeList[index].EndGLOBCNT); int byteCount = 6 - this.stack.Bytes; GLOBCNT cnt = this.globcntRangeList[index].StartGLOBCNT; byte[] tmp = new byte[byteCount]; Array.Copy( StructureSerializer.Serialize(cnt), 6 - byteCount, tmp, 0, byteCount); return this.Push(this.stream, tmp); } /// <summary> /// Compress the last byte(6th) of GLOBCNTRanges. /// </summary> /// <param name="startIndex">The start index of GLOBCNTRanges to compress.</param> /// <param name="endIndex">The end index of GLOBCNTRanges to compress.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int CompressLastByte(int startIndex, int endIndex) { this.Verify(this.stack.Bytes == 5); int bytesWriten = 0; int nextCompressIndex = startIndex; while (startIndex <= endIndex) { byte tmp1 = this.globcntRangeList[startIndex].StartGLOBCNT.Byte6; byte tmp2 = this.globcntRangeList[nextCompressIndex].EndGLOBCNT.Byte6; if (tmp2 - tmp1 >= 9) { bytesWriten += this.CompressRange(nextCompressIndex); nextCompressIndex++; } else { nextCompressIndex = startIndex; while (nextCompressIndex < endIndex) { tmp2 = this.globcntRangeList[nextCompressIndex + 1] .EndGLOBCNT.Byte6; if (tmp2 - tmp1 < 9) { nextCompressIndex++; } else { break; } } if (nextCompressIndex == startIndex) { if (this.globcntRangeList[startIndex].IsSingleton) { bytesWriten += this.CompressSingleton(startIndex); } else { bytesWriten += this.CompressRange(startIndex); } } else { bytesWriten += this.CompressBitmask( startIndex, nextCompressIndex); } startIndex = nextCompressIndex + 1; } } return bytesWriten; } /// <summary> /// Compresses a GLOBCNTRange to the stream. /// </summary> /// <param name="index">The index of the GLOBCNTRange.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int Compress(int index) { int bytesWriten = 0; if (this.globcntRangeList[index].IsSingleton) { bytesWriten += this.CompressSingleton(index); } else if (this.globcntRangeList[index].StartGLOBCNT < this.globcntRangeList[index].EndGLOBCNT) { bytesWriten += this.CompressRange(index); } return bytesWriten; } /// <summary> /// Compresses GLOBCNTRanges to the stream. /// </summary> /// <param name="startIndex">The start index.</param> /// <param name="endIndex">The end index.</param> /// <returns>The count of bytes have been wrote to the stream.</returns> private int Compress(int startIndex, int endIndex) { int bytesWriten = 0; bool pushed = false; this.Verify(this.stack.Bytes < 6); if (startIndex > this.globcntRangeList.Count) { this.Verify(false); } if (startIndex == endIndex) { this.Compress(startIndex); } else if (startIndex > endIndex) { AdapterHelper.Site.Assert.Fail(string.Format("The value of parameter 'startIndex'({0}) is bigger than the value of parameter 'endIndex'({1}).", startIndex, endIndex)); } else if (startIndex < endIndex) { int firstDiffIndex; byte[] commonBytes = this.HighOrderCommonBytes( startIndex, endIndex, this.stack.Bytes, out firstDiffIndex); if (commonBytes.Length == 6 - this.stack.Bytes) { // Two or more ranges have same bytes. this.Verify(false); } else if (commonBytes.Length == 0) { if (this.stack.Bytes == 5) { // Stack already has 5 bytes, ranges have different last byte. bytesWriten += this.CompressLastByte(startIndex, endIndex); } else if ((endIndex + 1) != firstDiffIndex) { // Divide current ranges. // Ranges' subset have same bytes. bytesWriten += this.Compress(startIndex, firstDiffIndex - 1); if (firstDiffIndex <= endIndex) { bytesWriten += this.Compress(firstDiffIndex, endIndex); } } else { // The first range's same bytes are different with others. bytesWriten += this.CompressSingleton(startIndex); startIndex++; if (startIndex <= endIndex) { bytesWriten += this.Compress(startIndex, endIndex); } } } else { // FirstDiffIndex < endIndex. this.stack.Push(commonBytes); bytesWriten += this.Push(this.stream, commonBytes); pushed = true; if (this.stack.Bytes == 5) { bytesWriten += this.CompressLastByte(startIndex, endIndex); this.stack.Pop(); bytesWriten += this.Pop(this.stream); return bytesWriten; } bytesWriten += this.Compress(startIndex, firstDiffIndex - 1); if (firstDiffIndex <= endIndex) { bytesWriten += this.Compress(firstDiffIndex, endIndex); } } } if (pushed) { this.stack.Pop(); bytesWriten += this.Pop(this.stream); } return bytesWriten; } /// <summary> /// Deserializes a GLOBCNTRange from a range command. /// </summary> /// <param name="comonBytes">The common bytes in the common byte stack.</param> /// <param name="lowBytes">The lowValue of the range command.</param> /// <param name="highBytes">The highValue of the range command.</param> /// <returns>A GLOBCNTRange.</returns> private GLOBCNTRange FromRange( byte[] comonBytes, byte[] lowBytes, byte[] highBytes) { this.Verify(comonBytes.Length + lowBytes.Length == 6 && lowBytes.Length == highBytes.Length); byte[] lowBuffer = new byte[6]; byte[] highBuffer = new byte[6]; Array.Copy(comonBytes, lowBuffer, comonBytes.Length); Array.Copy(lowBytes, 0, lowBuffer, comonBytes.Length, lowBytes.Length); Array.Copy(comonBytes, highBuffer, comonBytes.Length); Array.Copy(highBytes, 0, highBuffer, comonBytes.Length, highBytes.Length); return new GLOBCNTRange( StructureSerializer.Deserialize<GLOBCNT>(lowBuffer), StructureSerializer.Deserialize<GLOBCNT>(highBuffer)); } /// <summary> /// Deserializes a list of GLOBCNTRanges from a bitmask command. /// </summary> /// <param name="commonBytes">The common bytes in the common byte stack.</param> /// <param name="startValue">The startValue of the bitmask command.</param> /// <param name="bitmask">The bitmaskValue of the bitmask command.</param> /// <returns>A list of GLOBCNTRanges.</returns> private List<GLOBCNTRange> FromBitmask( byte[] commonBytes, byte startValue, byte bitmask) { int bitIndex = 0; List<GLOBCNTRange> ranges = new List<GLOBCNTRange>(); this.Verify(commonBytes.Length == 5); byte[] buffer = new byte[6]; Array.Copy(commonBytes, buffer, 5); buffer[5] = startValue; byte start = startValue; GLOBCNT cnt1 = StructureSerializer.Deserialize<GLOBCNT>(buffer); GLOBCNT cnt2; do { if (((1 << bitIndex) & bitmask) == 0) { // Use previous bitmask. // ==bitIndex + 1 -1; start = (byte)bitIndex; start = checked((byte)(start + startValue)); buffer[5] = start; cnt2 = StructureSerializer.Deserialize<GLOBCNT>(buffer); ranges.Add(new GLOBCNTRange(cnt1, cnt2)); bitIndex++; while (bitIndex < 8 && ((1 << bitIndex) & bitmask) == 0) { bitIndex++; } if (bitIndex == 8) { break; } else { start = (byte)(bitIndex + 1); start = checked((byte)(start + startValue)); buffer[5] = start; cnt1 = StructureSerializer.Deserialize<GLOBCNT>(buffer); bitIndex++; } } else { bitIndex++; } } while (bitIndex < 8); if (((1 << 7) & bitmask) != 0) { start = (byte)8; start = checked((byte)(8 + startValue)); buffer[5] = start; cnt2 = StructureSerializer.Deserialize<GLOBCNT>(buffer); ranges.Add(new GLOBCNTRange(cnt1, cnt2)); } return ranges; } /// <summary> /// Deserializes a GLOBCNTRange from a push command. /// </summary> /// <param name="comonBytes">The common bytes in the common byte stack.</param> /// <param name="pushedBytes">The bytes of the push command pushed.</param> /// <returns>A GLOBCNTRange.</returns> private GLOBCNTRange FromPush(byte[] comonBytes, byte[] pushedBytes) { this.Verify(pushedBytes.Length + comonBytes.Length == 6); byte[] pushedBuffer = new byte[6]; Array.Copy(comonBytes, pushedBuffer, comonBytes.Length); Array.Copy(pushedBytes, 0, pushedBuffer, comonBytes.Length, pushedBytes.Length); return new GLOBCNTRange( StructureSerializer.Deserialize<GLOBCNT>(pushedBuffer), StructureSerializer.Deserialize<GLOBCNT>(pushedBuffer)); } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microblog.Data; using Microblog.Models; using Microsoft.AspNetCore.Identity; using Microblog.Models.PostViewModels; using Microsoft.AspNetCore.Mvc.Rendering; namespace Microblog.Controllers { // ASP Core & EF conventions seem to do a lot of the CRUD work on the controller level instead of in a model. // https://docs.asp.net/en/latest/data/ef-mvc/crud.html public class PostsController : Controller { private readonly ApplicationDbContext _context; private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public PostsController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { _userManager = userManager; _signInManager = signInManager; _context = context; } // GET: Posts public async Task<IActionResult> Index() { // Get list of my posts. var user = await GetCurrentUserAsync(); return View(_context.Post. Include(p => p.PostInterests).ThenInclude(s => s.Interest). Where(m => m.User == user)); } // GET: Posts/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } // No lazy loading in EF7 yet, use eager loading by using Include manually. var post = await _context.Post. Include(u => u.User). Include(c => c.Comments).ThenInclude(ca => ca.User). Include(p => p.PostInterests).ThenInclude(s => s.Interest). SingleOrDefaultAsync(m => m.ID == id); if (post == null) { return NotFound(); } return View(post); } // GET: Posts/Create public IActionResult Create() { var interests = _context.Interest.OrderBy(c => c.Name).Select(x => new { Id = x.ID, Value = x.Name }); var model = new PostViewModel() { InterestsList = new SelectList(interests, "Id", "Value") }; return View(model); } // POST: Posts/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(PostViewModel postViewModel) { Post post = new Post(); if (ModelState.IsValid) { post.Title = postViewModel.Title; post.Content = postViewModel.Content; post.Public = postViewModel.Public; // Amazingly, entity framework automatically makes the translation from ApplicationUser to it's UserID. post.User = await GetCurrentUserAsync(); // Current DateTime on the machine (server). post.PostDate = DateTime.Now; // Generate excerpt of the content to show in the overview list. post.Excerpt = post.Content.Substring(0, (post.Content.Length < 144 ? post.Content.Length : 144)); _context.Add(post); await _context.SaveChangesAsync(); foreach (var i in postViewModel.InterestIds) { var pi = new PostInterests { InterestId = i, PostId = post.ID }; _context.PostInterests.Add(pi); } await _context.SaveChangesAsync(); return RedirectToAction("Index"); } return View(post); } // GET: Posts/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var post = await _context.Post.SingleOrDefaultAsync(m => m.ID == id); if (post == null) { return NotFound(); } return View(post); } // POST: Posts/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("ID,Content,PostDate,Title")] Post post) { if (id != post.ID) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(post); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostExists(post.ID)) { return NotFound(); } else { throw; } } return RedirectToAction("Index"); } return View(post); } // GET: Posts/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var post = await _context.Post.SingleOrDefaultAsync(m => m.ID == id); if (post == null) { return NotFound(); } return View(post); } // POST: Posts/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var post = await _context.Post.SingleOrDefaultAsync(m => m.ID == id); _context.Comment.RemoveRange(_context.Comment.Where(p => p.Post == post)); // Remove comments first, to avoid FK constraint error. _context.Post.Remove(post); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } // POST: Posts/Toggle/5 [HttpPost, ActionName("Toggle")] [ValidateAntiForgeryToken] public async Task<IActionResult> Toggle(int id) { var post = await _context.Post.SingleOrDefaultAsync(m => m.ID == id); post.Public = !post.Public; await _context.SaveChangesAsync(); return RedirectToAction("Index"); } private bool PostExists(int id) { return _context.Post.Any(e => e.ID == id); } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } } }
#region License /* * WebSocketSessionManager.cs * * The MIT License * * Copyright (c) 2012-2014 sta.blockhead * * 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.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Timers; namespace WebSocketSharp.Server { /// <summary> /// Manages the sessions in a Websocket service. /// </summary> public class WebSocketSessionManager { #region Private Fields private volatile bool _clean; private object _forSweep; private Logger _logger; private Dictionary<string, IWebSocketSession> _sessions; private volatile ServerState _state; private volatile bool _sweeping; private System.Timers.Timer _sweepTimer; private object _sync; private TimeSpan _waitTime; #endregion #region Internal Constructors internal WebSocketSessionManager () : this (new Logger ()) { } internal WebSocketSessionManager (Logger logger) { _logger = logger; _clean = true; _forSweep = new object (); _sessions = new Dictionary<string, IWebSocketSession> (); _state = ServerState.Ready; _sync = ((ICollection) _sessions).SyncRoot; _waitTime = TimeSpan.FromSeconds (1); setSweepTimer (60000); } #endregion #region Internal Properties internal ServerState State { get { return _state; } } #endregion #region Public Properties /// <summary> /// Gets the IDs for the active sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;string&gt;</c> instance that provides an enumerator which /// supports the iteration over the collection of the IDs for the active sessions. /// </value> public IEnumerable<string> ActiveIDs { get { foreach (var res in Broadping (WebSocketFrame.EmptyUnmaskPingBytes, _waitTime)) if (res.Value) yield return res.Key; } } /// <summary> /// Gets the number of the sessions in the Websocket service. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of the sessions. /// </value> public int Count { get { lock (_sync) return _sessions.Count; } } /// <summary> /// Gets the IDs for the sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;string&gt;</c> instance that provides an enumerator which /// supports the iteration over the collection of the IDs for the sessions. /// </value> public IEnumerable<string> IDs { get { if (_state == ServerState.ShuttingDown) return new string[0]; lock (_sync) return _sessions.Keys.ToList (); } } /// <summary> /// Gets the IDs for the inactive sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;string&gt;</c> instance that provides an enumerator which /// supports the iteration over the collection of the IDs for the inactive sessions. /// </value> public IEnumerable<string> InactiveIDs { get { foreach (var res in Broadping (WebSocketFrame.EmptyUnmaskPingBytes, _waitTime)) if (!res.Value) yield return res.Key; } } /// <summary> /// Gets the session with the specified <paramref name="id"/>. /// </summary> /// <value> /// A <see cref="IWebSocketSession"/> instance that provides the access to /// the information in the session, or <see langword="null"/> if it's not found. /// </value> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> public IWebSocketSession this[string id] { get { IWebSocketSession session; TryGetSession (id, out session); return session; } } /// <summary> /// Gets a value indicating whether the manager cleans up the inactive sessions /// in the WebSocket service periodically. /// </summary> /// <value> /// <c>true</c> if the manager cleans up the inactive sessions every 60 seconds; /// otherwise, <c>false</c>. /// </value> public bool KeepClean { get { return _clean; } internal set { if (!(value ^ _clean)) return; _clean = value; if (_state == ServerState.Start) _sweepTimer.Enabled = value; } } /// <summary> /// Gets the sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;IWebSocketSession&gt;</c> instance that provides an enumerator /// which supports the iteration over the collection of the sessions in the service. /// </value> public IEnumerable<IWebSocketSession> Sessions { get { if (_state == ServerState.ShuttingDown) return new IWebSocketSession[0]; lock (_sync) return _sessions.Values.ToList (); } } /// <summary> /// Gets the wait time for the response to the WebSocket Ping or Close. /// </summary> /// <value> /// A <see cref="TimeSpan"/> that represents the wait time. /// </value> public TimeSpan WaitTime { get { return _waitTime; } internal set { if (value == _waitTime) return; _waitTime = value; foreach (var session in Sessions) session.Context.WebSocket.WaitTime = value; } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte[] data, Action completed) { var cache = new Dictionary<CompressionMethod, byte[]> (); try { Broadcast (opcode, data, cache); if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { cache.Clear (); } } private void broadcast (Opcode opcode, Stream stream, Action completed) { var cache = new Dictionary <CompressionMethod, Stream> (); try { Broadcast (opcode, stream, cache); if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { foreach (var cached in cache.Values) cached.Dispose (); cache.Clear (); } } private void broadcastAsync (Opcode opcode, byte[] data, Action completed) { ThreadPool.QueueUserWorkItem (state => broadcast (opcode, data, completed)); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { ThreadPool.QueueUserWorkItem (state => broadcast (opcode, stream, completed)); } private static string createID () { return Guid.NewGuid ().ToString ("N"); } private void setSweepTimer (double interval) { _sweepTimer = new System.Timers.Timer (interval); _sweepTimer.Elapsed += (sender, e) => Sweep (); } private bool tryGetSession (string id, out IWebSocketSession session) { bool res; lock (_sync) res = _sessions.TryGetValue (id, out session); if (!res) _logger.Error ("A session with the specified ID isn't found.\nID: " + id); return res; } #endregion #region Internal Methods internal string Add (IWebSocketSession session) { lock (_sync) { if (_state != ServerState.Start) return null; var id = createID (); _sessions.Add (id, session); return id; } } internal void Broadcast ( Opcode opcode, byte[] data, Dictionary<CompressionMethod, byte[]> cache) { foreach (var session in Sessions) { if (_state != ServerState.Start) break; session.Context.WebSocket.Send (opcode, data, cache); } } internal void Broadcast ( Opcode opcode, Stream stream, Dictionary <CompressionMethod, Stream> cache) { foreach (var session in Sessions) { if (_state != ServerState.Start) break; session.Context.WebSocket.Send (opcode, stream, cache); } } internal Dictionary<string, bool> Broadping (byte[] frameAsBytes, TimeSpan timeout) { var res = new Dictionary<string, bool> (); foreach (var session in Sessions) { if (_state != ServerState.Start) break; res.Add (session.ID, session.Context.WebSocket.Ping (frameAsBytes, timeout)); } return res; } internal bool Remove (string id) { lock (_sync) return _sessions.Remove (id); } internal void Start () { lock (_sync) { _sweepTimer.Enabled = _clean; _state = ServerState.Start; } } internal void Stop (CloseEventArgs e, byte[] frameAsBytes, TimeSpan timeout) { lock (_sync) { _state = ServerState.ShuttingDown; _sweepTimer.Enabled = false; foreach (var session in _sessions.Values.ToList ()) session.Context.WebSocket.Close (e, frameAsBytes, timeout); _state = ServerState.Stop; } } #endregion #region Public Methods /// <summary> /// Broadcasts a binary <paramref name="data"/> to every client in the WebSocket service. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to broadcast. /// </param> public void Broadcast (byte[] data) { var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, null); else broadcast (Opcode.Binary, new MemoryStream (data), null); } /// <summary> /// Broadcasts a text <paramref name="data"/> to every client in the WebSocket service. /// </summary> /// <param name="data"> /// A <see cref="string"/> that represents the text data to broadcast. /// </param> public void Broadcast (string data) { var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } var rawData = Encoding.UTF8.GetBytes (data); if (rawData.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Text, rawData, null); else broadcast (Opcode.Text, new MemoryStream (rawData), null); } /// <summary> /// Broadcasts a binary <paramref name="data"/> asynchronously to every client /// in the WebSocket service. /// </summary> /// <remarks> /// This method doesn't wait for the broadcast to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to broadcast. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the broadcast is complete. /// </param> public void BroadcastAsync (byte[] data, Action completed) { var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, data, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (data), completed); } /// <summary> /// Broadcasts a text <paramref name="data"/> asynchronously to every client /// in the WebSocket service. /// </summary> /// <remarks> /// This method doesn't wait for the broadcast to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to broadcast. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the broadcast is complete. /// </param> public void BroadcastAsync (string data, Action completed) { var msg = _state.CheckIfStart () ?? data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } var rawData = Encoding.UTF8.GetBytes (data); if (rawData.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Text, rawData, completed); else broadcastAsync (Opcode.Text, new MemoryStream (rawData), completed); } /// <summary> /// Broadcasts a binary data from the specified <see cref="Stream"/> asynchronously /// to every client in the WebSocket service. /// </summary> /// <remarks> /// This method doesn't wait for the broadcast to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to broadcast. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to broadcast. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the broadcast is complete. /// </param> public void BroadcastAsync (Stream stream, int length, Action completed) { var msg = _state.CheckIfStart () ?? stream.CheckIfCanRead () ?? (length < 1 ? "'length' is less than 1." : null); if (msg != null) { _logger.Error (msg); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("The data cannot be read from 'stream'."); return; } if (len < length) _logger.Warn ( String.Format ( "The data with 'length' cannot be read from 'stream'.\nexpected: {0} actual: {1}", length, len)); if (len <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, completed); else broadcast (Opcode.Binary, new MemoryStream (data), completed); }, ex => _logger.Fatal (ex.ToString ())); } /// <summary> /// Sends a Ping to every client in the WebSocket service. /// </summary> /// <returns> /// A <c>Dictionary&lt;string, bool&gt;</c> that contains a collection of pairs of /// a session ID and a value indicating whether the manager received a Pong from /// each client in a time. /// </returns> public Dictionary<string, bool> Broadping () { var msg = _state.CheckIfStart (); if (msg != null) { _logger.Error (msg); return null; } return Broadping (WebSocketFrame.EmptyUnmaskPingBytes, _waitTime); } /// <summary> /// Sends a Ping with the specified <paramref name="message"/> to every client /// in the WebSocket service. /// </summary> /// <returns> /// A <c>Dictionary&lt;string, bool&gt;</c> that contains a collection of pairs of /// a session ID and a value indicating whether the manager received a Pong from /// each client in a time. /// </returns> /// <param name="message"> /// A <see cref="string"/> that represents the message to send. /// </param> public Dictionary<string, bool> Broadping (string message) { if (message == null || message.Length == 0) return Broadping (); byte[] data = null; var msg = _state.CheckIfStart () ?? (data = Encoding.UTF8.GetBytes (message)).CheckIfValidControlData ("message"); if (msg != null) { _logger.Error (msg); return null; } return Broadping (WebSocketFrame.CreatePingFrame (data, false).ToByteArray (), _waitTime); } /// <summary> /// Closes the session with the specified <paramref name="id"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to close. /// </param> public void CloseSession (string id) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (); } /// <summary> /// Closes the session with the specified <paramref name="id"/>, <paramref name="code"/>, /// and <paramref name="reason"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to close. /// </param> /// <param name="code"> /// A <see cref="ushort"/> that represents the status code indicating the reason for the close. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the close. /// </param> public void CloseSession (string id, ushort code, string reason) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (code, reason); } /// <summary> /// Closes the session with the specified <paramref name="id"/>, <paramref name="code"/>, /// and <paramref name="reason"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to close. /// </param> /// <param name="code"> /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code /// indicating the reason for the close. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the close. /// </param> public void CloseSession (string id, CloseStatusCode code, string reason) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (code, reason); } /// <summary> /// Sends a Ping to the client on the session with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the manager receives a Pong from the client in a time; /// otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> public bool PingTo (string id) { IWebSocketSession session; return TryGetSession (id, out session) && session.Context.WebSocket.Ping (); } /// <summary> /// Sends a Ping with the specified <paramref name="message"/> to the client /// on the session with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the manager receives a Pong from the client in a time; /// otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="message"> /// A <see cref="string"/> that represents the message to send. /// </param> public bool PingTo (string id, string message) { IWebSocketSession session; return TryGetSession (id, out session) && session.Context.WebSocket.Ping (message); } /// <summary> /// Sends a binary <paramref name="data"/> to the client on the session /// with the specified <paramref name="id"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> public void SendTo (string id, byte[] data) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Send (data); } /// <summary> /// Sends a text <paramref name="data"/> to the client on the session /// with the specified <paramref name="id"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> public void SendTo (string id, string data) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Send (data); } /// <summary> /// Sends a binary <paramref name="data"/> asynchronously to the client on the session /// with the specified <paramref name="id"/>. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="completed"> /// An <c>Action&lt;bool&gt;</c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendToAsync (string id, byte[] data, Action<bool> completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (data, completed); } /// <summary> /// Sends a text <paramref name="data"/> asynchronously to the client on the session /// with the specified <paramref name="id"/>. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="completed"> /// An <c>Action&lt;bool&gt;</c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendToAsync (string id, string data, Action<bool> completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (data, completed); } /// <summary> /// Sends a binary data from the specified <see cref="Stream"/> asynchronously /// to the client on the session with the specified <paramref name="id"/>. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="completed"> /// An <c>Action&lt;bool&gt;</c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendToAsync (string id, Stream stream, int length, Action<bool> completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (stream, length, completed); } /// <summary> /// Cleans up the inactive sessions in the WebSocket service. /// </summary> public void Sweep () { if (_state != ServerState.Start || _sweeping || Count == 0) return; lock (_forSweep) { _sweeping = true; foreach (var id in InactiveIDs) { if (_state != ServerState.Start) break; lock (_sync) { IWebSocketSession session; if (_sessions.TryGetValue (id, out session)) { var state = session.State; if (state == WebSocketState.Open) session.Context.WebSocket.Close (CloseStatusCode.Abnormal); else if (state == WebSocketState.Closing) continue; else _sessions.Remove (id); } } } _sweeping = false; } } /// <summary> /// Tries to get the session with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the session is successfully found; otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="session"> /// When this method returns, a <see cref="IWebSocketSession"/> instance that /// provides the access to the information in the session, or <see langword="null"/> /// if it's not found. This parameter is passed uninitialized. /// </param> public bool TryGetSession (string id, out IWebSocketSession session) { var msg = _state.CheckIfStart () ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); session = null; return false; } return tryGetSession (id, out session); } #endregion } }
using System; using System.Data; using PCSComUtils.PCSExc; using PCSComUtils.Common; using PCSComUtils.Framework.TableFrame.DS; namespace PCSComUtils.Framework.TableFrame.BO { public class TableGroupBO { private const string THIS = "PCSComUtils.Framework.TableFrame.BO.ITableGroupBO"; public TableGroupBO() { } /// <Description> /// This method checks business rule and call Add() method of DS class /// </Description> /// <Inputs> /// Value object /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void AddGroup(object pobjObjectVO) { const string METHOD_NAME = THIS + ".AddGroup()"; try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); dsTableGroup.Add(pobjObjectVO); } catch(PCSDBException ex) { throw ex; } catch (System.Runtime.InteropServices.COMException ex) { throw new PCSBOException(ErrorCode.MESSAGE_COM_TRANSACTION,METHOD_NAME,ex); } catch (Exception ex) { throw ex; } } /// <Description> /// This method checks business rule and call Add() method of DS class /// </Description> /// <Inputs> /// Value object /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public int AddGroupAndReturnMaxID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".AddGroup()"; try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); return dsTableGroup.AddAndReturnMaxID(pobjObjectVO); } catch(PCSDBException ex) { throw ex; } catch (System.Runtime.InteropServices.COMException ex) { throw new PCSBOException(ErrorCode.MESSAGE_COM_TRANSACTION,METHOD_NAME,ex); } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID,string VOclass) { const string METHOD_NAME = THIS + ".GetObjectVO()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME,new Exception()); } //************************************************************************** /// <Description> /// This method not implements yet /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(object pObjectVO) { const string METHOD_NAME = THIS + ".Delete()"; throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME,new Exception()); } //************************************************************************** /// <Description> /// This method checks business rule and call Delete() method of DS class /// </Description> /// <Inputs> /// pintID /// </Inputs> /// <Outputs> /// Delete a record from Database /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); dsTableGroup.Delete(pintID); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get data /// </Description> /// <Inputs> /// pintID /// </Inputs> /// <Outputs> /// Value object /// </Outputs> /// <Returns> /// object /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); return dsTableGroup.GetObjectVO(pintID); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to update data /// </Description> /// <Inputs> /// pobjObjecVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateGroup(object pobjObjecVO) { const string METHOD_NAME = THIS + ".UpdateGroup()"; try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); dsTableGroup.Update(pobjObjecVO); } catch(PCSDBException ex) { throw ex; } catch (System.Runtime.InteropServices.COMException ex) { throw new PCSBOException(ErrorCode.MESSAGE_COM_TRANSACTION,METHOD_NAME,ex); } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get all data /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); return dsTableGroup.List(); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// N/A /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 13-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); dsTableGroup.UpdateDataSet(pData); } catch(PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get a row in sys_tablegroup /// </Description> /// <Inputs> /// GroupID /// </Inputs> /// <Outputs> /// object sys_TableGroupVO /// </Outputs> /// <Returns> /// object /// </Returns> /// <Authors> /// NgocHT /// </Authors> /// <History> /// 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object ReturnTableGroup(int pintGroupID) { try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); return dsTableGroup.GetObjectVO(pintGroupID); } catch (PCSDBException ex) { throw ex; } catch (Exception ex) { throw ex; } } //************************************************************************** /// <Description> /// This method uses to get the order of row in sys_tablegroup /// </Description> /// <Inputs> /// N/A /// </Inputs> /// <Outputs> /// the order of group /// </Outputs> /// <Returns> /// int /// </Returns> /// <Authors> /// NgocHT /// </Authors> /// <History> /// 28-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public int ReturnGroupOrder() { try { sys_TableGroupDS dsTableGroup = new sys_TableGroupDS(); return dsTableGroup.MaxGroupOrder(); } catch (PCSDBException ex) { throw (ex); } catch (Exception ex) { throw ex; } } #region IObjectBO Members public void Add(object pObjectDetail) { // TODO: Add TableGroupBO.Add implementation } public void Update(object pObjectDetail) { // TODO: Add TableGroupBO.Update implementation } #endregion } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function initializeMeshRoadEditor() { echo(" % - Initializing Mesh Road Editor"); exec( "./meshRoadEditor.cs" ); exec( "./meshRoadEditorGui.gui" ); exec( "./meshRoadEditorToolbar.gui"); exec( "./meshRoadEditorGui.cs" ); MeshRoadEditorGui.setVisible( false ); MeshRoadEditorOptionsWindow.setVisible( false ); MeshRoadEditorToolbar.setVisible( false ); MeshRoadEditorTreeWindow.setVisible( false ); EditorGui.add( MeshRoadEditorGui ); EditorGui.add( MeshRoadEditorOptionsWindow ); EditorGui.add( MeshRoadEditorToolbar ); EditorGui.add( MeshRoadEditorTreeWindow ); new ScriptObject( MeshRoadEditorPlugin ) { superClass = "EditorPlugin"; editorGui = MeshRoadEditorGui; }; %map = new ActionMap(); %map.bindCmd( keyboard, "backspace", "MeshRoadEditorGui.deleteNode();", "" ); %map.bindCmd( keyboard, "1", "MeshRoadEditorGui.prepSelectionMode();", "" ); %map.bindCmd( keyboard, "2", "ToolsPaletteArray->MeshRoadEditorMoveMode.performClick();", "" ); %map.bindCmd( keyboard, "3", "ToolsPaletteArray->MeshRoadEditorRotateMode.performClick();", "" ); %map.bindCmd( keyboard, "4", "ToolsPaletteArray->MeshRoadEditorScaleMode.performClick();", "" ); %map.bindCmd( keyboard, "5", "ToolsPaletteArray->MeshRoadEditorAddRoadMode.performClick();", "" ); %map.bindCmd( keyboard, "=", "ToolsPaletteArray->MeshRoadEditorInsertPointMode.performClick();", "" ); %map.bindCmd( keyboard, "numpadadd", "ToolsPaletteArray->MeshRoadEditorInsertPointMode.performClick();", "" ); %map.bindCmd( keyboard, "-", "ToolsPaletteArray->MeshRoadEditorRemovePointMode.performClick();", "" ); %map.bindCmd( keyboard, "numpadminus", "ToolsPaletteArray->MeshRoadEditorRemovePointMode.performClick();", "" ); %map.bindCmd( keyboard, "z", "MeshRoadEditorShowSplineBtn.performClick();", "" ); %map.bindCmd( keyboard, "x", "MeshRoadEditorWireframeBtn.performClick();", "" ); %map.bindCmd( keyboard, "v", "MeshRoadEditorShowRoadBtn.performClick();", "" ); MeshRoadEditorPlugin.map = %map; MeshRoadEditorPlugin.initSettings(); } function destroyMeshRoadEditor() { } function MeshRoadEditorPlugin::onWorldEditorStartup( %this ) { // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu( "Mesh Road Editor", "", MeshRoadEditorPlugin ); // Add ourselves to the ToolsToolbar %tooltip = "Mesh Road Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar( "MeshRoadEditorPlugin", "MeshRoadEditorPalette", expandFilename("tools/worldEditor/images/toolbar/mesh-road-editor"), %tooltip ); //connect editor windows GuiWindowCtrl::attach( MeshRoadEditorOptionsWindow, MeshRoadEditorTreeWindow); // Add ourselves to the Editor Settings window exec( "./meshRoadEditorSettingsTab.gui" ); ESettingsWindow.addTabPage( EMeshRoadEditorSettingsPage ); } function MeshRoadEditorPlugin::onActivated( %this ) { %this.readSettings(); ToolsPaletteArray->MeshRoadEditorAddRoadMode.performClick(); EditorGui.bringToFront( MeshRoadEditorGui ); MeshRoadEditorGui.setVisible( true ); MeshRoadEditorGui.makeFirstResponder( true ); MeshRoadEditorOptionsWindow.setVisible( true ); MeshRoadEditorToolbar.setVisible( true ); MeshRoadEditorTreeWindow.setVisible( true ); MeshRoadTreeView.open(ServerMeshRoadSet,true); %this.map.push(); // Store this on a dynamic field // in order to restore whatever setting // the user had before. %this.prevGizmoAlignment = GlobalGizmoProfile.alignment; // The DecalEditor always uses Object alignment. GlobalGizmoProfile.alignment = "Object"; // Set the status bar here until all tool have been hooked up EditorGuiStatusBar.setInfo("Mesh road editor."); EditorGuiStatusBar.setSelection(""); Parent::onActivated(%this); } function MeshRoadEditorPlugin::onDeactivated( %this ) { %this.writeSettings(); MeshRoadEditorGui.setVisible( false ); MeshRoadEditorOptionsWindow.setVisible( false ); MeshRoadEditorToolbar.setVisible( false ); MeshRoadEditorTreeWindow.setVisible( false ); %this.map.pop(); // Restore the previous Gizmo // alignment settings. GlobalGizmoProfile.alignment = %this.prevGizmoAlignment; Parent::onDeactivated(%this); } function MeshRoadEditorPlugin::onEditMenuSelect( %this, %editMenu ) { %hasSelection = false; if( isObject( MeshRoadEditorGui.road ) ) %hasSelection = true; %editMenu.enableItem( 3, false ); // Cut %editMenu.enableItem( 4, false ); // Copy %editMenu.enableItem( 5, false ); // Paste %editMenu.enableItem( 6, %hasSelection ); // Delete %editMenu.enableItem( 8, false ); // Deselect } function MeshRoadEditorPlugin::handleDelete( %this ) { MeshRoadEditorGui.deleteNode(); } function MeshRoadEditorPlugin::handleEscape( %this ) { return MeshRoadEditorGui.onEscapePressed(); } function MeshRoadEditorPlugin::isDirty( %this ) { return MeshRoadEditorGui.isDirty; } function MeshRoadEditorPlugin::onSaveMission( %this, %missionFile ) { if( MeshRoadEditorGui.isDirty ) { $MissionGroup.save( %missionFile ); MeshRoadEditorGui.isDirty = false; } } //----------------------------------------------------------------------------- // Settings //----------------------------------------------------------------------------- function MeshRoadEditorPlugin::initSettings( %this ) { EditorSettings.beginGroup( "MeshRoadEditor", true ); EditorSettings.setDefaultValue( "DefaultWidth", "10" ); EditorSettings.setDefaultValue( "DefaultDepth", "5" ); EditorSettings.setDefaultValue( "DefaultNormal", "0 0 1" ); EditorSettings.setDefaultValue( "HoverSplineColor", "255 0 0 255" ); EditorSettings.setDefaultValue( "SelectedSplineColor", "0 255 0 255" ); EditorSettings.setDefaultValue( "HoverNodeColor", "255 255 255 255" ); //<-- Not currently used EditorSettings.setDefaultValue( "TopMaterialName", "DefaultRoadMaterialTop" ); EditorSettings.setDefaultValue( "BottomMaterialName", "DefaultRoadMaterialOther" ); EditorSettings.setDefaultValue( "SideMaterialName", "DefaultRoadMaterialOther" ); EditorSettings.endGroup(); } function MeshRoadEditorPlugin::readSettings( %this ) { EditorSettings.beginGroup( "MeshRoadEditor", true ); MeshRoadEditorGui.DefaultWidth = EditorSettings.value("DefaultWidth"); MeshRoadEditorGui.DefaultDepth = EditorSettings.value("DefaultDepth"); MeshRoadEditorGui.DefaultNormal = EditorSettings.value("DefaultNormal"); MeshRoadEditorGui.HoverSplineColor = EditorSettings.value("HoverSplineColor"); MeshRoadEditorGui.SelectedSplineColor = EditorSettings.value("SelectedSplineColor"); MeshRoadEditorGui.HoverNodeColor = EditorSettings.value("HoverNodeColor"); MeshRoadEditorGui.topMaterialName = EditorSettings.value("TopMaterialName"); MeshRoadEditorGui.bottomMaterialName = EditorSettings.value("BottomMaterialName"); MeshRoadEditorGui.sideMaterialName = EditorSettings.value("SideMaterialName"); EditorSettings.endGroup(); } function MeshRoadEditorPlugin::writeSettings( %this ) { EditorSettings.beginGroup( "MeshRoadEditor", true ); EditorSettings.setValue( "DefaultWidth", MeshRoadEditorGui.DefaultWidth ); EditorSettings.setValue( "DefaultDepth", MeshRoadEditorGui.DefaultDepth ); EditorSettings.setValue( "DefaultNormal", MeshRoadEditorGui.DefaultNormal ); EditorSettings.setValue( "HoverSplineColor", MeshRoadEditorGui.HoverSplineColor ); EditorSettings.setValue( "SelectedSplineColor", MeshRoadEditorGui.SelectedSplineColor ); EditorSettings.setValue( "HoverNodeColor", MeshRoadEditorGui.HoverNodeColor ); EditorSettings.setValue( "TopMaterialName", MeshRoadEditorGui.topMaterialName ); EditorSettings.setValue( "BottomMaterialName", MeshRoadEditorGui.bottomMaterialName ); EditorSettings.setValue( "SideMaterialName", MeshRoadEditorGui.sideMaterialName ); EditorSettings.endGroup(); }
// 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.Diagnostics.Contracts; using System.Globalization; using System.Text; namespace System.Net.Http.Headers { public class WarningHeaderValue : ICloneable { private int _code; private string _agent; private string _text; private DateTimeOffset? _date; public int Code { get { return _code; } } public string Agent { get { return _agent; } } public string Text { get { return _text; } } public DateTimeOffset? Date { get { return _date; } } public WarningHeaderValue(int code, string agent, string text) { CheckCode(code); CheckAgent(agent); HeaderUtilities.CheckValidQuotedString(text, "text"); _code = code; _agent = agent; _text = text; } public WarningHeaderValue(int code, string agent, string text, DateTimeOffset date) { CheckCode(code); CheckAgent(agent); HeaderUtilities.CheckValidQuotedString(text, "text"); _code = code; _agent = agent; _text = text; _date = date; } private WarningHeaderValue() { } private WarningHeaderValue(WarningHeaderValue source) { Contract.Requires(source != null); _code = source._code; _agent = source._agent; _text = source._text; _date = source._date; } public override string ToString() { StringBuilder sb = new StringBuilder(); // Warning codes are always 3 digits according to RFC2616 sb.Append(_code.ToString("000", NumberFormatInfo.InvariantInfo)); sb.Append(' '); sb.Append(_agent); sb.Append(' '); sb.Append(_text); if (_date.HasValue) { sb.Append(" \""); sb.Append(HttpRuleParser.DateToString(_date.Value)); sb.Append('\"'); } return sb.ToString(); } public override bool Equals(object obj) { WarningHeaderValue other = obj as WarningHeaderValue; if (other == null) { return false; } // 'agent' is a host/token, i.e. use case-insensitive comparison. Use case-sensitive comparison for 'text' // since it is a quoted string. if ((_code != other._code) || (!string.Equals(_agent, other._agent, StringComparison.OrdinalIgnoreCase)) || (!string.Equals(_text, other._text, StringComparison.Ordinal))) { return false; } // We have a date set. Verify 'other' has also a date that matches our value. if (_date.HasValue) { return other._date.HasValue && (_date.Value == other._date.Value); } // We don't have a date. If 'other' has a date, we're not equal. return !other._date.HasValue; } public override int GetHashCode() { int result = _code.GetHashCode() ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_agent) ^ _text.GetHashCode(); if (_date.HasValue) { result = result ^ _date.Value.GetHashCode(); } return result; } public static WarningHeaderValue Parse(string input) { int index = 0; return (WarningHeaderValue)GenericHeaderParser.SingleValueWarningParser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out WarningHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueWarningParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (WarningHeaderValue)output; return true; } return false; } internal static int GetWarningLength(string input, int startIndex, out object parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Read <code> in '<code> <agent> <text> ["<date>"]' int code; int current = startIndex; if (!TryReadCode(input, ref current, out code)) { return 0; } // Read <agent> in '<code> <agent> <text> ["<date>"]' string agent; if (!TryReadAgent(input, current, ref current, out agent)) { return 0; } // Read <text> in '<code> <agent> <text> ["<date>"]' int textLength = 0; int textStartIndex = current; if (HttpRuleParser.GetQuotedStringLength(input, current, out textLength) != HttpParseResult.Parsed) { return 0; } current = current + textLength; // Read <date> in '<code> <agent> <text> ["<date>"]' DateTimeOffset? date = null; if (!TryReadDate(input, ref current, out date)) { return 0; } WarningHeaderValue result = new WarningHeaderValue(); result._code = code; result._agent = agent; result._text = input.Substring(textStartIndex, textLength); result._date = date; parsedValue = result; return current - startIndex; } private static bool TryReadAgent(string input, int startIndex, ref int current, out string agent) { agent = null; int agentLength = HttpRuleParser.GetHostLength(input, startIndex, true, out agent); if (agentLength == 0) { return false; } current = current + agentLength; int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); current = current + whitespaceLength; // At least one whitespace required after <agent>. Also make sure we have characters left for <text> if ((whitespaceLength == 0) || (current == input.Length)) { return false; } return true; } private static bool TryReadCode(string input, ref int current, out int code) { code = 0; int codeLength = HttpRuleParser.GetNumberLength(input, current, false); // code must be a 3 digit value. We accept less digits, but we don't accept more. if ((codeLength == 0) || (codeLength > 3)) { return false; } if (!HeaderUtilities.TryParseInt32(input.Substring(current, codeLength), out code)) { Debug.Assert(false, "Unable to parse value even though it was parsed as <=3 digits string. Input: '" + input + "', Current: " + current + ", CodeLength: " + codeLength); return false; } current = current + codeLength; int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); current = current + whitespaceLength; // Make sure the number is followed by at least one whitespace and that we have characters left to parse. if ((whitespaceLength == 0) || (current == input.Length)) { return false; } return true; } private static bool TryReadDate(string input, ref int current, out DateTimeOffset? date) { date = null; // Make sure we have at least one whitespace between <text> and <date> (if we have <date>) int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current); current = current + whitespaceLength; // Read <date> in '<code> <agent> <text> ["<date>"]' if ((current < input.Length) && (input[current] == '"')) { if (whitespaceLength == 0) { return false; // we have characters after <text> but they were not separated by a whitespace } current++; // skip opening '"' // Find the closing '"' int dateStartIndex = current; while (current < input.Length) { if (input[current] == '"') { break; } current++; } if ((current == input.Length) || (current == dateStartIndex)) { return false; // we couldn't find the closing '"' or we have an empty quoted string. } DateTimeOffset temp; if (!HttpRuleParser.TryStringToDate(input.Substring(dateStartIndex, current - dateStartIndex), out temp)) { return false; } date = temp; current++; // skip closing '"' current = current + HttpRuleParser.GetWhitespaceLength(input, current); } return true; } object ICloneable.Clone() { return new WarningHeaderValue(this); } private static void CheckCode(int code) { if ((code < 0) || (code > 999)) { throw new ArgumentOutOfRangeException("code"); } } private static void CheckAgent(string agent) { if (string.IsNullOrEmpty(agent)) { throw new ArgumentException(SR.net_http_argument_empty_string, "agent"); } // 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value // is a valid host. string host = null; if (HttpRuleParser.GetHostLength(agent, 0, true, out host) != agent.Length) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, agent)); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #define COMPILED_QUERIES using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.EntityClient; using System.Data.Objects; // for compiled queries using System.Data.SqlClient; using System.Data.SqlServerCe; using System.IO; using System.Linq; using System.Reflection; namespace Microsoft.Research.CodeAnalysis { abstract class SQLCacheDataAccessor : ICacheDataAccessor { private readonly int MaxCacheSize; // the maximum number of method for which warnings are stored. protected EntityConnection connection; // We keep the connection open so that we do not reload all the SQLce engine protected ClousotCacheEntities objectContext; private Dictionary<string, byte[]> metadataIfCreation; private readonly Func<ClousotCacheEntities, byte[], MethodModel> compiledGetMethod; private readonly Func<ClousotCacheEntities, long, Guid, bool> compiledGetBinding; private readonly Func<ClousotCacheEntities, int> compiledNbToDelete; protected SQLCacheDataAccessor(Dictionary<string, byte[]> metadataIfCreation, int maxCacheSize, CacheVersionParameters cacheVersionParameters, string[] EntityConnectionMetadataPaths) { this.metadataIfCreation = metadataIfCreation; this.MaxCacheSize = maxCacheSize; this.EntityConnectionMetadataPaths = EntityConnectionMetadataPaths; this.cacheVersion = cacheVersionParameters; #if COMPILED_QUERIES this.compiledGetMethod = CompiledQuery.Compile<ClousotCacheEntities, byte[], MethodModel>( (context, hash) => context.MethodModels.FirstOrDefault(m => m.Hash == hash)); this.compiledGetBinding = CompiledQuery.Compile<ClousotCacheEntities, long, Guid, bool>( (context, methodid, guid) => context.AssemblyBindings.Any(b => b.MethodId == methodid && b.AssemblyId == guid)); this.compiledNbToDelete = CompiledQuery.Compile<ClousotCacheEntities, int>( context => context.MethodModels.Count() - this.MaxCacheSize); #else this.compiledGetMethod = (context, hash) => context.MethodModels.FirstOrDefault(m => m.Hash == hash); this.compiledGetBinding = (context, methodid, guid) => context.AssemblyBindings.Any(b => b.MethodId == methodid && b.AssemblyId == guid); this.compiledNbToDelete = (context) => context.MethodModels.Count() - this.MaxCacheSize; #endif } private readonly CacheVersionParameters cacheVersion; protected string currentAssembly; protected Guid currentAssemblyGuid; public bool IsValid { get { return this.connection != null; } } public virtual long GetNewId() { return default(long); } abstract protected bool DatabaseExist(out DbConnection dbConnection); abstract protected DbConnection CreateDatabase(); abstract protected string TablesCreationQueries { get; } protected readonly string[] EntityConnectionMetadataPaths; static private readonly Assembly[] EntityConnectionMetadataAssembliesToConsider = new Assembly[]{Assembly.GetExecutingAssembly()}; private EntityConnection OpenEntityConnection(DbConnection dbConnection) { var dbName = dbConnection.Database; if (dbConnection.State != ConnectionState.Closed) dbConnection.Close(); var connection = new EntityConnection(new System.Data.Metadata.Edm.MetadataWorkspace( EntityConnectionMetadataPaths, EntityConnectionMetadataAssembliesToConsider), dbConnection); connection.Open(); if (!String.IsNullOrEmpty(dbName)) connection.StoreConnection.ChangeDatabase(dbName); return connection; } private bool OpenConnection(bool silent = false) { if (this.connection != null && this.connection.State == ConnectionState.Open) return true; try { DbConnection dbConnection; if (this.DatabaseExist(out dbConnection)) { this.connection = this.OpenEntityConnection(dbConnection); this.objectContext = new ClousotCacheEntities(this.connection); return true; } dbConnection = this.CreateDatabase(); this.connection = this.OpenEntityConnection(dbConnection); using (var trans = this.connection.StoreConnection.BeginTransaction()) { using (var cmd = this.connection.StoreConnection.CreateCommand()) { cmd.Transaction = trans; foreach (var query in this.TablesCreationQueries.Split(';')) { if (String.IsNullOrWhiteSpace(query)) continue; cmd.CommandText = query; cmd.ExecuteNonQuery(); } } trans.Commit(); } this.objectContext = new ClousotCacheEntities(this.connection); foreach (var m in this.metadataIfCreation) this.objectContext.AddToCachingMetadatas(new CachingMetadata { Key = m.Key, Value = m.Value }); this.TrySaveChanges(); return true; } catch (Exception e) { if (!(e is SqlCeException || e is SqlException || e is IOException || e is DataException)) throw; if (!silent) Console.WriteLine("Error: unable to open the cache file: " + e.Message); this.CloseConnection(); } return false; } virtual protected void CloseDatabase() { } protected void CloseConnection() { if (this.connection != null) { this.connection.Close(); this.connection.Dispose(); this.connection = null; } if (this.objectContext != null) { this.objectContext.Dispose(); this.objectContext = null; } } #region ICacheDataAccessor Members public CachingMetadata GetMetadataOrNull(string key, bool silent = false) { try { if (!this.OpenConnection(silent)) { return null; } return this.objectContext.CachingMetadatas.FirstOrDefault(m => m.Key == key); } catch (Exception e) { if (!(e is SqlCeException || e is SqlException || e is IOException || e is DataException)) throw; if (!silent) Console.WriteLine("Error: unable to read the metadata in the cache file: " + e.Message); return null; } } public bool TryGetMethodModelForHash(byte[] hash, out MethodModel result) { try { if (!this.OpenConnection()) { result = null; return false; } result = this.compiledGetMethod(this.objectContext, hash); return result != null; } catch (Exception e) { if (!(e is SqlCeException || e is SqlException || e is IOException || e is DataException)) throw; Console.WriteLine("Error: unable to read the cache: " + e.Message); result = null; return false; } } public void AddAssemblyBinding(MethodModel methodModel) { if (this.objectContext == null) return; if (this.compiledGetBinding(this.objectContext, methodModel.Id, this.currentAssemblyGuid)) return; methodModel.AssemblyBindings.Add(new AssemblyBinding { AssemblyId = this.currentAssemblyGuid }); } public void AddAssemblyInfo() { if (!this.OpenConnection()) return; var ainfo = objectContext.AssemblyInfoes.FirstOrDefault(a => a.AssemblyId == this.currentAssemblyGuid); if (ainfo != null) { if (this.cacheVersion.Version >= 0 || this.cacheVersion.SetBaseLine) { ainfo.Version = this.cacheVersion.Version; if (this.cacheVersion.SetBaseLine) { // only ever set it. Don't clear it. ainfo.IsBaseLine = this.cacheVersion.SetBaseLine; } this.TrySaveChanges(now: true); } return; } ainfo = new AssemblyInfo { AssemblyId = this.currentAssemblyGuid, Created = DateTime.Now, Version = this.cacheVersion.Version, IsBaseLine = this.cacheVersion.SetBaseLine, Name = this.currentAssembly, }; objectContext.AssemblyInfoes.AddObject(ainfo); this.TrySaveChanges(now: true); } public bool TryAddMethodModel(MethodModel methodModel) { try { if (!this.OpenConnection()) return false; var oldEntry = this.compiledGetMethod(this.objectContext, methodModel.Hash); if (oldEntry != null) { this.objectContext.DeleteObject(oldEntry); // We force the removing this.objectContext.SaveChanges(); } this.objectContext.AddToMethodModels(methodModel); this.objectContext.SaveChanges(); AddAssemblyBinding(methodModel); this.objectContext.SaveChanges(); // FIFO algorithm #if false // ignore FIFO for now var nbToDelete = this.compiledNbToDelete(this.objectContext); if (nbToDelete > 0) { var toDelete = this.compiledMethodsToDelete(this.objectContext, nbToDelete); foreach (var m in toDelete) this.objectContext.DeleteObject(m); this.objectContext.SaveChanges(); } #endif return true; } catch (Exception e) { if (!(e is SqlCeException || e is SqlException || e is IOException || e is DataException)) throw; Console.WriteLine("Error: unable to add the method in the cache: " + e.Message); return false; } } private int nbWaitingChanges = 0; const int MaxWaitingChanges = 500; public bool TrySaveChanges(bool now = true) { if (!now && ++this.nbWaitingChanges <= MaxWaitingChanges) return false; try { // The connection should already be opened this.objectContext.SaveChanges(); this.nbWaitingChanges = 0; return true; } catch (Exception e) { if (!(e is SqlCeException || e is SqlException || e is IOException || e is DataException)) throw; Console.WriteLine("Error: unable to save the changes: " + e.Message); return false; } } protected abstract void DeleteDatabase(); public void Clear() { try { this.DeleteDatabase(); } catch (Exception e) { if (!(e is SqlCeException || e is SqlException || e is IOException || e is DataException)) throw; Console.WriteLine("Error: unable to delete the cache file: " + e.ToString()); this.CloseConnection(); } } public virtual void StartAssembly(string name, Guid guid) { this.currentAssembly = name; this.currentAssemblyGuid = guid; this.AddAssemblyInfo(); } public virtual void EndAssembly() { this.currentAssembly = null; } #endregion #region IDisposable Members public void Dispose() { this.Dispose(true); } protected void Dispose(bool disposing) { this.CloseDatabase(); this.CloseConnection(); } #endregion ~SQLCacheDataAccessor() { this.Dispose(false); } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace Microsoft.Win32 { public static class __RegistryKey { public static IObservable<System.Reactive.Unit> Close( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Do(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.Close()).ToUnit(); } public static IObservable<System.Reactive.Unit> Flush( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Do(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.Flush()).ToUnit(); } public static IObservable<System.Reactive.Unit> Dispose( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Do(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.Dispose()).ToUnit(); } public static IObservable<Microsoft.Win32.RegistryKey> CreateSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey) { return Observable.Zip(RegistryKeyValue, subkey, (RegistryKeyValueLambda, subkeyLambda) => RegistryKeyValueLambda.CreateSubKey(subkeyLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> CreateSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<Microsoft.Win32.RegistryKeyPermissionCheck> permissionCheck) { return Observable.Zip(RegistryKeyValue, subkey, permissionCheck, (RegistryKeyValueLambda, subkeyLambda, permissionCheckLambda) => RegistryKeyValueLambda.CreateSubKey(subkeyLambda, permissionCheckLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> CreateSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<Microsoft.Win32.RegistryKeyPermissionCheck> permissionCheck, IObservable<Microsoft.Win32.RegistryOptions> options) { return Observable.Zip(RegistryKeyValue, subkey, permissionCheck, options, (RegistryKeyValueLambda, subkeyLambda, permissionCheckLambda, optionsLambda) => RegistryKeyValueLambda.CreateSubKey(subkeyLambda, permissionCheckLambda, optionsLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> CreateSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<System.Boolean> writable) { return Observable.Zip(RegistryKeyValue, subkey, writable, (RegistryKeyValueLambda, subkeyLambda, writableLambda) => RegistryKeyValueLambda.CreateSubKey(subkeyLambda, writableLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> CreateSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<System.Boolean> writable, IObservable<Microsoft.Win32.RegistryOptions> options) { return Observable.Zip(RegistryKeyValue, subkey, writable, options, (RegistryKeyValueLambda, subkeyLambda, writableLambda, optionsLambda) => RegistryKeyValueLambda.CreateSubKey(subkeyLambda, writableLambda, optionsLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> CreateSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<Microsoft.Win32.RegistryKeyPermissionCheck> permissionCheck, IObservable<System.Security.AccessControl.RegistrySecurity> registrySecurity) { return Observable.Zip(RegistryKeyValue, subkey, permissionCheck, registrySecurity, (RegistryKeyValueLambda, subkeyLambda, permissionCheckLambda, registrySecurityLambda) => RegistryKeyValueLambda.CreateSubKey(subkeyLambda, permissionCheckLambda, registrySecurityLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> CreateSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<Microsoft.Win32.RegistryKeyPermissionCheck> permissionCheck, IObservable<Microsoft.Win32.RegistryOptions> registryOptions, IObservable<System.Security.AccessControl.RegistrySecurity> registrySecurity) { return Observable.Zip(RegistryKeyValue, subkey, permissionCheck, registryOptions, registrySecurity, (RegistryKeyValueLambda, subkeyLambda, permissionCheckLambda, registryOptionsLambda, registrySecurityLambda) => RegistryKeyValueLambda.CreateSubKey(subkeyLambda, permissionCheckLambda, registryOptionsLambda, registrySecurityLambda)); } public static IObservable<System.Reactive.Unit> DeleteSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey) { return ObservableExt.ZipExecute(RegistryKeyValue, subkey, (RegistryKeyValueLambda, subkeyLambda) => RegistryKeyValueLambda.DeleteSubKey(subkeyLambda)); } public static IObservable<System.Reactive.Unit> DeleteSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<System.Boolean> throwOnMissingSubKey) { return ObservableExt.ZipExecute(RegistryKeyValue, subkey, throwOnMissingSubKey, (RegistryKeyValueLambda, subkeyLambda, throwOnMissingSubKeyLambda) => RegistryKeyValueLambda.DeleteSubKey(subkeyLambda, throwOnMissingSubKeyLambda)); } public static IObservable<System.Reactive.Unit> DeleteSubKeyTree( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey) { return ObservableExt.ZipExecute(RegistryKeyValue, subkey, (RegistryKeyValueLambda, subkeyLambda) => RegistryKeyValueLambda.DeleteSubKeyTree(subkeyLambda)); } public static IObservable<System.Reactive.Unit> DeleteSubKeyTree( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> subkey, IObservable<System.Boolean> throwOnMissingSubKey) { return ObservableExt.ZipExecute(RegistryKeyValue, subkey, throwOnMissingSubKey, (RegistryKeyValueLambda, subkeyLambda, throwOnMissingSubKeyLambda) => RegistryKeyValueLambda.DeleteSubKeyTree(subkeyLambda, throwOnMissingSubKeyLambda)); } public static IObservable<System.Reactive.Unit> DeleteValue( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name) { return ObservableExt.ZipExecute(RegistryKeyValue, name, (RegistryKeyValueLambda, nameLambda) => RegistryKeyValueLambda.DeleteValue(nameLambda)); } public static IObservable<System.Reactive.Unit> DeleteValue( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<System.Boolean> throwOnMissingValue) { return ObservableExt.ZipExecute(RegistryKeyValue, name, throwOnMissingValue, (RegistryKeyValueLambda, nameLambda, throwOnMissingValueLambda) => RegistryKeyValueLambda.DeleteValue(nameLambda, throwOnMissingValueLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenBaseKey( IObservable<Microsoft.Win32.RegistryHive> hKey, IObservable<Microsoft.Win32.RegistryView> view) { return Observable.Zip(hKey, view, (hKeyLambda, viewLambda) => Microsoft.Win32.RegistryKey.OpenBaseKey(hKeyLambda, viewLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenRemoteBaseKey( IObservable<Microsoft.Win32.RegistryHive> hKey, IObservable<System.String> machineName) { return Observable.Zip(hKey, machineName, (hKeyLambda, machineNameLambda) => Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(hKeyLambda, machineNameLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenRemoteBaseKey( IObservable<Microsoft.Win32.RegistryHive> hKey, IObservable<System.String> machineName, IObservable<Microsoft.Win32.RegistryView> view) { return Observable.Zip(hKey, machineName, view, (hKeyLambda, machineNameLambda, viewLambda) => Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(hKeyLambda, machineNameLambda, viewLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<System.Boolean> writable) { return Observable.Zip(RegistryKeyValue, name, writable, (RegistryKeyValueLambda, nameLambda, writableLambda) => RegistryKeyValueLambda.OpenSubKey(nameLambda, writableLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<Microsoft.Win32.RegistryKeyPermissionCheck> permissionCheck) { return Observable.Zip(RegistryKeyValue, name, permissionCheck, (RegistryKeyValueLambda, nameLambda, permissionCheckLambda) => RegistryKeyValueLambda.OpenSubKey(nameLambda, permissionCheckLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<System.Security.AccessControl.RegistryRights> rights) { return Observable.Zip(RegistryKeyValue, name, rights, (RegistryKeyValueLambda, nameLambda, rightsLambda) => RegistryKeyValueLambda.OpenSubKey(nameLambda, rightsLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<Microsoft.Win32.RegistryKeyPermissionCheck> permissionCheck, IObservable<System.Security.AccessControl.RegistryRights> rights) { return Observable.Zip(RegistryKeyValue, name, permissionCheck, rights, (RegistryKeyValueLambda, nameLambda, permissionCheckLambda, rightsLambda) => RegistryKeyValueLambda.OpenSubKey(nameLambda, permissionCheckLambda, rightsLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> OpenSubKey( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name) { return Observable.Zip(RegistryKeyValue, name, (RegistryKeyValueLambda, nameLambda) => RegistryKeyValueLambda.OpenSubKey(nameLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> FromHandle( IObservable<Microsoft.Win32.SafeHandles.SafeRegistryHandle> handle) { return Observable.Select(handle, (handleLambda) => Microsoft.Win32.RegistryKey.FromHandle(handleLambda)); } public static IObservable<Microsoft.Win32.RegistryKey> FromHandle( IObservable<Microsoft.Win32.SafeHandles.SafeRegistryHandle> handle, IObservable<Microsoft.Win32.RegistryView> view) { return Observable.Zip(handle, view, (handleLambda, viewLambda) => Microsoft.Win32.RegistryKey.FromHandle(handleLambda, viewLambda)); } public static IObservable<System.String[]> GetSubKeyNames( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.GetSubKeyNames()); } public static IObservable<System.String[]> GetValueNames( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.GetValueNames()); } public static IObservable<System.Object> GetValue( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name) { return Observable.Zip(RegistryKeyValue, name, (RegistryKeyValueLambda, nameLambda) => RegistryKeyValueLambda.GetValue(nameLambda)); } public static IObservable<System.Object> GetValue( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<System.Object> defaultValue) { return Observable.Zip(RegistryKeyValue, name, defaultValue, (RegistryKeyValueLambda, nameLambda, defaultValueLambda) => RegistryKeyValueLambda.GetValue(nameLambda, defaultValueLambda)); } public static IObservable<System.Object> GetValue( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<System.Object> defaultValue, IObservable<Microsoft.Win32.RegistryValueOptions> options) { return Observable.Zip(RegistryKeyValue, name, defaultValue, options, (RegistryKeyValueLambda, nameLambda, defaultValueLambda, optionsLambda) => RegistryKeyValueLambda.GetValue(nameLambda, defaultValueLambda, optionsLambda)); } public static IObservable<Microsoft.Win32.RegistryValueKind> GetValueKind( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name) { return Observable.Zip(RegistryKeyValue, name, (RegistryKeyValueLambda, nameLambda) => RegistryKeyValueLambda.GetValueKind(nameLambda)); } public static IObservable<System.Reactive.Unit> SetValue( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<System.Object> value) { return ObservableExt.ZipExecute(RegistryKeyValue, name, value, (RegistryKeyValueLambda, nameLambda, valueLambda) => RegistryKeyValueLambda.SetValue(nameLambda, valueLambda)); } public static IObservable<System.Reactive.Unit> SetValue( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.String> name, IObservable<System.Object> value, IObservable<Microsoft.Win32.RegistryValueKind> valueKind) { return ObservableExt.ZipExecute(RegistryKeyValue, name, value, valueKind, (RegistryKeyValueLambda, nameLambda, valueLambda, valueKindLambda) => RegistryKeyValueLambda.SetValue(nameLambda, valueLambda, valueKindLambda)); } public static IObservable<System.String> ToString(this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.ToString()); } public static IObservable<System.Security.AccessControl.RegistrySecurity> GetAccessControl( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.GetAccessControl()); } public static IObservable<System.Security.AccessControl.RegistrySecurity> GetAccessControl( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.Security.AccessControl.AccessControlSections> includeSections) { return Observable.Zip(RegistryKeyValue, includeSections, (RegistryKeyValueLambda, includeSectionsLambda) => RegistryKeyValueLambda.GetAccessControl(includeSectionsLambda)); } public static IObservable<System.Reactive.Unit> SetAccessControl( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue, IObservable<System.Security.AccessControl.RegistrySecurity> registrySecurity) { return ObservableExt.ZipExecute(RegistryKeyValue, registrySecurity, (RegistryKeyValueLambda, registrySecurityLambda) => RegistryKeyValueLambda.SetAccessControl(registrySecurityLambda)); } public static IObservable<System.Int32> get_SubKeyCount( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.SubKeyCount); } public static IObservable<Microsoft.Win32.RegistryView> get_View( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.View); } public static IObservable<Microsoft.Win32.SafeHandles.SafeRegistryHandle> get_Handle( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.Handle); } public static IObservable<System.Int32> get_ValueCount( this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.ValueCount); } public static IObservable<System.String> get_Name(this IObservable<Microsoft.Win32.RegistryKey> RegistryKeyValue) { return Observable.Select(RegistryKeyValue, (RegistryKeyValueLambda) => RegistryKeyValueLambda.Name); } } }
using CocosSharp; namespace tests.FontTest { public class SystemFontTestScene : TestScene { private static int fontIdx; private static readonly string[] fontList = { #if IOS || IPHONE || MACOS "Chalkboard SE", "Chalkduster", "Noteworthy", "Marker Felt", "Papyrus", "American Typewriter", "Arial", "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", "fonts/Courier New.ttf", "fonts/Marker Felt.ttf", "fonts/Paint Boy.ttf", "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", "fonts/tahoma.ttf", "fonts/Thonburi.ttf", "fonts/ThonburiBold.ttf" #endif #if WINDOWS || WINDOWSGL "Comic Sans MS", "Felt", "MoolBoran", "Courier New", "Georgia", "Symbol", "Wingdings", "Arial", "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", "fonts/arial.ttf", "fonts/Courier New.ttf", "fonts/Marker Felt.ttf", "fonts/Paint Boy.ttf", "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", "fonts/tahoma.ttf", "fonts/Thonburi.ttf", "fonts/ThonburiBold.ttf" #endif #if ANDROID "Arial", "Courier New", "Georgia", "fonts/A Damn Mess.ttf", "fonts/Abberancy.ttf", "fonts/Abduction.ttf", "fonts/American Typewriter.ttf", "fonts/arial.ttf", "fonts/Courier New.ttf", "fonts/Marker Felt.ttf", "fonts/Paint Boy.ttf", "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", "fonts/tahoma.ttf", "fonts/Thonburi.ttf", "fonts/ThonburiBold.ttf" #endif }; public static int vAlignIdx = 0; public static CCVerticalTextAlignment[] verticalAlignment = { CCVerticalTextAlignment.Top, CCVerticalTextAlignment.Center, CCVerticalTextAlignment.Bottom }; public override void runThisTest() { CCLayer pLayer = new SystemFontTest(); AddChild(pLayer); Scene.Director.ReplaceScene(this); } protected override void NextTestCase() { nextAction(); } protected override void PreviousTestCase() { backAction(); } protected override void RestTestCase() { restartAction(); } public static string nextAction() { fontIdx++; if (fontIdx >= fontList.Length) { fontIdx = 0; vAlignIdx = (vAlignIdx + 1) % verticalAlignment.Length; } return fontList[fontIdx]; } public static string backAction() { fontIdx--; if (fontIdx < 0) { fontIdx = fontList.Length - 1; vAlignIdx--; if (vAlignIdx < 0) vAlignIdx = verticalAlignment.Length - 1; } return fontList[fontIdx]; } public static string restartAction() { return fontList[fontIdx]; } } public class SystemFontTest : CCLayer { private const int kTagLabel1 = 1; private const int kTagLabel2 = 2; private const int kTagLabel3 = 3; private const int kTagLabel4 = 4; private CCSize blockSize; private CCSize size; private float fontSize = 26; public SystemFontTest() { size = Layer.VisibleBoundsWorldspace.Size; CCMenuItemImage item1 = new CCMenuItemImage(TestResource.s_pPathB1, TestResource.s_pPathB2, backCallback); CCMenuItemImage item2 = new CCMenuItemImage(TestResource.s_pPathR1, TestResource.s_pPathR2, restartCallback); CCMenuItemImage item3 = new CCMenuItemImage(TestResource.s_pPathF1, TestResource.s_pPathF2, nextCallback); CCMenu menu = new CCMenu(item1, item2, item3); menu.Position = CCPoint.Zero; item1.Position = new CCPoint(size.Width / 2 - item2.ContentSize.Width * 2, item2.ContentSize.Height / 2); item2.Position = new CCPoint(size.Width / 2, item2.ContentSize.Height / 2); item3.Position = new CCPoint(size.Width / 2 + item2.ContentSize.Width * 2, item2.ContentSize.Height / 2); AddChild(menu, 1); blockSize = new CCSize(size.Width / 3, 200); var leftColor = new CCLayerColor(new CCColor4B(100, 100, 100, 255)); var centerColor = new CCLayerColor(new CCColor4B(200, 100, 100, 255)); var rightColor = new CCLayerColor(new CCColor4B(100, 100, 200, 255)); leftColor.IgnoreAnchorPointForPosition = false; centerColor.IgnoreAnchorPointForPosition = false; rightColor.IgnoreAnchorPointForPosition = false; leftColor.AnchorPoint = CCPoint.AnchorMiddleLeft; centerColor.AnchorPoint = CCPoint.AnchorMiddleLeft; rightColor.AnchorPoint = CCPoint.AnchorMiddleLeft; leftColor.Position = new CCPoint(0, size.Height / 2); centerColor.Position = new CCPoint(blockSize.Width, size.Height / 2); rightColor.Position = new CCPoint(blockSize.Width * 2, size.Height / 2); AddChild(leftColor, -1); AddChild(rightColor, -1); AddChild(centerColor, -1); showFont(SystemFontTestScene.restartAction()); } public void showFont(string pFont) { RemoveChildByTag(kTagLabel1, true); RemoveChildByTag(kTagLabel2, true); RemoveChildByTag(kTagLabel3, true); RemoveChildByTag(kTagLabel4, true); var top = new CCLabel(pFont,"Helvetica", 32); var left = new CCLabel("alignment left", pFont, fontSize, blockSize, CCTextAlignment.Left, SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]); var center = new CCLabel("alignment center", pFont, fontSize, blockSize, CCTextAlignment.Center, SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]); var right = new CCLabel("alignment right", pFont, fontSize, blockSize, CCTextAlignment.Right, SystemFontTestScene.verticalAlignment[SystemFontTestScene.vAlignIdx]); top.AnchorPoint = new CCPoint(0.5f, 1); left.AnchorPoint = CCPoint.AnchorMiddleLeft; center.AnchorPoint = CCPoint.AnchorMiddleLeft; right.AnchorPoint = CCPoint.AnchorMiddleLeft; top.Position = new CCPoint(size.Width / 2, size.Height - 20); left.Position = new CCPoint(0, size.Height / 2); center.Position = new CCPoint(blockSize.Width, size.Height / 2); right.Position = new CCPoint(blockSize.Width * 2, size.Height / 2); AddChild(left, 0, kTagLabel1); AddChild(right, 0, kTagLabel2); AddChild(center, 0, kTagLabel3); AddChild(top, 0, kTagLabel4); } public void restartCallback(object pSender) { showFont(SystemFontTestScene.restartAction()); } public void nextCallback(object pSender) { showFont(SystemFontTestScene.nextAction()); } public void backCallback(object pSender) { showFont(SystemFontTestScene.backAction()); } public virtual string title() { return "System Font test"; } } }
using System; using Xunit; using PillowSharp; using PillowSharp.Client; using PillowSharp.BaseObject; using PillowSharp.Middleware.Default; using System.Threading.Tasks; using PillowSharp.CouchType; using System.Collections.Generic; using System.Linq; using System.IO; namespace test { public class DocumentTests : BaseTest, IDisposable { public TestDocument LastDocument { get; set; } public DocumentTests() : base("pillowtest_doc") { GetTestClient().CreateNewDatabaseAsync(this.TestDB).Wait(); } [Fact] public void CreateDocument() { _CreateDocument().Wait(); } public static async Task<TestDocument> CreateTestDocument(string Database) { var testDoc = TestDocument.GenerateTestObject(); var client = CouchSettings.GetTestClient(Database); var result = await client.CreateANewDocumentAsync(testDoc, DatabaseToCreateDocumentIn: Database); //Ensure all needed parts are set by the client Assert.True(result.Ok, "Error during document creation"); Assert.False(string.IsNullOrEmpty(testDoc.ID), "ID was not set for new document"); Assert.False(string.IsNullOrEmpty(testDoc.Rev), "Rev was not set for new document"); return testDoc; } [Fact] public void PurgeDocuments() { var testDocTask = CreateTestDocument(this.TestDB); testDocTask.Wait(); var testDoc = testDocTask.Result; var client = CouchSettings.GetTestClient(this.TestDB); var result = client.PurgeDocumentsInDatabase(new PurgeRequest() { DocumentsToPurge = new List<PurgeRequestDocument>{ new PurgeRequestDocument(testDoc.ID, new List<string>{ testDoc.Rev}) } }); Assert.NotNull(result); Assert.True(result.Purged.ContainsKey(testDoc.ID)); //Get document from db -> must fail var allDocs = client.GetAllDocuments(); Assert.Empty(allDocs.Rows); //Purge multi revsions testDocTask = CreateTestDocument(this.TestDB); testDoc = testDocTask.Result; testDoc.StringProp = "Cat's everywhere"; var firstRev = testDoc.Rev; client.UpdateDocument(testDoc); result = client.PurgeDocumentsInDatabase(new PurgeRequest() { DocumentsToPurge = new List<PurgeRequestDocument>{ new PurgeRequestDocument(testDoc.ID, new List<string>{testDoc.Rev,firstRev}) } }); Assert.NotNull(result); Assert.True(result.Purged.ContainsKey(testDoc.ID)); allDocs = client.GetAllDocuments(); Assert.Empty(allDocs.Rows); } private async Task _CreateDocument() { LastDocument = await CreateTestDocument(this.TestDB); } [Fact] public void TestQueryForAll() { _CreateDocument().Wait(); var client = GetTestClient(); client.RunForAllDbs((db) => { Assert.True(client.GetAllDocuments(DatabaseToUse:db).TotalRows > 0); }, (db) => db == TestDB); } [Fact] public void GetDocument() { _CreateDocument().Wait(); // ensure document exists _GetDocument().Wait(); } private async Task _GetDocument() { //get all PillowClient client = GetTestClient(); var result = await client.GetAllDocumentsAsync(DatabaseToUse: this.TestDB); Assert.True(result != null, "No result from couch db"); Assert.True(result.TotalRows > 0, "No documents returned, expected >=1"); Assert.True(result.Rows?.Count == result.TotalRows, "Total rows where not equal returned rows!"); Assert.True(result.Rows.FirstOrDefault() != null, "Null object returned for first row"); var firstDocument = result.Rows.FirstOrDefault(); Assert.False(string.IsNullOrEmpty(firstDocument.ID), "Document id was null or empty"); Assert.False(string.IsNullOrEmpty(firstDocument.Value.Revision), "Document rev was null or empty"); //Get single docu, latest rev var singleDoc = await client.GetDocumentAsync<TestDocument>(firstDocument.ID); Assert.True(singleDoc.AllSet(), "Missing values in created document!"); //Get with rev number var singleDocRev = await client.GetDocumentAsync<TestDocument>(singleDoc.ID, singleDoc.Rev); Assert.True(singleDoc.Equals(singleDocRev), "Documents are differnt but should be the same"); } [Fact] public void DeleteDocument() { _CreateDocument().Wait(); Deletedocument().Wait(); } private async Task Deletedocument() { var client = GetTestClient(); var prevRevision = LastDocument.Rev; var result = await client.DeleteDocumentAsync<TestDocument>(LastDocument); Assert.NotNull(result); Assert.True(result.Ok, "Delete document returned false"); Assert.True(LastDocument.Deleted, "Delete flag is not true"); Assert.True(prevRevision != LastDocument.Rev, "Revision was not updated"); } [Fact] public void UpdateDocument() { _CreateDocument().Wait(); _UpdateDocument().Wait(); } private async Task _UpdateDocument() { var client = GetTestClient(); var prevText = LastDocument.StringProp; var lastRev = LastDocument.Rev; LastDocument.StringProp = "Luke, I'm your father!"; var result = await client.UpdateDocumentAsync<TestDocument>(LastDocument); Assert.True(result.Ok, "Update document returned false"); Assert.True(result.ID == LastDocument.ID, "ID of updated document where not the same!"); Assert.True(result.Rev == LastDocument.Rev, "Revision number of result is not the same as for the test document"); Assert.False(lastRev == LastDocument.Rev, "Revision number was not changed"); var dbObj = await client.GetDocumentAsync<TestDocument>(LastDocument.ID, LastDocument.Rev); Assert.False(dbObj.StringProp == prevText, "document wasnt updated as expected!"); } [Fact] public void UpdateDocuments() { _CreateDocument().Wait(); _UpdateDocuments().Wait(); } private async Task _UpdateDocuments() { var client = GetTestClient(); var prevText = LastDocument.StringProp; var lastRev = LastDocument.Rev; LastDocument.StringProp = "Luke, I'm your father!"; var documentList = new List<TestDocument>() { TestDocument.GenerateTestObject(), TestDocument.GenerateTestObject(), LastDocument }; var result = await client.UpdateDocumentsAsync(documentList); Assert.True(result.Count() == documentList.Count, "Result list was not the same length as document list"); Assert.True(documentList.All(d => !string.IsNullOrEmpty(d.ID)), "Not all IDs where set as expected"); Assert.True(documentList.All(d => !string.IsNullOrEmpty(d.Rev)), "Not all revs where set as expected"); Assert.True(result.All(r => r.Ok), "Update document returned false for at least one document"); var changedDocResult = result.FirstOrDefault(r => r.ID == LastDocument.ID); Assert.NotNull(changedDocResult); Assert.True(changedDocResult.Rev == LastDocument.Rev, "Revision number missmatch"); var dbObj = await client.GetDocumentAsync<TestDocument>(LastDocument.ID, LastDocument.Rev); Assert.False(dbObj.StringProp == prevText, "document wasnt updated as expected!"); } [Fact] public void AddAttachment() { //Generate test file with random contens as txt _CreateDocument().Wait(); var file = RandomTextFile(); Assert.True(File.Exists(file)); _AddAttachment(file).Wait(); } private async Task _AddAttachment(string File) { var client = GetTestClient(); var result = await client.AddAttachmentAsync(LastDocument, File, "test.txt"); Assert.True(result.Ok, "Add attachment failed"); Assert.True(result.Rev == LastDocument.Rev, "Revision was not updated"); } private string RandomTextFile() { var testFileName = "test.txt"; if (File.Exists(testFileName)) { File.Delete(testFileName); } Random random = new Random(); File.WriteAllText(testFileName, new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", random.Next(100, 1337)) .Select(s => s[random.Next(s.Length)]).ToArray())); return testFileName; } [Fact] public void GetAttachment() { _CreateDocument().Wait(); var file = RandomTextFile(); Assert.True(File.Exists(file)); _AddAttachment(file).Wait(); _GetAttachment(file).Wait(); } private async Task _GetAttachment(string FilePath) { var expectedSize = File.ReadAllBytes(FilePath); var client = GetTestClient(); var result = await client.GetAttachementAsync(LastDocument, "test.txt"); Assert.True(expectedSize.Count() == result.Count(), "File size is different"); } [Fact] public void DeleteAttachement() { try { _CreateDocument().Wait(); } catch (Exception ex) { throw new Exception($"Error in _CreateDocument with {ex.ToString()}", ex); } string file = null; try { file = RandomTextFile(); Assert.True(File.Exists(file)); } catch (Exception ex) { throw new Exception($"Error in RandomTextFile with {ex.ToString()}", ex); } try { _AddAttachment(file).Wait(); } catch (Exception ex) { throw new Exception($"Error in _AddAttachment with {ex.ToString()}", ex); } try { _DeleteAttachment().Wait(); } catch (Exception ex) { throw new Exception($"Error in _DeleteAttachment with {ex.ToString()}", ex); } } private async Task _DeleteAttachment() { var client = GetTestClient(); var result = await client.DeleteAttachmentAsync(LastDocument, "test.txt"); Assert.True(result.Ok, "Returned result was not true"); Assert.True(result.Rev == LastDocument.Rev, "Revision was not updated as expected"); } public void Dispose() { GetTestClient().DeleteDatbaseAsync(this.TestDB).Wait(); } [Fact] public void TestBaseDocumentProperties() { _CreateDocument().Wait(); var file = RandomTextFile(); Assert.True(File.Exists(file)); _AddAttachment(file).Wait(); CheckBasicProperties().Wait(); } [Fact] public void TestDocumentHead() { _CreateDocument().Wait(); _TestDocumentHead().Wait(); } private async Task _TestDocumentHead() { var client = GetTestClient(); var result = await client.GetCurrentDocumentRevisionAsync(LastDocument.ID, LastDocument.GetType()); Assert.NotNull(result); Assert.Equal(LastDocument.Rev, result); } private async Task CheckBasicProperties() { var client = GetTestClient(); var documentFromDB = await client.GetDocumentAsync<TestDocument>(LastDocument.ID); Assert.NotNull(documentFromDB.ID); Assert.NotNull(documentFromDB.Rev); Assert.False(documentFromDB.Deleted); Assert.NotNull(documentFromDB.Attachments); Assert.True(documentFromDB.Attachments.Count == 1); var firstAttachment = documentFromDB.Attachments.First(); Assert.True(firstAttachment.Key == "test.txt"); Assert.NotNull(firstAttachment.Value.ContentType); Assert.True(firstAttachment.Value.Length > 0); } } }
// // MutableDocument.cs // // Copyright (c) 2017 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; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Couchbase.Lite.Internal.Doc; using Couchbase.Lite.Logging; using Couchbase.Lite.Util; using JetBrains.Annotations; using LiteCore.Interop; namespace Couchbase.Lite { /// <summary> /// A class representing an entry in a Couchbase Lite <see cref="Lite.Database"/>. /// It consists of some metadata, and a collection of user-defined properties /// </summary> public sealed unsafe class MutableDocument : Document, IMutableDictionary { #region Constants private const string Tag = nameof(MutableDocument); #if CBL_LINQ private Linq.IDocumentModel _model; #endif #endregion #region Properties internal override uint Generation => base.Generation + Convert.ToUInt32(Changed); #if CBL_LINQ internal override bool IsEmpty => _model == null && base.IsEmpty; #endif internal override bool IsMutable => true; private bool Changed => (_dict as MutableDictionaryObject)?.HasChanges ?? (_dict as InMemoryDictionary)?.HasChanges ?? false; private IMutableDictionary Dict => _dict as IMutableDictionary; /// <inheritdoc /> public new IMutableFragment this[string key] => Dict?[key] ?? Fragment.Null; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> public MutableDocument() : this(default(string)) { } /// <summary> /// Creates a document given an ID /// </summary> /// <param name="id">The ID for the document</param> public MutableDocument(string id) : this(null, id ?? Misc.CreateGuid(), null) { } /// <summary> /// Creates a document with the given properties /// </summary> /// <param name="data">The properties of the document</param> public MutableDocument(IDictionary<string, object> data) : this() { SetData(data); } /// <summary> /// Creates a document with the given ID and properties /// </summary> /// <param name="id">The ID for the document</param> /// <param name="data">The properties for the document</param> public MutableDocument(string id, IDictionary<string, object> data) : this(id) { SetData(data); } /// <summary> /// Creates a document with the given ID and json string /// </summary> /// <param name="id">The ID for the document</param> /// <param name="json"> /// The json contains the properties for the document /// </param> public MutableDocument(string id, string json) : this(id) { SetJSON(json); } internal MutableDocument([NotNull]Database database, [NotNull]string id) : base(database, id) { } internal MutableDocument([NotNull]Document doc) : this(doc.Database, doc.Id, doc.c4Doc?.Retain<C4DocumentWrapper>()) { } private MutableDocument([CanBeNull]Database database, [NotNull]string id, [CanBeNull]C4DocumentWrapper c4Doc) : base(database, id, c4Doc) { } private MutableDocument([NotNull]MutableDocument other) : this((Document)other) { var dict = new MutableDictionaryObject(); if (other._dict != null) { foreach (var item in other._dict) { dict.SetValue(item.Key, MutableCopy(item.Value)); } } _dict = dict; } #endregion #region Internal Methods #if CBL_LINQ internal void SetFromModel(Linq.IDocumentModel model) { _model = model; } #endif #endregion #region Private Methods #if CBL_LINQ private FLSliceResult EncodeModel(FLEncoder* encoder) { var serializer = JsonSerializer.CreateDefault(); using (var writer = new Internal.Serialization.JsonFLValueWriter(c4Db)) { serializer.Serialize(writer, _model); writer.Flush(); return writer.Result; } } #endif private static object MutableCopy(object original) { switch (original) { case DictionaryObject dict: return dict.ToMutable(); case ArrayObject arr: return arr.ToMutable(); case IList list: return new List<object>(list.Cast<object>()); case IDictionary<string, object> netDict: return new Dictionary<string, object>(netDict); default: return original; } } #endregion #region Overrides /// <inheritdoc /> public override MutableDocument ToMutable() => new MutableDocument(this); // MutableDocument constructor is different, so this override is needed internal override FLSliceResult Encode() { Debug.Assert(Database != null); var body = new FLSliceResult(); Database.ThreadSafety.DoLocked(() => { FLEncoder* encoder = null; try { encoder = Database.SharedEncoder; } catch (Exception) { body = new FLSliceResult(null, 0UL); } #if CBL_LINQ if (_model != null) { return (FLSlice)EncodeModel(encoder); } #endif var handle = GCHandle.Alloc(this); Native.FLEncoder_SetExtraInfo(encoder, (void *)GCHandle.ToIntPtr(handle)); try { _dict.FLEncode(encoder); } catch (Exception) { Native.FLEncoder_Reset(encoder); throw; } finally { handle.Free(); } FLError err; body = NativeRaw.FLEncoder_Finish(encoder, &err); if (body.buf == null) { throw new CouchbaseFleeceException(err); } }); return body; } /// <inheritdoc /> public override string ToString() { var id = new SecureLogString(Id, LogMessageSensitivity.PotentiallyInsecure); return $"{GetType().Name}[{id}]"; } #endregion #region IMutableDictionary /// <inheritdoc /> public new MutableArrayObject GetArray(string key) { return Dict?.GetArray(key); } /// <inheritdoc /> public new MutableDictionaryObject GetDictionary(string key) { return Dict?.GetDictionary(key); } /// <inheritdoc /> public IMutableDictionary Remove(string key) { Dict?.Remove(key); return this; } /// <inheritdoc /> public IMutableDictionary SetValue(string key, object value) { Dict?.SetValue(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetData(IDictionary<string, object> dictionary) { Dict?.SetData(dictionary); return this; } /// <inheritdoc /> public IMutableDictionary SetString(string key, string value) { Dict?.SetString(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetInt(string key, int value) { Dict?.SetInt(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetLong(string key, long value) { Dict?.SetLong(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetFloat(string key, float value) { Dict?.SetFloat(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetDouble(string key, double value) { Dict?.SetDouble(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetBoolean(string key, bool value) { Dict?.SetBoolean(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetBlob(string key, Blob value) { Dict?.SetBlob(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetDate(string key, DateTimeOffset value) { Dict?.SetDate(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetArray(string key, ArrayObject value) { Dict?.SetArray(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetDictionary(string key, DictionaryObject value) { Dict?.SetDictionary(key, value); return this; } /// <inheritdoc /> public IMutableDictionary SetJSON([NotNull] string json) { return Dict?.SetJSON(json); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Compiler; using System.Diagnostics; using System.Diagnostics.Contracts; namespace Microsoft.Contracts.Foxtrot { /// <summary> /// This duplicator is used to copy contract from Out-of-band assemblies onto the real assembly /// /// It is in charge of rebinding all the members to the target assembly members. /// /// Different assemblies can use contracts defined in different places: /// - Microsoft.Contracts.dll for pre-v4.0 assemblies /// - Mscorlib.Contracts.dll for the contracts within the shadow assembly for mscorlib /// - mscorlib.dll for post-v4.0 assemblies /// Therefore, for an extracted assembly to be independently processed (e.g., by the /// rewriter), anything in the assembly dependent on the contracts used must be replaced. /// This visitor does that by turning calls to: /// - OldValue into OldExpressions /// - Result into ResultExpressions /// - ForAll into a method call to the ForAll defined in targetContractNodes /// - Exists into a method call to the Exists defined in targetContractNodes /// - ValueAtReturn(x) into the AST "AddressDereference(x,T)" where T is the type instantiation /// of the generic type that ValueAtReturn is defined over. [Note: this transformation /// is *not* undone by the Rewriter -- or anyone else -- since its only purpose was to /// get past the compiler and isn't needed anymore.] /// - All attributes defined in contractNodes are turned into the equivalent attribute in targetContractNodes /// /// When the regular Duplicator visits a member reference and that member is a generic /// instance, its DuplicateFor table has only the templates in it. To find the corresponding /// generic instance, it uses Specializer.GetCorrespondingMember. That method assumes the /// the member's DeclaringType, which is in the duplicator's source has the same members /// as the corresponding type in the duplicator's target. It furthermore assumes that those /// members are in exactly the same order in the respective member lists. /// /// But we cannot assume that when forwarding things from one assembly to another. /// So this subtype of duplicator just has an override for VisitMemberReference that /// uses a different technique for generic method instances. /// /// </summary> [ContractVerification(true)] internal class ForwardingDuplicator : Duplicator { private readonly ContractNodes contractNodes; private readonly ContractNodes targetContractNodes; public ForwardingDuplicator(Module /*!*/ module, TypeNode type, ContractNodes contractNodes, ContractNodes targetContractNodes) : base(module, type) { this.contractNodes = contractNodes; this.targetContractNodes = targetContractNodes; } /// <summary> /// Note, we can't just use the duplicator's logic for Member references, because the member offsets in the source and /// target are vastly different. /// </summary> [ContractVerification(false)] public override Member VisitMemberReference(Member member) { Contract.Ensures(Contract.Result<Member>() != null || member == null); var asType = member as TypeNode; if (asType != null) return this.VisitTypeReference(asType); var targetDeclaringType = this.VisitTypeReference(member.DeclaringType); Method sourceMethod = member as Method; if (sourceMethod != null) { // Here's how this works: // // 2. Identify MArgs (type arguments of method instance) // // 4. Find index i of method template in TargetDeclaringTypeTemplate by name and type names // 5. TargetDeclaringType = instantiate TargetDeclaringType with mapped TArgs // 6. MethodTemplate = TargetDeclaringType[i] // 7. Instantiate MethodTemplate with MArgs // var sourceMethodTemplate = sourceMethod; // Find source method template, but leave type instantiation while (sourceMethodTemplate.Template != null && sourceMethodTemplate.TemplateArguments != null && sourceMethodTemplate.TemplateArguments.Count > 0) { sourceMethodTemplate = sourceMethodTemplate.Template; } // Steps 1 and 2 TypeNodeList targetMArgs = null; TypeNodeList sourceMArgs = sourceMethod.TemplateArguments; if (sourceMArgs != null) { targetMArgs = new TypeNodeList(sourceMArgs.Count); foreach (var mArg in sourceMArgs) { targetMArgs.Add(this.VisitTypeReference(mArg)); } } Method targetMethod; var targetMethodTemplate = targetDeclaringType.FindShadow(sourceMethodTemplate); if (targetMethodTemplate == null) { // something is wrong. Let's not crash and simply keep the original return sourceMethod; } if (targetMArgs != null) { targetMethod = targetMethodTemplate.GetTemplateInstance(targetMethodTemplate.DeclaringType, targetMArgs); } else { targetMethod = targetMethodTemplate; } return targetMethod; } Field sourceField = member as Field; if (sourceField != null) { return targetDeclaringType.FindShadow(sourceField); } Property sourceProperty = member as Property; if (sourceProperty != null) { return targetDeclaringType.FindShadow(sourceProperty); } Event sourceEvent = member as Event; if (sourceEvent != null) { return targetDeclaringType.FindShadow(sourceEvent); } Debug.Assert(false, "what other members are there?"); Member result = base.VisitMemberReference(member); return result; } /// <summary> /// Need to make sure that references to ForAll/Exists that could be to another assembly go to the target contract nodes /// implementation. /// </summary> public override Expression VisitMemberBinding(MemberBinding memberBinding) { if (memberBinding == null) return null; var result = base.VisitMemberBinding(memberBinding); memberBinding = result as MemberBinding; if (this.targetContractNodes != null && memberBinding != null && memberBinding.TargetObject == null) { // all methods are static Method method = memberBinding.BoundMember as Method; if (method == null) return memberBinding; Contract.Assume(this.contractNodes != null); if (method.Template == null) { if (contractNodes.IsExistsMethod(method)) { return new MemberBinding(null, targetContractNodes.GetExistsTemplate); } if (contractNodes.IsForallMethod(method)) { return new MemberBinding(null, targetContractNodes.GetForAllTemplate); } } else { // template != null Method template = method.Template; var templateArgs = method.TemplateArguments; if (contractNodes.IsGenericForallMethod(template)) { Contract.Assume(templateArgs != null); Contract.Assume(targetContractNodes.GetForAllGenericTemplate != null); return new MemberBinding(null, targetContractNodes.GetForAllGenericTemplate.GetTemplateInstance( targetContractNodes.GetForAllGenericTemplate.DeclaringType, templateArgs[0])); } if (contractNodes.IsGenericExistsMethod(template)) { Contract.Assume(templateArgs != null); Contract.Assume(targetContractNodes.GetExistsGenericTemplate != null); return new MemberBinding(null, targetContractNodes.GetExistsGenericTemplate.GetTemplateInstance( targetContractNodes.GetExistsGenericTemplate.DeclaringType, templateArgs[0])); } } } return result; } [ContractVerification(false)] public override AttributeNode VisitAttributeNode(AttributeNode attribute) { attribute = base.VisitAttributeNode(attribute); if (attribute == null) return null; if (this.targetContractNodes == null) return attribute; if (attribute.Type == this.contractNodes.ContractClassAttribute) { return new AttributeNode( new MemberBinding(null, this.targetContractNodes.ContractClassAttribute.GetConstructor(SystemTypes.Type)), attribute.Expressions); } if (attribute.Type == this.contractNodes.ContractClassForAttribute) { return new AttributeNode( new MemberBinding(null, this.targetContractNodes.ContractClassForAttribute.GetConstructor(SystemTypes.Type)), attribute.Expressions); } if (attribute.Type == this.contractNodes.IgnoreAtRuntimeAttribute) { return new AttributeNode( new MemberBinding(null, this.targetContractNodes.IgnoreAtRuntimeAttribute.GetConstructor()), null); } if (attribute.Type == this.contractNodes.InvariantMethodAttribute) { return new AttributeNode( new MemberBinding(null, this.targetContractNodes.InvariantMethodAttribute.GetConstructor()), null); } if (attribute.Type == this.contractNodes.PureAttribute) { return new AttributeNode(new MemberBinding(null, this.targetContractNodes.PureAttribute.GetConstructor()), null); } if (attribute.Type == this.contractNodes.SpecPublicAttribute) { return new AttributeNode( new MemberBinding(null, this.targetContractNodes.SpecPublicAttribute.GetConstructor(SystemTypes.String)), attribute.Expressions); } if (attribute.Type == this.contractNodes.VerifyAttribute) { return new AttributeNode( new MemberBinding(null, this.targetContractNodes.VerifyAttribute.GetConstructor(SystemTypes.Boolean)), attribute.Expressions); } return attribute; } } }
// 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: Create a stream over unmanaged memory, mostly ** useful for memory-mapped files. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace System.IO { /* * This class is used to access a contiguous block of memory, likely outside * the GC heap (or pinned in place in the GC heap, but a MemoryStream may * make more sense in those cases). It's great if you have a pointer and * a length for a section of memory mapped in by someone else and you don't * want to copy this into the GC heap. UnmanagedMemoryStream assumes these * two things: * * 1) All the memory in the specified block is readable or writable, * depending on the values you pass to the constructor. * 2) The lifetime of the block of memory is at least as long as the lifetime * of the UnmanagedMemoryStream. * 3) You clean up the memory when appropriate. The UnmanagedMemoryStream * currently will do NOTHING to free this memory. * 4) All calls to Write and WriteByte may not be threadsafe currently. * * It may become necessary to add in some sort of * DeallocationMode enum, specifying whether we unmap a section of memory, * call free, run a user-provided delegate to free the memory, etc etc. * We'll suggest user write a subclass of UnmanagedMemoryStream that uses * a SafeHandle subclass to hold onto the memory. * Check for problems when using this in the negative parts of a * process's address space. We may need to use unsigned longs internally * and change the overflow detection logic. * * -----SECURITY MODEL AND SILVERLIGHT----- * A few key notes about exposing UMS in silverlight: * 1. No ctors are exposed to transparent code. This version of UMS only * supports byte* (not SafeBuffer). Therefore, framework code can create * a UMS and hand it to transparent code. Transparent code can use most * operations on a UMS, but not operations that directly expose a * pointer. * * 2. Scope of "unsafe" and non-CLS compliant operations reduced: The * Whidbey version of this class has CLSCompliant(false) at the class * level and unsafe modifiers at the method level. These were reduced to * only where the unsafe operation is performed -- i.e. immediately * around the pointer manipulation. Note that this brings UMS in line * with recent changes in pu/clr to support SafeBuffer. * * 3. Currently, the only caller that creates a UMS is ResourceManager, * which creates read-only UMSs, and therefore operations that can * change the length will throw because write isn't supported. A * conservative option would be to formalize the concept that _only_ * read-only UMSs can be creates, and enforce this by making WriteX and * SetLength SecurityCritical. However, this is a violation of * security inheritance rules, so we must keep these safe. The * following notes make this acceptable for future use. * a. a race condition in WriteX that could have allowed a thread to * read from unzeroed memory was fixed * b. memory region cannot be expanded beyond _capacity; in other * words, a UMS creator is saying a writeable UMS is safe to * write to anywhere in the memory range up to _capacity, specified * in the ctor. Even if the caller doesn't specify a capacity, then * length is used as the capacity. */ public class UnmanagedMemoryStream : Stream { private const long UnmanagedMemStreamMaxLength = Int64.MaxValue; [System.Security.SecurityCritical] // auto-generated private SafeBuffer _buffer; [SecurityCritical] private unsafe byte* _mem; private long _length; private long _capacity; private long _position; private long _offset; private FileAccess _access; internal bool _isOpen; [NonSerialized] private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync // Needed for subclasses that need to map a file, etc. [System.Security.SecuritySafeCritical] // auto-generated protected UnmanagedMemoryStream() { unsafe { _mem = null; } _isOpen = false; } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) { Initialize(buffer, offset, length, FileAccess.Read, false); } [System.Security.SecuritySafeCritical] // auto-generated public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } // We must create one of these without doing a security check. This // class is created while security is trying to start up. Plus, doing // a Demand from Assembly.GetManifestResourceStream isn't useful. [System.Security.SecurityCritical] // auto-generated internal UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { Initialize(buffer, offset, length, access, skipSecurityCheck); } [System.Security.SecuritySafeCritical] // auto-generated protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) { Initialize(buffer, offset, length, access, false); } [System.Security.SecurityCritical] // auto-generated internal void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access, bool skipSecurityCheck) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (buffer.ByteLength < (ulong)(offset + length)) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen")); } if (access < FileAccess.Read || access > FileAccess.ReadWrite) { throw new ArgumentOutOfRangeException("access"); } Contract.EndContractBlock(); if (_isOpen) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); } if (!skipSecurityCheck) { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 } // check for wraparound unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.AcquirePointer(ref pointer); if ( (pointer + offset + length) < pointer) { throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround")); } } finally { if (pointer != null) { buffer.ReleasePointer(); } } } _offset = offset; _buffer = buffer; _length = length; _capacity = length; _access = access; _isOpen = true; } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length) { Initialize(pointer, length, length, FileAccess.Read, false); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } // We must create one of these without doing a security check. This // class is created while security is trying to start up. Plus, doing // a Demand from Assembly.GetManifestResourceStream isn't useful. [System.Security.SecurityCritical] // auto-generated internal unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { Initialize(pointer, length, capacity, access, skipSecurityCheck); } [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access) { Initialize(pointer, length, capacity, access, false); } [System.Security.SecurityCritical] // auto-generated internal unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access, bool skipSecurityCheck) { if (pointer == null) throw new ArgumentNullException("pointer"); if (length < 0 || capacity < 0) throw new ArgumentOutOfRangeException((length < 0) ? "length" : "capacity", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (length > capacity) throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity")); Contract.EndContractBlock(); // Check for wraparound. if (((byte*) ((long)pointer + capacity)) < pointer) throw new ArgumentOutOfRangeException("capacity", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround")); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", Environment.GetResourceString("ArgumentOutOfRange_Enum")); if (_isOpen) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice")); if (!skipSecurityCheck) #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 618 _mem = pointer; _offset = 0; _length = length; _capacity = capacity; _access = access; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen && (_access & FileAccess.Read) != 0; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _isOpen && (_access & FileAccess.Write) != 0; } } [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { _isOpen = false; unsafe { _mem = null; } // Stream allocates WaitHandles for async calls. So for correctness // call base.Dispose(disposing) for better perf, avoiding waiting // for the finalizers to run on those types. base.Dispose(disposing); } public override void Flush() { if (!_isOpen) __Error.StreamIsClosed(); } [HostProtection(ExternalThreading=true)] [ComVisible(false)] public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Flush(); return Task.CompletedTask; } catch(Exception ex) { return Task.FromException(ex); } } public override long Length { get { if (!_isOpen) __Error.StreamIsClosed(); return Interlocked.Read(ref _length); } } public long Capacity { get { if (!_isOpen) __Error.StreamIsClosed(); return _capacity; } } public override long Position { get { if (!CanSeek) __Error.StreamIsClosed(); Contract.EndContractBlock(); return Interlocked.Read(ref _position); } [System.Security.SecuritySafeCritical] // auto-generated set { if (value < 0) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (!CanSeek) __Error.StreamIsClosed(); #if WIN32 unsafe { // On 32 bit machines, ensure we don't wrap around. if (value > (long) Int32.MaxValue || _mem + value < _mem) throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_StreamLength")); } #endif Interlocked.Exchange(ref _position, value); } } [CLSCompliant(false)] public unsafe byte* PositionPointer { [System.Security.SecurityCritical] // auto-generated_required get { if (_buffer != null) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); } // Use a temp to avoid a race long pos = Interlocked.Read(ref _position); if (pos > _capacity) throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition")); byte * ptr = _mem + pos; if (!_isOpen) __Error.StreamIsClosed(); return ptr; } [System.Security.SecurityCritical] // auto-generated_required set { if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); if (!_isOpen) __Error.StreamIsClosed(); // Note: subtracting pointers returns an Int64. Working around // to avoid hitting compiler warning CS0652 on this line. if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength")); if (value < _mem) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, value - _mem); } } internal unsafe byte* Pointer { [System.Security.SecurityCritical] // auto-generated get { if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); return _mem; } } [System.Security.SecuritySafeCritical] // auto-generated public override int Read([In, Out] byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync if (!_isOpen) __Error.StreamIsClosed(); if (!CanRead) __Error.ReadNotSupported(); // Use a local variable to avoid a race where another thread // changes our position after we decide we can read some bytes. long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); long n = len - pos; if (n > count) n = count; if (n <= 0) return 0; int nInt = (int) n; // Safe because n <= count, which is an Int32 if (nInt < 0) nInt = 0; // _position could be beyond EOF Contract.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1. if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(buffer, offset, pointer + pos + _offset, 0, nInt); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(buffer, offset, _mem + pos, 0, nInt); } } Interlocked.Exchange(ref _position, pos + n); return nInt; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Read(...) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<Int32>(cancellationToken); try { Int32 n = Read(buffer, offset, count); Task<Int32> t = _lastReadTask; return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n)); } catch (Exception ex) { Contract.Assert(! (ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } [System.Security.SecuritySafeCritical] // auto-generated public override int ReadByte() { if (!_isOpen) __Error.StreamIsClosed(); if (!CanRead) __Error.ReadNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); if (pos >= len) return -1; Interlocked.Exchange(ref _position, pos + 1); int result; if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); result = *(pointer + pos + _offset); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { result = _mem[pos]; } } return result; } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) __Error.StreamIsClosed(); if (offset > UnmanagedMemStreamMaxLength) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength")); switch(loc) { case SeekOrigin.Begin: if (offset < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, offset); break; case SeekOrigin.Current: long pos = Interlocked.Read(ref _position); if (offset + pos < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, offset + pos); break; case SeekOrigin.End: long len = Interlocked.Read(ref _length); if (len + offset < 0) throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin")); Interlocked.Exchange(ref _position, len + offset); break; default: throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin")); } long finalPos = Interlocked.Read(ref _position); Contract.Assert(finalPos >= 0, "_position >= 0"); return finalPos; } [System.Security.SecuritySafeCritical] // auto-generated public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (_buffer != null) throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer")); if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); if (value > _capacity) throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity")); long pos = Interlocked.Read(ref _position); long len = Interlocked.Read(ref _length); if (value > len) { unsafe { Buffer.ZeroMemory(_mem+len, value-len); } } Interlocked.Exchange(ref _length, value); if (pos > value) { Interlocked.Exchange(ref _position, value); } } [System.Security.SecuritySafeCritical] // auto-generated public override void Write(byte[] buffer, int offset, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..) if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + count; // Check for overflow if (n < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (n > _capacity) { throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); } if (_buffer == null) { // Check to see whether we are now expanding the stream and must // zero any memory in the middle. if (pos > len) { unsafe { Buffer.ZeroMemory(_mem+len, pos-len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory if (n > len) { Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { long bytesLeft = _capacity - pos; if (bytesLeft < count) { throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall")); } unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); Buffer.Memcpy(pointer + pos + _offset, 0, buffer, offset, count); } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { Buffer.Memcpy(_mem + pos, 0, buffer, offset, count); } } Interlocked.Exchange(ref _position, n); return; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - offset < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // contract validation copied from Write(..) if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); try { Write(buffer, offset, count); return Task.CompletedTask; } catch (Exception ex) { Contract.Assert(! (ex is OperationCanceledException)); return Task.FromException<Int32>(ex); } } [System.Security.SecuritySafeCritical] // auto-generated public override void WriteByte(byte value) { if (!_isOpen) __Error.StreamIsClosed(); if (!CanWrite) __Error.WriteNotSupported(); long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition long len = Interlocked.Read(ref _length); long n = pos + 1; if (pos >= len) { // Check for overflow if (n < 0) throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong")); if (n > _capacity) throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity")); // Check to see whether we are now expanding the stream and must // zero any memory in the middle. // don't do if created from SafeBuffer if (_buffer == null) { if (pos > len) { unsafe { Buffer.ZeroMemory(_mem+len, pos-len); } } // set length after zeroing memory to avoid race condition of accessing unzeroed memory Interlocked.Exchange(ref _length, n); } } if (_buffer != null) { unsafe { byte* pointer = null; RuntimeHelpers.PrepareConstrainedRegions(); try { _buffer.AcquirePointer(ref pointer); *(pointer + pos + _offset) = value; } finally { if (pointer != null) { _buffer.ReleasePointer(); } } } } else { unsafe { _mem[pos] = value; } } Interlocked.Exchange(ref _position, n); } } }
namespace Oort.AzureStorage.Mockable { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.RetryPolicies; using Microsoft.WindowsAzure.Storage.Shared.Protocol; public class OortBlobClient : ICloudBlobClient { private readonly CloudBlobClient _cloudBlobClient; public IEnumerable<CloudBlobContainer> ListContainers(string prefix = null, ContainerListingDetails detailsIncluded = ContainerListingDetails.None, BlobRequestOptions options = null, OperationContext operationContext = null) { return _cloudBlobClient.ListContainers(prefix, detailsIncluded, options, operationContext); } public ContainerResultSegment ListContainersSegmented(BlobContinuationToken currentToken) { return _cloudBlobClient.ListContainersSegmented(currentToken); } public ContainerResultSegment ListContainersSegmented(string prefix, BlobContinuationToken currentToken) { return _cloudBlobClient.ListContainersSegmented(prefix, currentToken); } public ContainerResultSegment ListContainersSegmented(string prefix, ContainerListingDetails detailsIncluded, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options = null, OperationContext operationContext = null) { return _cloudBlobClient.ListContainersSegmented(prefix, detailsIncluded, maxResults, currentToken, options, operationContext); } public ICancellableAsyncResult BeginListContainersSegmented(BlobContinuationToken continuationToken, AsyncCallback callback, object state) { return _cloudBlobClient.BeginListContainersSegmented(continuationToken, callback, state); } public ICancellableAsyncResult BeginListContainersSegmented(string prefix, BlobContinuationToken continuationToken, AsyncCallback callback, object state) { return _cloudBlobClient.BeginListContainersSegmented(prefix, continuationToken, callback, state); } public ICancellableAsyncResult BeginListContainersSegmented(string prefix, ContainerListingDetails detailsIncluded, int? maxResults, BlobContinuationToken continuationToken, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state) { return _cloudBlobClient.BeginListContainersSegmented(prefix, detailsIncluded, maxResults, continuationToken, options, operationContext, callback, state); } public ContainerResultSegment EndListContainersSegmented(IAsyncResult asyncResult) { return _cloudBlobClient.EndListContainersSegmented(asyncResult); } public Task<ContainerResultSegment> ListContainersSegmentedAsync(BlobContinuationToken continuationToken) { return _cloudBlobClient.ListContainersSegmentedAsync(continuationToken); } public Task<ContainerResultSegment> ListContainersSegmentedAsync(BlobContinuationToken continuationToken, CancellationToken cancellationToken) { return _cloudBlobClient.ListContainersSegmentedAsync(continuationToken, cancellationToken); } public Task<ContainerResultSegment> ListContainersSegmentedAsync(string prefix, BlobContinuationToken continuationToken) { return _cloudBlobClient.ListContainersSegmentedAsync(prefix, continuationToken); } public Task<ContainerResultSegment> ListContainersSegmentedAsync(string prefix, BlobContinuationToken continuationToken, CancellationToken cancellationToken) { return _cloudBlobClient.ListContainersSegmentedAsync(prefix, continuationToken, cancellationToken); } public Task<ContainerResultSegment> ListContainersSegmentedAsync(string prefix, ContainerListingDetails detailsIncluded, int? maxResults, BlobContinuationToken continuationToken, BlobRequestOptions options, OperationContext operationContext) { return _cloudBlobClient.ListContainersSegmentedAsync(prefix, detailsIncluded, maxResults, continuationToken, options, operationContext); } public Task<ContainerResultSegment> ListContainersSegmentedAsync(string prefix, ContainerListingDetails detailsIncluded, int? maxResults, BlobContinuationToken continuationToken, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { return _cloudBlobClient.ListContainersSegmentedAsync(prefix, detailsIncluded, maxResults, continuationToken, options, operationContext, cancellationToken); } public IEnumerable<IListBlobItem> ListBlobs(string prefix, bool useFlatBlobListing = false, BlobListingDetails blobListingDetails = BlobListingDetails.None, BlobRequestOptions options = null, OperationContext operationContext = null) { return _cloudBlobClient.ListBlobs(prefix, useFlatBlobListing, blobListingDetails, options, operationContext); } public BlobResultSegment ListBlobsSegmented(string prefix, BlobContinuationToken currentToken) { return _cloudBlobClient.ListBlobsSegmented(prefix, currentToken); } public BlobResultSegment ListBlobsSegmented(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext) { return _cloudBlobClient.ListBlobsSegmented(prefix, useFlatBlobListing, blobListingDetails, maxResults, currentToken, options, operationContext); } public ICancellableAsyncResult BeginListBlobsSegmented(string prefix, BlobContinuationToken currentToken, AsyncCallback callback, object state) { return _cloudBlobClient.BeginListBlobsSegmented(prefix, currentToken, callback, state); } public ICancellableAsyncResult BeginListBlobsSegmented(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state) { return _cloudBlobClient.BeginListBlobsSegmented(prefix, useFlatBlobListing, blobListingDetails, maxResults, currentToken, options, operationContext, callback, state); } public BlobResultSegment EndListBlobsSegmented(IAsyncResult asyncResult) { return _cloudBlobClient.EndListBlobsSegmented(asyncResult); } public Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, BlobContinuationToken currentToken) { return _cloudBlobClient.ListBlobsSegmentedAsync(prefix, currentToken); } public Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, BlobContinuationToken currentToken, CancellationToken cancellationToken) { return _cloudBlobClient.ListBlobsSegmentedAsync(prefix, currentToken, cancellationToken); } public Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext) { return _cloudBlobClient.ListBlobsSegmentedAsync(prefix, useFlatBlobListing, blobListingDetails, maxResults, currentToken, options, operationContext); } public Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { return _cloudBlobClient.ListBlobsSegmentedAsync(prefix, useFlatBlobListing, blobListingDetails, maxResults, currentToken, options, operationContext, cancellationToken); } public ICloudBlob GetBlobReferenceFromServer(Uri blobUri, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return _cloudBlobClient.GetBlobReferenceFromServer(blobUri, accessCondition, options, operationContext); } public ICloudBlob GetBlobReferenceFromServer(StorageUri blobUri, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null) { return _cloudBlobClient.GetBlobReferenceFromServer(blobUri, accessCondition, options, operationContext); } public ICancellableAsyncResult BeginGetBlobReferenceFromServer(Uri blobUri, AsyncCallback callback, object state) { return _cloudBlobClient.BeginGetBlobReferenceFromServer(blobUri, callback, state); } public ICancellableAsyncResult BeginGetBlobReferenceFromServer(Uri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state) { return _cloudBlobClient.BeginGetBlobReferenceFromServer(blobUri, accessCondition, options, operationContext, callback, state); } public ICancellableAsyncResult BeginGetBlobReferenceFromServer(StorageUri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, AsyncCallback callback, object state) { return _cloudBlobClient.BeginGetBlobReferenceFromServer(blobUri, accessCondition, options, operationContext, callback, state); } public ICloudBlob EndGetBlobReferenceFromServer(IAsyncResult asyncResult) { return _cloudBlobClient.EndGetBlobReferenceFromServer(asyncResult); } public Task<ICloudBlob> GetBlobReferenceFromServerAsync(Uri blobUri) { return _cloudBlobClient.GetBlobReferenceFromServerAsync(blobUri); } public Task<ICloudBlob> GetBlobReferenceFromServerAsync(Uri blobUri, CancellationToken cancellationToken) { return _cloudBlobClient.GetBlobReferenceFromServerAsync(blobUri, cancellationToken); } public Task<ICloudBlob> GetBlobReferenceFromServerAsync(Uri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { return _cloudBlobClient.GetBlobReferenceFromServerAsync(blobUri, accessCondition, options, operationContext); } public Task<ICloudBlob> GetBlobReferenceFromServerAsync(Uri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { return _cloudBlobClient.GetBlobReferenceFromServerAsync(blobUri, accessCondition, options, operationContext, cancellationToken); } public Task<ICloudBlob> GetBlobReferenceFromServerAsync(StorageUri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { return _cloudBlobClient.GetBlobReferenceFromServerAsync(blobUri, accessCondition, options, operationContext); } public Task<ICloudBlob> GetBlobReferenceFromServerAsync(StorageUri blobUri, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { return _cloudBlobClient.GetBlobReferenceFromServerAsync(blobUri, accessCondition, options, operationContext, cancellationToken); } public ICancellableAsyncResult BeginGetServiceProperties(AsyncCallback callback, object state) { return _cloudBlobClient.BeginGetServiceProperties(callback, state); } public ICancellableAsyncResult BeginGetServiceProperties(BlobRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state) { return _cloudBlobClient.BeginGetServiceProperties(requestOptions, operationContext, callback, state); } public ServiceProperties EndGetServiceProperties(IAsyncResult asyncResult) { return _cloudBlobClient.EndGetServiceProperties(asyncResult); } public Task<ServiceProperties> GetServicePropertiesAsync() { return _cloudBlobClient.GetServicePropertiesAsync(); } public Task<ServiceProperties> GetServicePropertiesAsync(CancellationToken cancellationToken) { return _cloudBlobClient.GetServicePropertiesAsync(cancellationToken); } public Task<ServiceProperties> GetServicePropertiesAsync(BlobRequestOptions requestOptions, OperationContext operationContext) { return _cloudBlobClient.GetServicePropertiesAsync(requestOptions, operationContext); } public Task<ServiceProperties> GetServicePropertiesAsync(BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return _cloudBlobClient.GetServicePropertiesAsync(requestOptions, operationContext, cancellationToken); } public ServiceProperties GetServiceProperties(BlobRequestOptions requestOptions = null, OperationContext operationContext = null) { return _cloudBlobClient.GetServiceProperties(requestOptions, operationContext); } public ICancellableAsyncResult BeginSetServiceProperties(ServiceProperties properties, AsyncCallback callback, object state) { return _cloudBlobClient.BeginSetServiceProperties(properties, callback, state); } public ICancellableAsyncResult BeginSetServiceProperties(ServiceProperties properties, BlobRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state) { return _cloudBlobClient.BeginSetServiceProperties(properties, requestOptions, operationContext, callback, state); } public void EndSetServiceProperties(IAsyncResult asyncResult) { _cloudBlobClient.EndSetServiceProperties(asyncResult); } public Task SetServicePropertiesAsync(ServiceProperties properties) { return _cloudBlobClient.SetServicePropertiesAsync(properties); } public Task SetServicePropertiesAsync(ServiceProperties properties, CancellationToken cancellationToken) { return _cloudBlobClient.SetServicePropertiesAsync(properties, cancellationToken); } public Task SetServicePropertiesAsync(ServiceProperties properties, BlobRequestOptions requestOptions, OperationContext operationContext) { return _cloudBlobClient.SetServicePropertiesAsync(properties, requestOptions, operationContext); } public Task SetServicePropertiesAsync(ServiceProperties properties, BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return _cloudBlobClient.SetServicePropertiesAsync(properties, requestOptions, operationContext, cancellationToken); } public void SetServiceProperties(ServiceProperties properties, BlobRequestOptions requestOptions = null, OperationContext operationContext = null) { _cloudBlobClient.SetServiceProperties(properties, requestOptions, operationContext); } public ICancellableAsyncResult BeginGetServiceStats(AsyncCallback callback, object state) { return _cloudBlobClient.BeginGetServiceStats(callback, state); } public ICancellableAsyncResult BeginGetServiceStats(BlobRequestOptions requestOptions, OperationContext operationContext, AsyncCallback callback, object state) { return _cloudBlobClient.BeginGetServiceStats(requestOptions, operationContext, callback, state); } public ServiceStats EndGetServiceStats(IAsyncResult asyncResult) { return _cloudBlobClient.EndGetServiceStats(asyncResult); } public Task<ServiceStats> GetServiceStatsAsync() { return _cloudBlobClient.GetServiceStatsAsync(); } public Task<ServiceStats> GetServiceStatsAsync(CancellationToken cancellationToken) { return _cloudBlobClient.GetServiceStatsAsync(cancellationToken); } public Task<ServiceStats> GetServiceStatsAsync(BlobRequestOptions requestOptions, OperationContext operationContext) { return _cloudBlobClient.GetServiceStatsAsync(requestOptions, operationContext); } public Task<ServiceStats> GetServiceStatsAsync(BlobRequestOptions requestOptions, OperationContext operationContext, CancellationToken cancellationToken) { return _cloudBlobClient.GetServiceStatsAsync(requestOptions, operationContext, cancellationToken); } public ServiceStats GetServiceStats(BlobRequestOptions requestOptions = null, OperationContext operationContext = null) { return _cloudBlobClient.GetServiceStats(requestOptions, operationContext); } public CloudBlobContainer GetRootContainerReference() { return _cloudBlobClient.GetRootContainerReference(); } public CloudBlobContainer GetContainerReference(string containerName) { return _cloudBlobClient.GetContainerReference(containerName); } public AuthenticationScheme AuthenticationScheme { get { return _cloudBlobClient.AuthenticationScheme; } set { _cloudBlobClient.AuthenticationScheme = value; } } public IBufferManager BufferManager { get { return _cloudBlobClient.BufferManager; } set { _cloudBlobClient.BufferManager = value; } } public StorageCredentials Credentials { get { return _cloudBlobClient.Credentials; } } public Uri BaseUri { get { return _cloudBlobClient.BaseUri; } } public StorageUri StorageUri { get { return _cloudBlobClient.StorageUri; } } public IRetryPolicy RetryPolicy { get { return _cloudBlobClient.RetryPolicy; } set { _cloudBlobClient.RetryPolicy = value; } } public LocationMode LocationMode { get { return _cloudBlobClient.LocationMode; } set { _cloudBlobClient.LocationMode = value; } } public TimeSpan? ServerTimeout { get { return _cloudBlobClient.ServerTimeout; } set { _cloudBlobClient.ServerTimeout = value; } } public TimeSpan? MaximumExecutionTime { get { return _cloudBlobClient.MaximumExecutionTime; } set { _cloudBlobClient.MaximumExecutionTime = value; } } public string DefaultDelimiter { get { return _cloudBlobClient.DefaultDelimiter; } set { _cloudBlobClient.DefaultDelimiter = value; } } public long SingleBlobUploadThresholdInBytes { get { return _cloudBlobClient.SingleBlobUploadThresholdInBytes; } set { _cloudBlobClient.SingleBlobUploadThresholdInBytes = value; } } public int ParallelOperationThreadCount { get { return _cloudBlobClient.ParallelOperationThreadCount; } set { _cloudBlobClient.ParallelOperationThreadCount = value; } } public OortBlobClient(CloudBlobClient cloudBlobClient) { _cloudBlobClient = cloudBlobClient; } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace C { /// <summary> /// Windows binary version resource file /// </summary> [Bam.Core.EvaluationRequired(true)] class WinVersionResource : SourceFile { /// <summary> /// Path key for this module /// </summary> public const string HashFileKey = "Hash of version resource contents"; /// <summary> /// Initialize this module /// </summary> protected override void Init() { base.Init(); this.RegisterGeneratedFile( HashFileKey, this.CreateTokenizedString("$(packagebuilddir)/$(moduleoutputdir)/@filename($(0)).hash", this.InputPath) ); } /// <summary> /// Get or set the binary module associated with this resource /// </summary> public ConsoleApplication BinaryModule { get; set; } private string Contents { get { var binaryModule = this.BinaryModule; var binaryMajorVersion = binaryModule.Macros[ModuleMacroNames.MajorVersion].ToString(); var getMinorVersion = binaryModule.CreateTokenizedString("#valid($(MinorVersion),0)"); if (!getMinorVersion.IsParsed) { getMinorVersion.Parse(); } var binaryMinorVersion = getMinorVersion.ToString(); var getPatchVersion = binaryModule.CreateTokenizedString("#valid($(PatchVersion),0)"); if (!getPatchVersion.IsParsed) { getPatchVersion.Parse(); } var binaryPatchVersion = getPatchVersion.ToString(); var productDefinition = Bam.Core.Graph.Instance.ProductDefinition; var contents = new System.Text.StringBuilder(); contents.AppendLine($"// Version resource for {binaryModule.Macros[Bam.Core.ModuleMacroNames.ModuleName].ToString()}, automatically generated by BuildAMation"); contents.AppendLine("#include \"winver.h\""); contents.AppendLine("VS_VERSION_INFO VERSIONINFO"); // note that these are comma separated contents.AppendLine($"FILEVERSION {binaryMajorVersion},{binaryMinorVersion},{binaryPatchVersion}"); if (null != productDefinition) { contents.AppendLine($"PRODUCTVERSION {productDefinition.MajorVersion ?? 0},{productDefinition.MinorVersion ?? 0},{productDefinition.PatchVersion ?? 0}"); } contents.AppendLine("FILEFLAGSMASK VS_FFI_FILEFLAGSMASK"); string flags = ""; if (this.BuildEnvironment.Configuration == Bam.Core.EConfiguration.Debug) { if (flags.Length > 0) { flags += "|"; } flags += "VS_FF_DEBUG"; } if (null != productDefinition) { if (productDefinition.IsPrerelease) { if (flags.Length > 0) { flags += "|"; } flags += "VS_FF_PRERELEASE"; } } if (!string.IsNullOrEmpty(flags)) { contents.AppendLine($"FILEFLAGS ({flags})"); } contents.AppendLine("FILEOS VOS_NT_WINDOWS32"); // TODO: is there a 64-bit? if (binaryModule is DynamicLibrary || binaryModule is Cxx.DynamicLibrary) { contents.AppendLine("FILETYPE VFT_DLL"); } else { contents.AppendLine("FILETYPE VFT_APP"); } // use the current machine's configuration to determine the default // language,codepage pair supported by the binary var culture = System.Globalization.CultureInfo.CurrentCulture; var codepage = System.Text.Encoding.Default.WindowsCodePage; contents.AppendLine("FILESUBTYPE VFT2_UNKNOWN"); contents.AppendLine("BEGIN"); contents.AppendLine("\tBLOCK \"StringFileInfo\""); contents.AppendLine("\tBEGIN"); contents.AppendLine($"\t\tBLOCK \"{culture.LCID:X4}{codepage:X4}\""); contents.AppendLine("\t\tBEGIN"); var fileDescription = binaryModule.CreateTokenizedString("#valid($(Description),$(modulename))"); if (!fileDescription.IsParsed) { fileDescription.Parse(); } contents.AppendLine($"\t\t\tVALUE \"FileDescription\", \"{fileDescription.ToString()}\""); contents.AppendLine($"\t\t\tVALUE \"FileVersion\", \"{binaryMajorVersion}.{binaryMinorVersion}.{binaryPatchVersion}\""); contents.AppendLine($"\t\t\tVALUE \"InternalName\", \"{binaryModule.Macros[Bam.Core.ModuleMacroNames.ModuleName].ToString()}\""); contents.AppendLine($"\t\t\tVALUE \"OriginalFilename\", \"{System.IO.Path.GetFileName(binaryModule.GeneratedPaths[ConsoleApplication.ExecutableKey].ToString())}\""); if (null != productDefinition) { contents.AppendLine($"\t\t\tVALUE \"ProductName\", \"{productDefinition.Name}\""); contents.AppendLine($"\t\t\tVALUE \"ProductVersion\", \"{productDefinition.MajorVersion ?? 0}.{productDefinition.MinorVersion ?? 0}.{productDefinition.PatchVersion ?? 0}\""); contents.AppendLine($"\t\t\tVALUE \"LegalCopyright\", \"{productDefinition.CopyrightNotice}\""); contents.AppendLine($"\t\t\tVALUE \"CompanyName\", \"{productDefinition.CompanyName}\""); } contents.AppendLine("\t\tEND"); contents.AppendLine("\tEND"); contents.AppendLine("\tBLOCK \"VarFileInfo\""); contents.AppendLine("\tBEGIN"); contents.AppendLine($"\t\tVALUE \"Translation\", 0x{culture.LCID:X4}, {codepage}"); contents.AppendLine("\tEND"); contents.AppendLine("END"); return contents.ToString(); } } /// <summary> /// Execute the build on this module /// </summary> /// <param name="context">in this context</param> protected override void ExecuteInternal( Bam.Core.ExecutionContext context) { base.ExecuteInternal(context); var rcPath = this.InputPath.ToString(); if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(rcPath))) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(rcPath)); } using (System.IO.TextWriter writer = new System.IO.StreamWriter(rcPath)) { writer.NewLine = "\n"; writer.WriteLine(this.Contents); } } /// <summary> /// Determine if this module needs updating /// </summary> protected override void EvaluateInternal() { this.ReasonToExecute = null; var outputPath = this.GeneratedPaths[SourceFileKey].ToString(); if (!System.IO.File.Exists(outputPath)) { this.ReasonToExecute = Bam.Core.ExecuteReasoning.FileDoesNotExist(this.GeneratedPaths[SourceFileKey]); } // have the contents changed since last time? var hashFilePath = this.GeneratedPaths[HashFileKey].ToString(); var hashCompare = Bam.Core.Hash.CompareAndUpdateHashFile( hashFilePath, this.Contents ); switch (hashCompare) { case Bam.Core.Hash.EHashCompareResult.HashesAreDifferent: this.ReasonToExecute = Bam.Core.ExecuteReasoning.InputFileNewer( this.GeneratedPaths[SourceFileKey], this.GeneratedPaths[HashFileKey] ); break; case Bam.Core.Hash.EHashCompareResult.HashFileDoesNotExist: case Bam.Core.Hash.EHashCompareResult.HashesAreIdentical: break; } } } }
namespace XenAdmin.TabPages { partial class VMStoragePage { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { UnregisterHandlers(); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VMStoragePage)); this.AddButton = new System.Windows.Forms.Button(); this.EditButton = new System.Windows.Forms.Button(); this.AttachButton = new System.Windows.Forms.Button(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.DeactivateButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DeactivateButton = new System.Windows.Forms.Button(); this.MoveButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.MoveButton = new System.Windows.Forms.Button(); this.DetachButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DetachButton = new System.Windows.Forms.Button(); this.DeleteButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DeleteButton = new System.Windows.Forms.Button(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.toolStripMenuItemAdd = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemAttach = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemDeactivate = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemMove = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemDelete = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemDetach = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItemProperties = new System.Windows.Forms.ToolStripMenuItem(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.dataGridViewStorage = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.ColumnDevicePosition = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDesc = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSR = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSRVolume = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSize = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnReadOnly = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnPriority = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnActive = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDevicePath = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.pageContainerPanel.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.DeactivateButtonContainer.SuspendLayout(); this.MoveButtonContainer.SuspendLayout(); this.DetachButtonContainer.SuspendLayout(); this.DeleteButtonContainer.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).BeginInit(); this.SuspendLayout(); // // pageContainerPanel // this.pageContainerPanel.Controls.Add(this.tableLayoutPanel1); resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel"); // // AddButton // resources.ApplyResources(this.AddButton, "AddButton"); this.AddButton.Name = "AddButton"; this.AddButton.UseVisualStyleBackColor = true; this.AddButton.Click += new System.EventHandler(this.AddButton_Click); // // EditButton // resources.ApplyResources(this.EditButton, "EditButton"); this.EditButton.Name = "EditButton"; this.EditButton.UseVisualStyleBackColor = true; this.EditButton.Click += new System.EventHandler(this.EditButton_Click); // // AttachButton // resources.ApplyResources(this.AttachButton, "AttachButton"); this.AttachButton.Name = "AttachButton"; this.AttachButton.UseVisualStyleBackColor = true; this.AttachButton.Click += new System.EventHandler(this.AttachButton_Click); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.AddButton); this.flowLayoutPanel1.Controls.Add(this.AttachButton); this.flowLayoutPanel1.Controls.Add(this.DeactivateButtonContainer); this.flowLayoutPanel1.Controls.Add(this.MoveButtonContainer); this.flowLayoutPanel1.Controls.Add(this.DetachButtonContainer); this.flowLayoutPanel1.Controls.Add(this.DeleteButtonContainer); this.flowLayoutPanel1.Controls.Add(this.EditButton); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // DeactivateButtonContainer // this.DeactivateButtonContainer.Controls.Add(this.DeactivateButton); resources.ApplyResources(this.DeactivateButtonContainer, "DeactivateButtonContainer"); this.DeactivateButtonContainer.Name = "DeactivateButtonContainer"; // // DeactivateButton // resources.ApplyResources(this.DeactivateButton, "DeactivateButton"); this.DeactivateButton.Name = "DeactivateButton"; this.DeactivateButton.UseVisualStyleBackColor = true; this.DeactivateButton.Click += new System.EventHandler(this.DeactivateButton_Click); // // MoveButtonContainer // this.MoveButtonContainer.Controls.Add(this.MoveButton); resources.ApplyResources(this.MoveButtonContainer, "MoveButtonContainer"); this.MoveButtonContainer.Name = "MoveButtonContainer"; // // MoveButton // resources.ApplyResources(this.MoveButton, "MoveButton"); this.MoveButton.Name = "MoveButton"; this.MoveButton.UseVisualStyleBackColor = true; this.MoveButton.Click += new System.EventHandler(this.MoveButton_Click); // // DetachButtonContainer // this.DetachButtonContainer.Controls.Add(this.DetachButton); resources.ApplyResources(this.DetachButtonContainer, "DetachButtonContainer"); this.DetachButtonContainer.Name = "DetachButtonContainer"; // // DetachButton // resources.ApplyResources(this.DetachButton, "DetachButton"); this.DetachButton.Name = "DetachButton"; this.DetachButton.UseVisualStyleBackColor = true; this.DetachButton.Click += new System.EventHandler(this.DetachButton_Click); // // DeleteButtonContainer // this.DeleteButtonContainer.Controls.Add(this.DeleteButton); resources.ApplyResources(this.DeleteButtonContainer, "DeleteButtonContainer"); this.DeleteButtonContainer.Name = "DeleteButtonContainer"; // // DeleteButton // resources.ApplyResources(this.DeleteButton, "DeleteButton"); this.DeleteButton.Name = "DeleteButton"; this.DeleteButton.UseVisualStyleBackColor = true; this.DeleteButton.Click += new System.EventHandler(this.DeleteDriveButton_Click); // // contextMenuStrip1 // this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemAdd, this.toolStripMenuItemAttach, this.toolStripMenuItemDeactivate, this.toolStripMenuItemMove, this.toolStripMenuItemDelete, this.toolStripMenuItemDetach, this.toolStripSeparator1, this.toolStripMenuItemProperties}); this.contextMenuStrip1.Name = "contextMenuStrip1"; resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1"); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening); // // toolStripMenuItemAdd // this.toolStripMenuItemAdd.Name = "toolStripMenuItemAdd"; resources.ApplyResources(this.toolStripMenuItemAdd, "toolStripMenuItemAdd"); this.toolStripMenuItemAdd.Click += new System.EventHandler(this.toolStripMenuItemAdd_Click); // // toolStripMenuItemAttach // this.toolStripMenuItemAttach.Name = "toolStripMenuItemAttach"; resources.ApplyResources(this.toolStripMenuItemAttach, "toolStripMenuItemAttach"); this.toolStripMenuItemAttach.Click += new System.EventHandler(this.toolStripMenuItemAttach_Click); // // toolStripMenuItemDeactivate // this.toolStripMenuItemDeactivate.Name = "toolStripMenuItemDeactivate"; resources.ApplyResources(this.toolStripMenuItemDeactivate, "toolStripMenuItemDeactivate"); this.toolStripMenuItemDeactivate.Click += new System.EventHandler(this.toolStripMenuItemDeactivate_Click); // // toolStripMenuItemMove // this.toolStripMenuItemMove.Name = "toolStripMenuItemMove"; resources.ApplyResources(this.toolStripMenuItemMove, "toolStripMenuItemMove"); this.toolStripMenuItemMove.Click += new System.EventHandler(this.toolStripMenuItemMove_Click); // // toolStripMenuItemDelete // this.toolStripMenuItemDelete.Name = "toolStripMenuItemDelete"; resources.ApplyResources(this.toolStripMenuItemDelete, "toolStripMenuItemDelete"); this.toolStripMenuItemDelete.Click += new System.EventHandler(this.toolStripMenuItemDelete_Click); // // toolStripMenuItemDetach // this.toolStripMenuItemDetach.Name = "toolStripMenuItemDetach"; resources.ApplyResources(this.toolStripMenuItemDetach, "toolStripMenuItemDetach"); this.toolStripMenuItemDetach.Click += new System.EventHandler(this.toolStripMenuItemDetach_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // toolStripMenuItemProperties // this.toolStripMenuItemProperties.Image = global::XenAdmin.Properties.Resources.edit_16; resources.ApplyResources(this.toolStripMenuItemProperties, "toolStripMenuItemProperties"); this.toolStripMenuItemProperties.Name = "toolStripMenuItemProperties"; this.toolStripMenuItemProperties.Click += new System.EventHandler(this.toolStripMenuItemProperties_Click); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 2); this.tableLayoutPanel1.Controls.Add(this.dataGridViewStorage, 0, 1); this.tableLayoutPanel1.Controls.Add(this.multipleDvdIsoList1, 0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // dataGridViewStorage // this.dataGridViewStorage.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridViewStorage.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridViewStorage.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridViewStorage.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnDevicePosition, this.ColumnName, this.ColumnDesc, this.ColumnSR, this.ColumnSRVolume, this.ColumnSize, this.ColumnReadOnly, this.ColumnPriority, this.ColumnActive, this.ColumnDevicePath}); resources.ApplyResources(this.dataGridViewStorage, "dataGridViewStorage"); this.dataGridViewStorage.MultiSelect = true; this.dataGridViewStorage.Name = "dataGridViewStorage"; this.dataGridViewStorage.ReadOnly = true; this.dataGridViewStorage.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridViewStorage_CellMouseDoubleClick); this.dataGridViewStorage.SelectionChanged += new System.EventHandler(this.dataGridViewStorage_SelectedIndexChanged); this.dataGridViewStorage.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.dataGridViewStorage_SortCompare); this.dataGridViewStorage.KeyUp += new System.Windows.Forms.KeyEventHandler(this.dataGridViewStorage_KeyUp); this.dataGridViewStorage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dataGridViewStorage_MouseUp); // // ColumnDevicePosition // this.ColumnDevicePosition.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnDevicePosition, "ColumnDevicePosition"); this.ColumnDevicePosition.Name = "ColumnDevicePosition"; this.ColumnDevicePosition.ReadOnly = true; // // ColumnName // this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnName, "ColumnName"); this.ColumnName.Name = "ColumnName"; this.ColumnName.ReadOnly = true; // // ColumnDesc // this.ColumnDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnDesc, "ColumnDesc"); this.ColumnDesc.Name = "ColumnDesc"; this.ColumnDesc.ReadOnly = true; // // ColumnSR // this.ColumnSR.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSR, "ColumnSR"); this.ColumnSR.Name = "ColumnSR"; this.ColumnSR.ReadOnly = true; // // ColumnSRVolume // this.ColumnSRVolume.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSRVolume, "ColumnSRVolume"); this.ColumnSRVolume.Name = "ColumnSRVolume"; this.ColumnSRVolume.ReadOnly = true; // // ColumnSize // this.ColumnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnSize, "ColumnSize"); this.ColumnSize.Name = "ColumnSize"; this.ColumnSize.ReadOnly = true; // // ColumnReadOnly // this.ColumnReadOnly.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnReadOnly, "ColumnReadOnly"); this.ColumnReadOnly.Name = "ColumnReadOnly"; this.ColumnReadOnly.ReadOnly = true; // // ColumnPriority // this.ColumnPriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnPriority, "ColumnPriority"); this.ColumnPriority.Name = "ColumnPriority"; this.ColumnPriority.ReadOnly = true; // // ColumnActive // this.ColumnActive.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnActive, "ColumnActive"); this.ColumnActive.Name = "ColumnActive"; this.ColumnActive.ReadOnly = true; // // ColumnDevicePath // this.ColumnDevicePath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ColumnDevicePath, "ColumnDevicePath"); this.ColumnDevicePath.Name = "ColumnDevicePath"; this.ColumnDevicePath.ReadOnly = true; // // multipleDvdIsoList1 // resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1"); this.multipleDvdIsoList1.LabelNewCdForeColor = System.Drawing.SystemColors.HotTrack; this.multipleDvdIsoList1.LabelSingleDvdForeColor = System.Drawing.SystemColors.ControlText; this.multipleDvdIsoList1.LinkLabelLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.multipleDvdIsoList1.Name = "multipleDvdIsoList1"; this.multipleDvdIsoList1.VM = null; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1"); this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.ReadOnly = true; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2"); this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3"); this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.ReadOnly = true; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.dataGridViewTextBoxColumn4, "dataGridViewTextBoxColumn4"); this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn5, "dataGridViewTextBoxColumn5"); this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; this.dataGridViewTextBoxColumn5.ReadOnly = true; // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn6, "dataGridViewTextBoxColumn6"); this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6"; this.dataGridViewTextBoxColumn6.ReadOnly = true; // // dataGridViewTextBoxColumn7 // this.dataGridViewTextBoxColumn7.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn7, "dataGridViewTextBoxColumn7"); this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7"; this.dataGridViewTextBoxColumn7.ReadOnly = true; // // dataGridViewTextBoxColumn8 // this.dataGridViewTextBoxColumn8.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.dataGridViewTextBoxColumn8, "dataGridViewTextBoxColumn8"); this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8"; this.dataGridViewTextBoxColumn8.ReadOnly = true; // // dataGridViewTextBoxColumn9 // this.dataGridViewTextBoxColumn9.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn9, "dataGridViewTextBoxColumn9"); this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9"; this.dataGridViewTextBoxColumn9.ReadOnly = true; // // dataGridViewTextBoxColumn10 // this.dataGridViewTextBoxColumn10.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn10, "dataGridViewTextBoxColumn10"); this.dataGridViewTextBoxColumn10.Name = "dataGridViewTextBoxColumn10"; this.dataGridViewTextBoxColumn10.ReadOnly = true; // // VMStoragePage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.DoubleBuffered = true; this.Name = "VMStoragePage"; this.Controls.SetChildIndex(this.pageContainerPanel, 0); this.pageContainerPanel.ResumeLayout(false); this.flowLayoutPanel1.ResumeLayout(false); this.DeactivateButtonContainer.ResumeLayout(false); this.MoveButtonContainer.ResumeLayout(false); this.DetachButtonContainer.ResumeLayout(false); this.DeleteButtonContainer.ResumeLayout(false); this.contextMenuStrip1.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button AttachButton; private System.Windows.Forms.Button AddButton; private System.Windows.Forms.Button EditButton; private System.Windows.Forms.Button DetachButton; private System.Windows.Forms.Button DeleteButton; private XenAdmin.Controls.ToolTipContainer DetachButtonContainer; private XenAdmin.Controls.ToolTipContainer DeleteButtonContainer; private XenAdmin.Controls.ToolTipContainer DeactivateButtonContainer; private System.Windows.Forms.Button DeactivateButton; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewStorage; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10; private XenAdmin.Controls.ToolTipContainer MoveButtonContainer; private System.Windows.Forms.Button MoveButton; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemAdd; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemAttach; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDeactivate; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemMove; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemProperties; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDelete; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDetach; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePosition; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDesc; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSR; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSRVolume; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSize; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnReadOnly; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnPriority; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnActive; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePath; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/room_claims/room_assignment_by_night.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Operations.RoomClaims { /// <summary>Holder for reflection information generated from operations/room_claims/room_assignment_by_night.proto</summary> public static partial class RoomAssignmentByNightReflection { #region Descriptor /// <summary>File descriptor for operations/room_claims/room_assignment_by_night.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static RoomAssignmentByNightReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjVvcGVyYXRpb25zL3Jvb21fY2xhaW1zL3Jvb21fYXNzaWdubWVudF9ieV9u", "aWdodC5wcm90bxIiaG9sbXMudHlwZXMub3BlcmF0aW9ucy5yb29tX2NsYWlt", "cxodcHJpbWl0aXZlL3BiX2xvY2FsX2RhdGUucHJvdG8aJW9wZXJhdGlvbnMv", "cm9vbXMvcm9vbV9pbmRpY2F0b3IucHJvdG8ihAEKFVJvb21Bc3NpZ25tZW50", "QnlOaWdodBI5CgRyb29tGAEgASgLMisuaG9sbXMudHlwZXMub3BlcmF0aW9u", "cy5yb29tcy5Sb29tSW5kaWNhdG9yEjAKBGRhdGUYAiABKAsyIi5ob2xtcy50", "eXBlcy5wcmltaXRpdmUuUGJMb2NhbERhdGVCO1oVb3BlcmF0aW9ucy9yb29t", "Y2xhaW1zqgIhSE9MTVMuVHlwZXMuT3BlcmF0aW9ucy5Sb29tQ2xhaW1zYgZw", "cm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbLocalDateReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight), global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNight.Parser, new[]{ "Room", "Date" }, null, null, null) })); } #endregion } #region Messages public sealed partial class RoomAssignmentByNight : pb::IMessage<RoomAssignmentByNight> { private static readonly pb::MessageParser<RoomAssignmentByNight> _parser = new pb::MessageParser<RoomAssignmentByNight>(() => new RoomAssignmentByNight()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RoomAssignmentByNight> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RoomClaims.RoomAssignmentByNightReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomAssignmentByNight() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomAssignmentByNight(RoomAssignmentByNight other) : this() { Room = other.room_ != null ? other.Room.Clone() : null; Date = other.date_ != null ? other.Date.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RoomAssignmentByNight Clone() { return new RoomAssignmentByNight(this); } /// <summary>Field number for the "room" field.</summary> public const int RoomFieldNumber = 1; private global::HOLMS.Types.Operations.Rooms.RoomIndicator room_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.Rooms.RoomIndicator Room { get { return room_; } set { room_ = value; } } /// <summary>Field number for the "date" field.</summary> public const int DateFieldNumber = 2; private global::HOLMS.Types.Primitive.PbLocalDate date_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbLocalDate Date { get { return date_; } set { date_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RoomAssignmentByNight); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RoomAssignmentByNight other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Room, other.Room)) return false; if (!object.Equals(Date, other.Date)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (room_ != null) hash ^= Room.GetHashCode(); if (date_ != null) hash ^= Date.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (room_ != null) { output.WriteRawTag(10); output.WriteMessage(Room); } if (date_ != null) { output.WriteRawTag(18); output.WriteMessage(Date); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (room_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Room); } if (date_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Date); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RoomAssignmentByNight other) { if (other == null) { return; } if (other.room_ != null) { if (room_ == null) { room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator(); } Room.MergeFrom(other.Room); } if (other.date_ != null) { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } Date.MergeFrom(other.Date); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (room_ == null) { room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator(); } input.ReadMessage(room_); break; } case 18: { if (date_ == null) { date_ = new global::HOLMS.Types.Primitive.PbLocalDate(); } input.ReadMessage(date_); break; } } } } } #endregion } #endregion Designer generated code
using UnityEngine; using System.Collections; using System.Collections.Generic; [RequireComponent (typeof (NetworkView))] public class Networking : MonoBehaviour { public bool build = false; public bool resource = false; public AudioClip[] AudioClipSFX; public string ipAddress = "127.0.0.1"; public int port = 25167; public int maxConnections = 2; public GUIStyle unitstyle; public GUIStyle resourcestyle; public GUIStyle buildingstyle; public GUIStyle resourcebuildingstyle; public GameObject[] UnitPrefabs; public GameObject[] BuildingPrefabs; public GameObject[] SpawnPoints; //public GameObject GameController; //for chatting public List<string> chatLog = new List<string>(); public string currentMessage = ""; public string playername = " default"; public GameObject playerObject; public struct PlayerInformation{ public string name; public NetworkPlayer player; public bool ready; public bool winner; } public List<PlayerInformation> playerInfoList = new List<PlayerInformation>(); public int gold = 0; public float goldTimer = 0; public float goldTime = 0; public int goldAmount = 0; public bool gameStarted = false; public bool gameOver = false; public GameObject myBase; // Use this for initialization void Start () { Application.runInBackground = true; if (!gameObject.GetComponent<NetworkView> ()) { gameObject.AddComponent<NetworkView>(); gameObject.networkView.observed = this; gameObject.networkView.stateSynchronization = NetworkStateSynchronization.ReliableDeltaCompressed; gameObject.networkView.viewID = Network.AllocateViewID(); } } // Update is called once per frame void Update () { if (gameOver) { return; } if (Network.peerType == NetworkPeerType.Disconnected) { chatLog.Clear(); currentMessage = ""; } else if (gameStarted){ goldTimer += Time.deltaTime; if (goldTimer >= goldTime){ goldTimer -= goldTime; gold += goldAmount; } if (myBase.GetComponent<BaseBuilding>().destroyed){ networkView.RPC ("UpdateWinner", RPCMode.All,Network.player); } } else if (!gameStarted){ bool temp = true; foreach(PlayerInformation pi in playerInfoList){ if (!pi.ready){ temp = false; } } if (playerInfoList.Count > 0){ gameStarted = temp; if (gameStarted){ if (Network.isServer){ myBase = Network.Instantiate(BuildingPrefabs[2], SpawnPoints[0].transform.position, Quaternion.identity, 0) as GameObject; myBase.GetComponent<Building>().placing = false; } else if (Network.isClient){ myBase = Network.Instantiate(BuildingPrefabs[2], SpawnPoints[1].transform.position, Quaternion.identity, 0) as GameObject; myBase.GetComponent<Building>().placing = false; } } } } } void OnGUI(){ if (gameOver) { if (playerInfoList[0].winner){ GUI.Window(0, new Rect(Screen.width / 4, Screen.height /3, Screen.width/4, Screen.height/100*42), GUIWINDOWLOSE, "Game Over"); } else{ GUI.Window(0, new Rect(Screen.width / 4, Screen.height /3, Screen.width/2, Screen.height/100*20), GUIWINDOWWIN, "Game Over"); } return; } if (Network.peerType == NetworkPeerType.Disconnected) { //ip text box GUI.BeginGroup (new Rect (10, 10, 800, 600)); GUI.Label (new Rect (0.0f, 0.0f, 100, 25), "IP: "); ipAddress = GUI.TextField (new Rect (40.0f, 0.0f, 100, 25), ipAddress); //port text box GUI.Label (new Rect (0.0f, 30.0f, 100, 25), "Port: "); string tempport; tempport = GUI.TextField (new Rect (40.0f, 30.0f, 100, 25), port.ToString ()); port = int.Parse (tempport); //player name text box GUI.Label (new Rect (0.0f, 60.0f, 100, 25), "Name: "); playername = GUI.TextField (new Rect (40.0f, 60.0f, 100, 25), playername); //connect button if (GUI.Button (new Rect (0.0f, 90.0f, 125, 25), "Connect")) { print ("Connecting to " + ipAddress + " : " + port.ToString ()); Network.Connect (ipAddress, port); StartCoroutine (SendJoinMessage ()); //StartCoroutine(OnConnect ()); } //host server button if (GUI.Button (new Rect (0.0f, 120.0f, 125, 25), "Host")) { print ("Hosting server on " + ipAddress + " : " + port.ToString ()); Network.InitializeServer (maxConnections, port, false); ipAddress = Network.player.ipAddress; StartCoroutine (SendJoinMessage ()); //StartCoroutine(OnConnect ()); } GUI.EndGroup (); } else { GUI.BeginGroup (new Rect (10, 10, Screen.width, Screen.height)); if (!gameStarted){ //disconnect button if (GUI.Button (new Rect (0.0f, 0.0f, 125, 25), "Disconnect")) { Network.Disconnect (200); } //display server info GUI.Label (new Rect (0.0f, 30.0f, 200, 25), "IP: " + ipAddress); GUI.Label (new Rect (0.0f, 45.0f, 100, 25), "Port: " + port); GUI.Label (new Rect (0.0f, 60.0f, 200, 25), "Players: " + (Network.connections.Length + 1)); //display connected players int playerIndex = 0; foreach (PlayerInformation pi in playerInfoList) { ++playerIndex; GUI.Label (new Rect (200.0f, 10 + 12.5f * playerIndex, Screen.width, 25), pi.name + " (" + pi.ready + ")"); } //ready button if (GUI.Button (new Rect (0.0f, 85.0f, 125, 25), "Ready")) { this.networkView.RPC ("UpdateReady", RPCMode.All, Network.player, !playerInfoList [0].ready); } GUI.Box(new Rect(150, 0, 200,150), "Lobby"); } //chat input GUI.SetNextControlName ("chatfield"); currentMessage = GUI.TextField (new Rect (0.0f, Screen.height -49, 190, 20), currentMessage); if (GUI.Button (new Rect (Screen.width / 100 * 25, Screen.height -49, 60, 20), "Send")) { if (currentMessage.Length > 0) { string temp = "[" + playername + "]: " + currentMessage; this.networkView.RPC ("Chat", RPCMode.All, temp); currentMessage = ""; } } if (Event.current.isKey && Event.current.keyCode == KeyCode.Return) { if (GUI.GetNameOfFocusedControl () == "chatfield") { if (currentMessage.Length > 0) { string temp = "[" + playername + "]: " + currentMessage; this.networkView.RPC ("Chat", RPCMode.All, temp); currentMessage = ""; } } else { GUI.FocusControl ("chatfield"); } } //chat log int chatindex = 0; foreach (string msg in chatLog) { ++chatindex; GUI.Label (new Rect (0.0f, Screen.height - 72 - 12.5f * (chatLog.Count - chatindex), Screen.width, 25), msg); } GUI.Box(new Rect(0.0f, Screen.height-451 ,260, 400),""); //======================================= // Enforces it to build function //======================================= if (gameStarted){ //GUI.Label (new Rect (0.0f, 30.0f, 200, 25), "Gold: " + gold); GUI.Box(new Rect(Screen.width-220, Screen.height/100*2, 200,300), "Gold: " + gold); //Debug.Log("Gold: " + gold); //GUI.Label (new Rect (Screen.width/100*20, Screen.height/100*4, (float)Screen.width/100*20, (float)Screen.height), "You WIN!"); if (GUI.Button (new Rect (Screen.width -180, Screen.height / 100*8, Screen.width / 100 * 15, Screen.height / 100 * 5), "", unitstyle)) { //AudioClip units = AudioClip.Create ("SFX/Units", 44100, 1, 44100, false, true); //sfx = this.audio; build = true; //Debug.Log("build: " + build); //audio.Play (); } //=========================== // If its in build function //=========================== if (build == true) { if (GUI.Button (new Rect (Screen.width -160, Screen.height / 100 * 15, 80, 60), "", buildingstyle)) { if (gold >= BuildingPrefabs [0].GetComponent<Building> ().cost) { //AudioClip units = AudioClip.Create ("SFX/Units", 44100, 1, 44100, false, true); //sfx = this.audio; gold -= BuildingPrefabs [0].GetComponent<Building> ().cost; Network.Instantiate (BuildingPrefabs [0], Vector3.zero, Quaternion.identity, 0); build = false; PlaySound(1); } } else if (Input.GetMouseButtonDown (1) || Input.GetKey(KeyCode.Escape)) { build = false; PlaySound(2); } } //========================== // Resources Building //========================== if (GUI.Button (new Rect (Screen.width - 180, Screen.height / 100 * 32, Screen.width / 100 * 15, Screen.height / 100 * 5), "", resourcestyle)) { //AudioClip units = AudioClip.Create ("SFX/Units", 44100, 1, 44100, false, true); //sfx = this.audio; resource = true; //Debug.Log("build: " + build); //audio.Play (); } //=========================== // If its in build function //=========================== if (resource == true) { if (GUI.Button (new Rect (Screen.width -160, Screen.height / 100 * 40, 80, 60), "", resourcebuildingstyle)) { if (gold >= BuildingPrefabs [1].GetComponent<Building> ().cost) { //AudioClip units = AudioClip.Create ("SFX/Units", 44100, 1, 44100, false, true); //sfx = this.audio; gold -= BuildingPrefabs [1].GetComponent<Building> ().cost; Network.Instantiate (BuildingPrefabs [1], Vector3.zero, Quaternion.identity, 0); resource = false; PlaySound(1); } } else if (Input.GetMouseButtonDown (1) || Input.GetKey(KeyCode.Escape)) { resource = false; PlaySound(2); } } } GUI.EndGroup (); } } /*IEnumerator OnConnect(){ yield return new WaitForSeconds (1); if (Network.peerType == NetworkPeerType.Connecting) { StartCoroutine (OnConnect ()); } else { GameObject go = GameController.GetComponent<Game>().UnitBuildingPrefabs[0]; GameObject go1 = Network.Instantiate(go, go.transform.position, go.transform.rotation, 0) as GameObject; GameController.GetComponent<Game>().unitBuildingList.Add(go1); } }*/ void OnPlayerConnected(NetworkPlayer player){ } void OnPlayerDisconnected(NetworkPlayer player){ for (int i = 0; i < playerInfoList.Count; ++i) { if (playerInfoList[i].player == player){ this.networkView.RPC ("Chat", RPCMode.All, playerInfoList[i].name + " has left the server"); break; } } this.networkView.RPC ("RemovePlayer", RPCMode.All, player); Network.RemoveRPCs (player); Network.DestroyPlayerObjects (player); } [RPC] public void Chat(string message){ chatLog.Add (message); } [RPC] public void AddPlayer(string name, NetworkPlayer player, bool ready){ if (Network.isServer) { foreach (PlayerInformation pi in playerInfoList){ this.networkView.RPC ("AddPlayer", player, pi.name, pi.player, pi.ready); } } foreach (PlayerInformation pi in playerInfoList){ if (pi.player == player){ return; } } PlayerInformation playerinfo = new PlayerInformation(); playerinfo.name = name; playerinfo.player = player; playerinfo.ready = ready; playerInfoList.Add(playerinfo); } [RPC] public void RemovePlayer(NetworkPlayer player){ for (int i = 0; i < playerInfoList.Count; ++i) { if (playerInfoList[i].player == player){ playerInfoList.RemoveAt(i); break; } } } [RPC] public void UpdateReady(NetworkPlayer player, bool ready){ for (int i = 0; i < playerInfoList.Count; ++i) { if (playerInfoList[i].player == player){ PlayerInformation pi = new PlayerInformation(); pi.name = playerInfoList[i].name; pi.player = playerInfoList[i].player; pi.ready = ready; playerInfoList[i] = pi; break; } } } [RPC] public void UpdateWinner(NetworkPlayer player){ gameOver = true; for (int i = 0; i < playerInfoList.Count; ++i) { if (playerInfoList[i].player == player){ PlayerInformation pi = new PlayerInformation(); pi = playerInfoList[i]; pi.winner = true; playerInfoList[i] = pi; break; } } } IEnumerator SendJoinMessage(){ yield return new WaitForSeconds (0.01f); if (Network.peerType == NetworkPeerType.Server) { this.networkView.RPC ("Chat", RPCMode.All, ""); Vector3 temp = playerObject.transform.position; temp.x += 20; //Network.Instantiate(playerObject, temp, playerObject.transform.rotation, 0); playerInfoList.Clear(); networkView.RPC("AddPlayer", RPCMode.All, playername, Network.player, false); } else if (Network.peerType == NetworkPeerType.Client) { this.networkView.RPC ("Chat", RPCMode.All, playername + " has joined the server"); //Network.Instantiate(playerObject, playerObject.transform.position, playerObject.transform.rotation, 0); playerInfoList.Clear(); networkView.RPC("AddPlayer", RPCMode.All, playername, Network.player, false); } else { StartCoroutine (SendJoinMessage ()); } } void PlaySound(int clip) { audio.volume = Settings.SFXSliderValue; audio.clip = AudioClipSFX [clip]; audio.Play (); } void LoginWindow(int WindowID) { } void GUIWINDOWWIN (int WindowID) { GUI.Label (new Rect (Screen.width/100*23, Screen.height/100*4, (float)Screen.width/100*20, (float)Screen.height), "You WIN!"); if (GUI.Button (new Rect (Screen.width/100*17, Screen.height/100*10, 150, 30), "Return To Main Menu")) { Network.Disconnect (200); Initiate.Fade("Main Menu", Color.black, 0.5f); } } void GUIWINDOWLOSE (int WindowID) { GUI.Label (new Rect (Screen.width/100*23, Screen.height/100*4, (float)Screen.width/100*20, (float)Screen.height), "You LOSE!"); if (GUI.Button (new Rect (Screen.width/100*17, Screen.height/100*10, 150, 30), "Return To Main Menu")) { Network.Disconnect (200); Initiate.Fade("Main Menu", Color.black, 0.5f); } } }
// // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; namespace System.Data { /// <summary> /// Summary description for MergeManager. /// </summary> internal class MergeManager { internal static void Merge(DataSet targetSet, DataSet sourceSet, bool preserveChanges, MissingSchemaAction missingSchemaAction) { if(targetSet == null) throw new ArgumentNullException("targetSet"); if(sourceSet == null) throw new ArgumentNullException("sourceSet"); bool prevEC = targetSet.EnforceConstraints; targetSet.EnforceConstraints = false; foreach (DataTable t in sourceSet.Tables) MergeManager.Merge(targetSet, t, preserveChanges, missingSchemaAction); AdjustSchema(targetSet,sourceSet,missingSchemaAction); targetSet.EnforceConstraints = prevEC; } internal static void Merge(DataSet targetSet, DataTable sourceTable, bool preserveChanges, MissingSchemaAction missingSchemaAction) { if(targetSet == null) throw new ArgumentNullException("targetSet"); if(sourceTable == null) throw new ArgumentNullException("sourceTable"); bool savedEnfoceConstraints = targetSet.EnforceConstraints; targetSet.EnforceConstraints = false; DataTable targetTable = null; if (!AdjustSchema(targetSet, sourceTable, missingSchemaAction,ref targetTable)) { return; } if (targetTable != null) { checkColumnTypes(targetTable, sourceTable); // check that the colums datatype is the same fillData(targetTable, sourceTable, preserveChanges); } targetSet.EnforceConstraints = savedEnfoceConstraints; if (!targetSet.EnforceConstraints && targetTable != null) { // indexes are still outdated targetTable.ResetIndexes(); } } internal static void Merge(DataSet targetSet, DataRow[] sourceRows, bool preserveChanges, MissingSchemaAction missingSchemaAction) { if(targetSet == null) throw new ArgumentNullException("targetSet"); if(sourceRows == null) throw new ArgumentNullException("sourceRows"); bool savedEnfoceConstraints = targetSet.EnforceConstraints; targetSet.EnforceConstraints = false; ArrayList targetTables = new ArrayList(); for (int i = 0; i < sourceRows.Length; i++) { DataRow row = sourceRows[i]; DataTable sourceTable = row.Table; DataTable targetTable = null; if (!AdjustSchema(targetSet, sourceTable, missingSchemaAction,ref targetTable)) { return; } if (targetTable != null) { checkColumnTypes(targetTable, row.Table); MergeRow(targetTable, row, preserveChanges); if (!(targetTables.IndexOf(targetTable) >= 0)) { targetTables.Add(targetTable); } } } targetSet.EnforceConstraints = savedEnfoceConstraints; foreach(DataTable table in targetTables) { table.ResetIndexes(); } } // merge a row into a target table. private static void MergeRow(DataTable targetTable, DataRow row, bool preserveChanges) { DataColumnCollection columns = row.Table.Columns; DataColumn[] primaryKeys = targetTable.PrimaryKey; DataRow targetRow = null; DataRowVersion version = DataRowVersion.Default; if (row.RowState == DataRowState.Deleted) version = DataRowVersion.Original; if (primaryKeys != null && primaryKeys.Length > 0) // if there are any primary key. { // initiate an array that has the values of the primary keys. object[] keyValues = new object[primaryKeys.Length]; for (int j = 0; j < keyValues.Length; j++) { keyValues[j] = row[primaryKeys[j].ColumnName, version]; } // find the row in the target table. targetRow = targetTable.Rows.Find(keyValues, DataViewRowState.OriginalRows); if (targetRow == null) targetRow = targetTable.Rows.Find(keyValues); } // row doesn't exist in target table, or there are no primary keys. // create new row and copy values from source row to the new row. if (targetRow == null) { DataRow newRow = targetTable.NewNotInitializedRow(); row.CopyValuesToRow(newRow); targetTable.Rows.AddInternal (newRow); } // row exists in target table, and presere changes is false - // change the values of the target row to the values of the source row. else if (!preserveChanges) { row.CopyValuesToRow(targetRow); } } // adjust the dataset schema according to the missingschemaaction param // (relations). // return false if adjusting fails. private static bool AdjustSchema(DataSet targetSet, DataSet sourceSet, MissingSchemaAction missingSchemaAction) { if (missingSchemaAction == MissingSchemaAction.Add || missingSchemaAction == MissingSchemaAction.AddWithKey) { foreach (DataRelation relation in sourceSet.Relations) { // TODO : add more precise condition (columns) if (!targetSet.Relations.Contains(relation.RelationName)) { DataTable targetTable = targetSet.Tables[relation.ParentColumns[0].Table.TableName]; DataColumn[] parentColumns = ResolveColumns(sourceSet,targetTable,relation.ParentColumns); targetTable = targetSet.Tables[relation.ChildColumns[0].Table.TableName]; DataColumn[] childColumns = ResolveColumns(sourceSet,targetTable,relation.ChildColumns); if (parentColumns != null && childColumns != null) { DataRelation newRelation = new DataRelation(relation.RelationName,parentColumns,childColumns); newRelation.Nested = relation.Nested; targetSet.Relations.Add(newRelation); } } else { // TODO : should we throw an exeption ? } } foreach(DataTable sourceTable in sourceSet.Tables) { DataTable targetTable = targetSet.Tables[sourceTable.TableName]; if (targetTable != null) { foreach(Constraint constraint in sourceTable.Constraints) { if (constraint is UniqueConstraint) { UniqueConstraint uc = (UniqueConstraint)constraint; // FIXME : add more precise condition (columns) if ( !targetTable.Constraints.Contains(uc.ConstraintName) ) { DataColumn[] columns = ResolveColumns(sourceSet,targetTable,uc.Columns); if (columns != null) { UniqueConstraint newConstraint = new UniqueConstraint(uc.ConstraintName,columns,uc.IsPrimaryKey); targetTable.Constraints.Add(newConstraint); } } else { // FIXME : should we throw an exception ? } } else { ForeignKeyConstraint fc = (ForeignKeyConstraint)constraint; // FIXME : add more precise condition (columns) if (!targetTable.Constraints.Contains(fc.ConstraintName)) { DataColumn[] columns = ResolveColumns(sourceSet,targetTable,fc.Columns); DataTable relatedTable = targetSet.Tables[fc.RelatedTable.TableName]; DataColumn[] relatedColumns = ResolveColumns(sourceSet,relatedTable,fc.RelatedColumns); if (columns != null && relatedColumns != null) { ForeignKeyConstraint newConstraint = new ForeignKeyConstraint(fc.ConstraintName,relatedColumns,columns); targetTable.Constraints.Add(newConstraint); } } else { // FIXME : should we throw an exception ? } } } } } } return true; } private static DataColumn[] ResolveColumns(DataSet targetSet,DataTable targetTable,DataColumn[] sourceColumns) { if (sourceColumns != null && sourceColumns.Length > 0) { // TODO : worth to check that all source colums come from the same table if (targetTable != null) { int i=0; DataColumn[] targetColumns = new DataColumn[sourceColumns.Length]; foreach(DataColumn sourceColumn in sourceColumns) { targetColumns[i++] = targetTable.Columns[sourceColumn.ColumnName]; } return targetColumns; } } return null; } // adjust the table schema according to the missingschemaaction param. // return false if adjusting fails. private static bool AdjustSchema(DataSet targetSet, DataTable sourceTable, MissingSchemaAction missingSchemaAction, ref DataTable newTable) { string tableName = sourceTable.TableName; // if the source table not exists in the target dataset // we act according to the missingschemaaction param. int tmp = targetSet.Tables.IndexOf(tableName); // we need to check if it is equals names if (tmp != -1 && !targetSet.Tables[tmp].TableName.Equals(tableName)) tmp = -1; if (tmp == -1) { if (missingSchemaAction == MissingSchemaAction.Ignore) { return true; } if (missingSchemaAction == MissingSchemaAction.Error) { throw new ArgumentException("Target DataSet missing definition for "+ tableName + "."); } DataTable cloneTable = (DataTable)sourceTable.Clone(); targetSet.Tables.Add(cloneTable); tableName = cloneTable.TableName; } DataTable table = targetSet.Tables[tableName]; for (int i = 0; i < sourceTable.Columns.Count; i++) { DataColumn sourceColumn = sourceTable.Columns[i]; // if a column from the source table doesn't exists in the target table // we act according to the missingschemaaction param. DataColumn targetColumn = table.Columns[sourceColumn.ColumnName]; if(targetColumn == null) { if (missingSchemaAction == MissingSchemaAction.Ignore) { continue; } if (missingSchemaAction == MissingSchemaAction.Error) { throw new ArgumentException(("Column '" + sourceColumn.ColumnName + "' does not belong to table Items.")); } targetColumn = new DataColumn(sourceColumn.ColumnName, sourceColumn.DataType, sourceColumn.Expression, sourceColumn.ColumnMapping); table.Columns.Add(targetColumn); } if (sourceColumn.Unique) { try { targetColumn.Unique = sourceColumn.Unique; } catch(Exception e){ // Console.WriteLine("targetColumn : {0} targetTable : {1} ",targetColumn.ColumnName,table.TableName); foreach(DataRow row in table.Rows) { // Console.WriteLine(row[targetColumn]); } throw e; } } if(sourceColumn.AutoIncrement) { targetColumn.AutoIncrement = sourceColumn.AutoIncrement; targetColumn.AutoIncrementSeed = sourceColumn.AutoIncrementSeed; targetColumn.AutoIncrementStep = sourceColumn.AutoIncrementStep; } } if (!AdjustPrimaryKeys(table, sourceTable)) { return false; } newTable = table; return true; } // find if there is a valid matching between the targetTable PrimaryKey and the // sourceTable primatyKey. // return true if there is a match, else return false and raise a MergeFailedEvent. private static bool AdjustPrimaryKeys(DataTable targetTable, DataTable sourceTable) { // if the length of one of the tables primarykey if 0 - there is nothing to check. if (sourceTable.PrimaryKey.Length != 0) { if (targetTable.PrimaryKey.Length == 0) { // if target table has no primary key at all - // import primary key from source table DataColumn[] targetColumns = new DataColumn[sourceTable.PrimaryKey.Length]; for(int i=0; i < sourceTable.PrimaryKey.Length; i++){ DataColumn sourceColumn = sourceTable.PrimaryKey[i]; DataColumn targetColumn = targetTable.Columns[sourceColumn.ColumnName]; if (targetColumn == null) { // is target table has no column corresponding // to source table PK column - merge fails string message = "Column " + sourceColumn.ColumnName + " does not belongs to table " + targetTable.TableName; MergeFailedEventArgs e = new MergeFailedEventArgs(sourceTable, message); targetTable.DataSet.OnMergeFailed(e); return false; } else { targetColumns[i] = targetColumn; } } targetTable.PrimaryKey = targetColumns; } else { // if target table already has primary key and // if the length of primarykey is not equal - merge fails if (targetTable.PrimaryKey.Length != sourceTable.PrimaryKey.Length) { string message = "<target>.PrimaryKey and <source>.PrimaryKey have different Length."; MergeFailedEventArgs e = new MergeFailedEventArgs(sourceTable, message); targetTable.DataSet.OnMergeFailed(e); return false; } else { // we have to see that each primary column in the target table // has a column with the same name in the sourcetable primarykey columns. bool foundMatch; DataColumn[] targetDataColumns = targetTable.PrimaryKey; DataColumn[] srcDataColumns = sourceTable.PrimaryKey; // loop on all primary key columns in the targetTable. for (int i = 0; i < targetDataColumns.Length; i++) { foundMatch = false; DataColumn col = targetDataColumns[i]; // find if there is a column with the same name in the // sourceTable primary key columns. for (int j = 0; j < srcDataColumns.Length; j++) { if (srcDataColumns[j].ColumnName == col.ColumnName) { foundMatch = true; break; } } if (!foundMatch) { string message = "Mismatch columns in the PrimaryKey : <target>." + col.ColumnName + " versus <source>." + srcDataColumns[i].ColumnName + "."; MergeFailedEventArgs e = new MergeFailedEventArgs(sourceTable, message); targetTable.DataSet.OnMergeFailed(e); return false; } } } } } return true; } // fill the data from the source table to the target table private static void fillData(DataTable targetTable, DataTable sourceTable, bool preserveChanges) { for (int i = 0; i < sourceTable.Rows.Count; i++) { DataRow row = sourceTable.Rows[i]; MergeRow(targetTable, row, preserveChanges); } } // check tha column from 2 tables that has the same name also has the same datatype. private static void checkColumnTypes(DataTable targetTable, DataTable sourceTable) { for (int i = 0; i < sourceTable.Columns.Count; i++) { DataColumn fromCol = sourceTable.Columns[i]; DataColumn toCol = targetTable.Columns[fromCol.ColumnName]; if((toCol != null) && (toCol.DataType != fromCol.DataType)) throw new DataException("<target>." + fromCol.ColumnName + " and <source>." + fromCol.ColumnName + " have conflicting properties: DataType property mismatch."); } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using log4net; using Nini.Config; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework { public class ModuleLoader { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public Dictionary<string, Assembly> LoadedAssemblys = new Dictionary<string, Assembly>(); private readonly List<IRegionModule> m_loadedModules = new List<IRegionModule>(); private readonly Dictionary<string, IRegionModule> m_loadedSharedModules = new Dictionary<string, IRegionModule>(); private readonly IConfigSource m_config; public ModuleLoader(IConfigSource config) { m_config = config; } public IRegionModule[] GetLoadedSharedModules { get { IRegionModule[] regionModules = new IRegionModule[m_loadedSharedModules.Count]; m_loadedSharedModules.Values.CopyTo(regionModules, 0); return regionModules; } } public List<IRegionModule> PickupModules(Scene scene, string moduleDir) { DirectoryInfo dir = new DirectoryInfo(moduleDir); List<IRegionModule> modules = new List<IRegionModule>(); foreach (FileInfo fileInfo in dir.GetFiles("*.dll")) { modules.AddRange(LoadRegionModules(fileInfo.FullName, scene)); } return modules; } public void LoadDefaultSharedModule(IRegionModule module) { if (m_loadedSharedModules.ContainsKey(module.Name)) { m_log.ErrorFormat("[MODULES]: Module name \"{0}\" already exists in module list. Module not added!", module.Name); } else { m_loadedSharedModules.Add(module.Name, module); } } public void InitialiseSharedModules(Scene scene) { foreach (IRegionModule module in m_loadedSharedModules.Values) { module.Initialise(scene, m_config); scene.AddModule(module.Name, module); //should be doing this? } } public void InitializeModule(IRegionModule module, Scene scene) { module.Initialise(scene, m_config); scene.AddModule(module.Name, module); m_loadedModules.Add(module); } /// <summary> /// Loads/initialises a Module instance that can be used by multiple Regions /// </summary> /// <param name="dllName"></param> /// <param name="moduleName"></param> public void LoadSharedModule(string dllName, string moduleName) { IRegionModule module = LoadModule(dllName, moduleName); if (module != null) LoadSharedModule(module); } /// <summary> /// Loads/initialises a Module instance that can be used by multiple Regions /// </summary> /// <param name="module"></param> public void LoadSharedModule(IRegionModule module) { if (!m_loadedSharedModules.ContainsKey(module.Name)) { m_loadedSharedModules.Add(module.Name, module); } } public List<IRegionModule> LoadRegionModules(string dllName, Scene scene) { IRegionModule[] modules = LoadModules(dllName); List<IRegionModule> initializedModules = new List<IRegionModule>(); if (modules.Length > 0) { m_log.InfoFormat("[MODULES]: Found Module Library [{0}]", dllName); foreach (IRegionModule module in modules) { if (!module.IsSharedModule) { m_log.InfoFormat("[MODULES]: [{0}]: Initializing.", module.Name); InitializeModule(module, scene); initializedModules.Add(module); } else { m_log.InfoFormat("[MODULES]: [{0}]: Loading Shared Module.", module.Name); LoadSharedModule(module); } } } return initializedModules; } public void LoadRegionModule(string dllName, string moduleName, Scene scene) { IRegionModule module = LoadModule(dllName, moduleName); if (module != null) { InitializeModule(module, scene); } } /// <summary> /// Loads a external Module (if not already loaded) and creates a new instance of it. /// </summary> /// <param name="dllName"></param> /// <param name="moduleName"></param> public IRegionModule LoadModule(string dllName, string moduleName) { IRegionModule[] modules = LoadModules(dllName); foreach (IRegionModule module in modules) { if ((module != null) && (module.Name == moduleName)) { return module; } } return null; } public IRegionModule[] LoadModules(string dllName) { //m_log.DebugFormat("[MODULES]: Looking for modules in {0}", dllName); List<IRegionModule> modules = new List<IRegionModule>(); Assembly pluginAssembly; if (!LoadedAssemblys.TryGetValue(dllName, out pluginAssembly)) { try { pluginAssembly = Assembly.LoadFrom(dllName); LoadedAssemblys.Add(dllName, pluginAssembly); } catch (BadImageFormatException) { //m_log.InfoFormat("[MODULES]: The file [{0}] is not a module assembly.", e.FileName); } } if (pluginAssembly != null) { try { foreach (Type pluginType in pluginAssembly.GetTypes()) { if (pluginType.IsPublic) { if (!pluginType.IsAbstract) { if (pluginType.GetInterface("IRegionModule") != null) { modules.Add((IRegionModule)Activator.CreateInstance(pluginType)); } } } } } catch (Exception e) { m_log.ErrorFormat( "[MODULES]: Could not load types for plugin DLL {0}. Exception {1} {2}", pluginAssembly.FullName, e.Message, e.StackTrace); // justincc: Right now this is fatal to really get the user's attention throw e; } } return modules.ToArray(); } public void PostInitialise() { foreach (IRegionModule module in m_loadedSharedModules.Values) { module.PostInitialise(); } foreach (IRegionModule module in m_loadedModules) { module.PostInitialise(); } } public void ClearCache() { LoadedAssemblys.Clear(); } public void UnloadModule(IRegionModule rm) { rm.Close(); m_loadedModules.Remove(rm); } } }
using MagicOnion.Server.Hubs; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; namespace MagicOnion.Server { public abstract class MagicOnionFilterDescriptor<TAttribute> : IMagicOnionFilterFactory<TAttribute> where TAttribute: class { public IMagicOnionFilterFactory<TAttribute>? Factory { get; } public TAttribute? Instance { get; } public int Order { get; } protected MagicOnionFilterDescriptor(Type type, int order = 0) { Factory = new MagicOnionFilterTypeFactory(type, order); Instance = null; Order = order; } protected MagicOnionFilterDescriptor(TAttribute instance, int order = 0) { Factory = null; Instance = instance ?? throw new ArgumentNullException(nameof(instance)); Order = order; } protected MagicOnionFilterDescriptor(IMagicOnionFilterFactory<TAttribute> factory, int order = 0) { Factory = factory ?? throw new ArgumentNullException(nameof(factory)); Instance = null; Order = order; } public TAttribute CreateInstance(IServiceProvider serviceProvider) { if (Instance != null) return Instance; if (Factory != null) return Factory.CreateInstance(serviceProvider); throw new InvalidOperationException("MagicOnionFilterDescriptor requires instance or factory"); } // Create a filter instance from specified type. class MagicOnionFilterTypeFactory : IMagicOnionFilterFactory<TAttribute> { public Type Type { get; } public int Order { get; } public MagicOnionFilterTypeFactory(Type type, int order) { Type = type; Order = order; } public TAttribute CreateInstance(IServiceProvider serviceProvider) { return (TAttribute)ActivatorUtilities.CreateInstance(serviceProvider, Type); } } } public class MagicOnionServiceFilterDescriptor : MagicOnionFilterDescriptor<MagicOnionFilterAttribute> { public MagicOnionServiceFilterDescriptor(Type type, int order = 0) : base(type, order) { } public MagicOnionServiceFilterDescriptor(MagicOnionFilterAttribute instance, int order = 0) : base(instance, order) { } public MagicOnionServiceFilterDescriptor(IMagicOnionFilterFactory<MagicOnionFilterAttribute> factory, int order = 0) : base(factory, order) { } } public class StreamingHubFilterDescriptor : MagicOnionFilterDescriptor<StreamingHubFilterAttribute> { public StreamingHubFilterDescriptor(Type type, int order = 0) : base(type, order) { } public StreamingHubFilterDescriptor(StreamingHubFilterAttribute instance, int order = 0) : base(instance, order) { } public StreamingHubFilterDescriptor(IMagicOnionFilterFactory<StreamingHubFilterAttribute> factory, int order = 0) : base(factory, order) { } } public static class MagicOnionFilterDescriptorExtensions { /// <summary> /// Adds the MagicOnion filter as type. /// </summary> /// <param name="descriptors"></param> public static void Add<T>(this IList<MagicOnionServiceFilterDescriptor> descriptors) { if (typeof(IMagicOnionFilterFactory<MagicOnionFilterAttribute>).IsAssignableFrom(typeof(T))) { var ctor = typeof(T).GetConstructors().SingleOrDefault(x => x.GetParameters().Length == 0); if (ctor == null) { throw new InvalidOperationException($"Type '{typeof(T).FullName}' has no parameter-less constructor. You can also use `Add(instance)` overload method."); } descriptors.Add(new MagicOnionServiceFilterDescriptor((IMagicOnionFilterFactory<MagicOnionFilterAttribute>)Activator.CreateInstance<T>()!)); } else if (typeof(MagicOnionFilterAttribute).IsAssignableFrom(typeof(T))) { descriptors.Add(new MagicOnionServiceFilterDescriptor(typeof(T))); } else { throw new InvalidOperationException($"Type '{typeof(T).FullName}' is not compatible with MagicOnionFilterAttribute or IMagicOnionFilterFactory<MagicOnionFilterAttribute>"); } } /// <summary> /// Adds the MagicOnion filter instance as singleton. /// </summary> /// <param name="descriptors"></param> /// <param name="filterInstance"></param> public static void Add(this IList<MagicOnionServiceFilterDescriptor> descriptors, MagicOnionFilterAttribute filterInstance) { if (filterInstance == null) throw new ArgumentNullException(nameof(filterInstance)); descriptors.Add(new MagicOnionServiceFilterDescriptor(filterInstance)); } /// <summary> /// Adds the MagicOnion filter as type. /// </summary> /// <param name="descriptors"></param> /// <param name="factory"></param> public static void Add(this IList<MagicOnionServiceFilterDescriptor> descriptors, IMagicOnionFilterFactory<MagicOnionFilterAttribute> factory) { if (factory == null) throw new ArgumentNullException(nameof(factory)); descriptors.Add(new MagicOnionServiceFilterDescriptor(factory)); } /// <summary> /// Adds the MagicOnion StreamingHub filter as type. /// </summary> /// <param name="descriptors"></param> public static void Add<T>(this IList<StreamingHubFilterDescriptor> descriptors) { if (typeof(IMagicOnionFilterFactory<StreamingHubFilterAttribute>).IsAssignableFrom(typeof(T))) { var ctor = typeof(T).GetConstructors().SingleOrDefault(x => x.GetParameters().Length == 0); if (ctor == null) { throw new InvalidOperationException($"Type '{typeof(T).FullName}' has no parameter-less constructor. You can also use `Add(instance)` overload method."); } descriptors.Add(new StreamingHubFilterDescriptor((IMagicOnionFilterFactory<StreamingHubFilterAttribute>)Activator.CreateInstance<T>()!)); } else if (typeof(StreamingHubFilterAttribute).IsAssignableFrom(typeof(T))) { descriptors.Add(new StreamingHubFilterDescriptor(typeof(T))); } else { throw new InvalidOperationException($"Type '{typeof(T).FullName}' is not compatible with StreamingHubFilterAttribute or IMagicOnionFilterFactory<StreamingHubFilterAttribute>"); } } /// <summary> /// Adds the MagicOnion StreamingHub filter instance as singleton. /// </summary> /// <param name="descriptors"></param> /// <param name="filterInstance"></param> public static void Add(this IList<StreamingHubFilterDescriptor> descriptors, StreamingHubFilterAttribute filterInstance) { if (filterInstance == null) throw new ArgumentNullException(nameof(filterInstance)); descriptors.Add(new StreamingHubFilterDescriptor(filterInstance)); } /// <summary> /// Adds the MagicOnion StreamingHub filter instance as singleton. /// </summary> /// <param name="descriptors"></param> /// <param name="factory"></param> public static void Add(this IList<StreamingHubFilterDescriptor> descriptors, IMagicOnionFilterFactory<StreamingHubFilterAttribute> factory) { if (factory == null) throw new ArgumentNullException(nameof(factory)); descriptors.Add(new StreamingHubFilterDescriptor(factory)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using WebAPI.Areas.HelpPage.ModelDescriptions; using WebAPI.Areas.HelpPage.Models; namespace WebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // DrawingTests.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2013 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using NUnit.Framework; using System.Threading; using Xwt.Drawing; using System.IO; using System.Collections.Generic; namespace Xwt { [TestFixture] public class DrawingTests: DrawingTestsBase { [Test] public void Line () { InitBlank (); context.MoveTo (1, 1.5); context.LineTo (20, 1.5); context.Stroke (); CheckImage ("Line.png"); } [Test] public void LineClosePath () { InitBlank (); context.MoveTo (1.5, 1.5); context.LineTo (20.5, 1.5); context.LineTo (20.5, 20.5); context.ClosePath (); context.Stroke (); CheckImage ("LineClosePath.png"); } [Test] public void LineWidth () { InitBlank (); context.MoveTo (10, 20.5); context.LineTo (40, 20.5); context.SetLineWidth (1); context.Stroke (); context.MoveTo (10, 25); context.LineTo (40, 25); context.SetLineWidth (2); context.Stroke (); context.MoveTo (10, 30); context.LineTo (40, 30); context.SetLineWidth (4); context.Stroke (); CheckImage ("LineWidth.png"); } [Test] public void Rectangle () { InitBlank (); context.Rectangle (1.5, 1.5, 20, 20); context.Stroke (); CheckImage ("Rectangle.png"); } [Test] public void RectanglePathConnection () { InitBlank (); context.Rectangle (5.5, 5.5, 20, 20); DrawCurrentPosition (); context.Stroke (); CheckImage ("RectanglePathConnection.png"); } [Test] public void RectangleFill () { InitBlank (); context.Rectangle (1, 1, 20, 20); context.SetColor (Colors.Blue); context.Fill (); CheckImage ("RectangleFill.png"); } [Test] public void FillPreserve () { InitBlank (); context.Rectangle (1, 1, 20, 20); context.SetColor (Colors.Yellow); context.FillPreserve (); context.SetColor (Colors.Blue); context.SetLineWidth (2); context.Stroke (); CheckImage ("FillPreserve.png"); } [Test] public void StrokePreserve () { InitBlank (); context.MoveTo (10, 25); context.LineTo (40, 25); context.SetColor (Colors.Blue); context.SetLineWidth (10); context.StrokePreserve (); context.SetLineWidth (5); context.SetColor (Colors.Yellow); context.Stroke (); CheckImage ("StrokePreserve.png"); } void DrawCurrentPosition () { context.RelMoveTo (-2.5, -3); context.RelLineTo (6, 0); context.RelLineTo (0, 6); context.RelLineTo (-6, 0); context.RelLineTo (0, -6); context.RelLineTo (6, 0); context.RelLineTo (-6, 0); context.RelMoveTo (2.5, 3); } #region Arc [Test] public void Arc () { InitBlank (); context.Arc (25, 25, 20.5, 0, 90); DrawCurrentPosition (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("Arc.png"); } [Test] public void ArcStartingNegative () { InitBlank (); context.Arc (25, 25, 20.5, -45, 45); DrawCurrentPosition (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcStartingNegative.png"); } [Test] public void ArcSwappedAngles () { InitBlank (); context.Arc (25, 25, 20.5, 300, 0); DrawCurrentPosition (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcSwappedAngles.png"); } [Test] public void ArcMultipleLoops () { InitBlank (); context.Arc (25, 25, 20.5, 0, 360 + 180); context.SetColor (Colors.Black.WithAlpha (0.5)); context.SetLineWidth (5); context.RelLineTo (10, 0); context.Stroke (); CheckImage ("ArcMultipleLoops.png"); } [Test] public void ArcFill () { InitBlank (); context.Arc (25, 25, 20, 0, 135); context.SetColor (Colors.Black); context.Fill (); CheckImage ("ArcFill.png"); } [Test] public void ArcPathConnection () { InitBlank (); context.MoveTo (25.5, 25.5); context.Arc (25.5, 25.5, 20, 0, 135); DrawCurrentPosition (); context.LineTo (25.5, 25.5); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcPathConnection.png"); } [Test] public void ArcClosePath () { InitBlank (); context.Arc (25, 25, 20.5, 0, 90); context.Arc (25, 35, 10.5, 90, 180); context.ClosePath (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcClosePath.png"); } #endregion #region ArcNegative [Test] public void ArcNegative () { InitBlank (); context.ArcNegative (25, 25, 20.5, 0, 90); DrawCurrentPosition (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcNegative.png"); } [Test] public void ArcNegativeStartingNegative () { InitBlank (); context.ArcNegative (25, 25, 20.5, -45, 45); DrawCurrentPosition (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcNegativeStartingNegative.png"); } [Test] public void ArcNegativeSwappedAngles () { InitBlank (); context.ArcNegative (25, 25, 20.5, 300, 0); DrawCurrentPosition (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcNegativeSwappedAngles.png"); } [Test] public void ArcNegativeMultipleLoops () { InitBlank (); context.ArcNegative (25, 25, 20.5, 0, 360 + 180); context.SetColor (Colors.Black.WithAlpha (0.5)); context.SetLineWidth (5); context.RelLineTo (10, 0); context.Stroke (); CheckImage ("ArcNegativeMultipleLoops.png"); } [Test] public void ArcNegativeFill () { InitBlank (); context.ArcNegative (25, 25, 20, 0, 135); context.SetColor (Colors.Black); context.Fill (); CheckImage ("ArcNegativeFill.png"); } [Test] public void ArcNegativePathConnection () { InitBlank (); context.MoveTo (25.5, 25.5); context.ArcNegative (25.5, 25.5, 20, 0, 135); DrawCurrentPosition (); context.LineTo (25.5, 25.5); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcNegativePathConnection.png"); } [Test] public void ArcNegativeClosePath () { InitBlank (); context.ArcNegative (25, 25, 20.5, 0, 180); context.ArcNegative (15, 25, 10.5, 180, 90); context.ClosePath (); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("ArcNegativeClosePath.png"); } #endregion #region ImagePattern [Test] public void ImagePattern () { InitBlank (70, 70); context.Rectangle (5, 5, 40, 60); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Fill (); CheckImage ("ImagePattern.png"); } [Test] public void ImagePatternInCircle () { InitBlank (50, 50); context.Arc (25, 25, 20, 0, 360); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Fill (); CheckImage ("ImagePatternInCircle.png"); } [Test] public void ImagePatternInTriangle () { InitBlank (50, 50); context.MoveTo (25, 5); context.LineTo (45, 20); context.LineTo (5, 45); context.ClosePath (); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Fill (); CheckImage ("ImagePatternInTriangle.png"); } [Test] public void ImagePatternWithTranslateTransform () { InitBlank (70, 70); context.Translate (5, 5); context.Rectangle (0, 0, 40, 60); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Fill (); CheckImage ("ImagePatternWithTranslateTransform.png"); } [Test] public void ImagePatternWithRotateTransform () { InitBlank (70, 70); context.Rotate (4); context.Rectangle (5, 5, 40, 60); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Fill (); CheckImage ("ImagePatternWithRotateTransform.png"); } [Test] public void ImagePatternWithScaleTransform () { InitBlank (70, 70); context.Scale (2, 0.5); context.Rectangle (5, 5, 20, 120); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Fill (); CheckImage ("ImagePatternWithScaleTransform.png"); } [Test] public void ImagePatternWithAlpha () { InitBlank (70, 70); context.Rectangle (5, 5, 40, 60); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); img = img.WithAlpha (0.5); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Fill (); CheckImage ("ImagePatternWithAlpha.png"); } [Test] public void ImagePatternWithTranslateTransformWithAlpha () { InitBlank (70, 70); context.Translate (5, 5); context.Rectangle (0, 0, 40, 60); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img.WithAlpha (0.5)); context.Fill (); CheckImage ("ImagePatternWithTranslateTransformWithAlpha.png"); } [Test] public void ImagePatternWithRotateTransformWithAlpha () { InitBlank (70, 70); context.Rotate (4); context.Rectangle (5, 5, 40, 60); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img.WithAlpha (0.5)); context.Fill (); CheckImage ("ImagePatternWithRotateTransformWithAlpha.png"); } [Test] public void ImagePatternWithScaleTransformWithAlpha () { InitBlank (70, 70); context.Scale (2, 0.5); context.Rectangle (5, 5, 20, 120); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img.WithAlpha (0.5)); context.Fill (); CheckImage ("ImagePatternWithScaleTransformWithAlpha.png"); } #endregion #region Clipping void DrawSimplePattern () { context.Rectangle (0, 0, 20, 20); context.SetColor (Colors.Red); context.Fill (); context.Rectangle (20, 0, 20, 20); context.SetColor (Colors.Blue); context.Fill (); context.Rectangle (0, 20, 20, 20); context.SetColor (Colors.Green); context.Fill (); context.Rectangle (20, 20, 20, 20); context.SetColor (Colors.Yellow); context.Fill (); } [Test] public void Clip () { InitBlank (); context.Rectangle (15, 15, 20, 20); context.Clip (); DrawSimplePattern (); CheckImage ("Clip.png"); } [Test] public void ClipAccumulated () { InitBlank (); context.Rectangle (15, 15, 20, 20); context.Clip (); context.Rectangle (0, 0, 20, 20); context.Clip (); DrawSimplePattern (); CheckImage ("ClipAccumulated.png"); } [Test] public void ClipPreserve () { InitBlank (); DrawSimplePattern (); context.Rectangle (15, 15, 20, 20); context.ClipPreserve (); context.SetColor (Colors.Violet); context.Fill (); CheckImage ("ClipPreserve.png"); } [Test] public void ClipSaveRestore () { InitBlank (); context.Rectangle (15, 15, 20, 20); context.Clip (); context.Save (); context.Rectangle (0, 0, 20, 20); context.Clip (); context.Restore (); DrawSimplePattern (); CheckImage ("ClipSaveRestore.png"); } #endregion [Test] public void NewPath () { InitBlank (); context.MoveTo (1, 1.5); context.LineTo (20, 1.5); context.NewPath (); context.MoveTo (0, 0); context.LineTo (20, 20); context.Stroke (); CheckImage ("NewPath.png"); } #region LinearGradient [Test] public void LinearGradient () { InitBlank (); var g = new LinearGradient (5, 5, 5, 45); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Rectangle (5, 5, 40, 40); context.Pattern = g; context.Fill (); CheckImage ("LinearGradient.png"); } [Test] public void LinearGradientDiagonal () { InitBlank (); var g = new LinearGradient (5, 5, 45, 45); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Rectangle (5, 5, 40, 40); context.Pattern = g; context.Fill (); CheckImage ("LinearGradientDiagonal.png"); } [Test] public void LinearGradientReverse () { InitBlank (); var g = new LinearGradient (5, 45, 5, 5); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Rectangle (5, 5, 40, 40); context.Pattern = g; context.Fill (); CheckImage ("LinearGradientReverse.png"); } [Test] public void LinearGradientInternalBox () { InitBlank (); var g = new LinearGradient (25, 15, 35, 35); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Rectangle (5, 5, 40, 40); context.Pattern = g; context.Fill (); CheckImage ("LinearGradientInternalBox.png"); } #endregion #region RadialGradient [Test] public void RadialGradient () { InitBlank (); var g = new RadialGradient (20, 20, 5, 30, 30, 30); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Rectangle (5, 5, 40, 40); context.Pattern = g; context.Fill (); CheckImage ("RadialGradient.png"); } [Test] public void RadialGradientReverse () { InitBlank (); var g = new RadialGradient (20, 20, 30, 30, 25, 5); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Rectangle (5, 5, 40, 40); context.Pattern = g; context.Fill (); CheckImage ("RadialGradientReverse.png"); } [Test] public void RadialGradientSmall () { InitBlank (); var g = new RadialGradient (5, 5, 5, 30, 30, 15); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Rectangle (5, 5, 40, 40); context.Pattern = g; context.Fill (); CheckImage ("RadialGradientSmall.png"); } #endregion #region Curves [Test] public void Curve () { InitBlank (70,70); context.MoveTo (5, 35); context.CurveTo (35, 5, 35, 65, 65, 35); context.Stroke (); CheckImage ("Curve.png"); } [Test] public void CurvePathConnection () { InitBlank (70,70); context.MoveTo (0, 0); context.LineTo (5, 35); context.CurveTo (35, 5, 35, 65, 65, 35); context.LineTo (70, 70); context.Stroke (); CheckImage ("CurvePathConnection.png"); } [Test] public void CurveFillWithHoles () { InitBlank (70, 70); // Curve 1 context.MoveTo (5, 35); context.CurveTo (20, 0, 50, 0, 60, 25); // curve2 with lineTo; curve1 is closed context.LineTo (5, 5); context.CurveTo (20, 30, 50, 30, 60, 5); context.ClosePath (); context.SetColor (Colors.Black); context.StrokePreserve (); context.SetColor (Colors.LightGray); context.Fill (); CheckImage ("CurveFillWithHoles.png"); } [Test] public void CurveClosePath () { InitBlank (100,100); context.MoveTo (5, 20); context.CurveTo (35, 5, 35, 65, 65, 20); context.CurveTo (70, 25, 60, 40, 45, 65); context.ClosePath (); context.Stroke (); CheckImage ("CurveClosePath.png"); } #endregion #region Save/Restore [Test] public void SaveRestorePath () { // Path is not saved InitBlank (); context.SetLineWidth (2); context.MoveTo (10, 10); context.LineTo (40, 10); context.Save (); context.LineTo (40, 40); context.Restore (); context.LineTo (10, 40); context.SetColor (Colors.Black); context.Stroke (); CheckImage ("SaveRestorePath.png"); } [Test] public void SaveRestoreColor () { // Color is saved InitBlank (); context.Rectangle (10, 10, 20, 20); context.SetColor (Colors.Black); context.Save (); context.SetColor (Colors.Red); context.Restore (); context.Fill (); CheckImage ("SaveRestoreColor.png"); } [Test] public void SaveRestoreImagePattern () { // Pattern is saved InitBlank (70, 70); context.Save (); var img = ReferenceImageManager.LoadReferenceImage ("pattern-sample.png"); context.Pattern = new Xwt.Drawing.ImagePattern (img); context.Restore (); context.Rectangle (5, 5, 40, 60); context.Fill (); CheckImage ("SaveRestoreImagePattern.png"); } [Test] public void SaveRestoreLinearGradient () { // Pattern is saved InitBlank (); var g = new LinearGradient (5, 5, 5, 45); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Save (); context.Pattern = g; context.Restore (); context.Rectangle (5, 5, 40, 40); context.Fill (); CheckImage ("SaveRestoreLinearGradient.png"); } [Test] public void SaveRestoreRadialGradient () { // Pattern is saved InitBlank (); var g = new RadialGradient (20, 20, 5, 30, 30, 30); g.AddColorStop (0, Colors.Red); g.AddColorStop (0.5, Colors.Green); g.AddColorStop (1, Colors.Blue); context.Save (); context.Pattern = g; context.Restore (); context.Rectangle (5, 5, 40, 40); context.Fill (); CheckImage ("SaveRestoreRadialGradient.png"); } [Test] public void SaveRestoreLineWidth () { // Line width is saved InitBlank (); context.SetLineWidth (2); context.Save (); context.SetLineWidth (8); context.Restore (); context.Rectangle (10, 10, 30, 30); context.Stroke (); CheckImage ("SaveRestoreLineWidth.png"); } [Test] public void SaveRestoreTransform () { // Transform is saved InitBlank (); context.Save (); context.Translate (10, 10); context.Rotate (10); context.Scale (0.5, 0.5); context.Restore (); context.Rectangle (10, 10, 30, 30); context.Fill (); CheckImage ("SaveRestoreTransform.png"); } #endregion #region Text [Test] public void Text () { // Transform is saved InitBlank (100, 50); var la = new TextLayout (); la.Font = Font.FromName ("Arial 12"); la.Text = "Hello World"; context.DrawTextLayout (la, 5, 5); CheckImage ("Text.png"); } [Test] public void TextSize () { // Transform is saved InitBlank (100, 50); var la = new TextLayout (); la.Font = Font.FromName ("Arial 12"); la.Text = "Hello World"; var s = la.GetSize (); context.Rectangle (10.5, 10.5, s.Width, s.Height); context.SetColor (Colors.Blue); context.Stroke (); context.SetColor (Colors.Black); context.DrawTextLayout (la, 10, 10); CheckImage ("TextSize.png"); } [Test] public void TextLineBreak () { // Transform is saved InitBlank (100, 50); var la = new TextLayout (); la.Font = Font.FromName ("Arial 12"); la.Text = "Hello\nWorld"; var s = la.GetSize (); context.Rectangle (10.5, 10.5, s.Width, s.Height); context.SetColor (Colors.Blue); context.Stroke (); context.SetColor (Colors.Black); context.DrawTextLayout (la, 10, 10); CheckImage ("TextLineBreak.png"); } [Test] public void TextWithBlankLines () { // Transform is saved InitBlank (50, 150); var la = new TextLayout (); la.Font = Font.FromName ("Arial 12"); la.Text = "\n\nHello\n\n\nWorld\n\n"; var s = la.GetSize (); context.Rectangle (10.5, 10.5, s.Width, s.Height); context.SetColor (Colors.Blue); context.Stroke (); context.SetColor (Colors.Black); context.DrawTextLayout (la, 10, 10); CheckImage ("TextWithBlankLines.png"); } [Test] public void TextWordWrap () { // Transform is saved InitBlank (100, 100); var la = new TextLayout (); la.Font = Font.FromName ("Arial 12"); la.Text = "One Two Three Four Five Six Seven Eight Nine"; la.Width = 90; la.Trimming = TextTrimming.Word; var s = la.GetSize (); context.Rectangle (5.5, 5.5, s.Width, s.Height); context.SetColor (Colors.Blue); context.Stroke (); context.SetColor (Colors.Black); context.DrawTextLayout (la, 5, 5); CheckImage ("TextWordWrap.png"); } [Test] public void TextTrimmingEllipsis () { // Transform is saved InitBlank (50, 100); var la = new TextLayout (); la.Font = Font.FromName ("Arial 12"); la.Text = "One Two Three Four Five Six Seven Eight Nine"; la.Width = 45; la.Trimming = TextTrimming.WordElipsis; var s = la.GetSize (); context.Rectangle (5.5, 5.5, s.Width, s.Height); context.SetColor (Colors.Blue); context.Stroke (); context.SetColor (Colors.Black); context.DrawTextLayout (la, 5, 5); CheckImage ("TextTrimmingEllipsis.png"); } #endregion #region Paths [Test] public void DrawPathTwoTimes () { InitBlank (50, 50); var p = new DrawingPath (); p.Rectangle (15, 15, 20, 20); p.Rectangle (20, 20, 10, 10); context.AppendPath (p); context.Stroke (); context.Rotate (15); context.AppendPath (p); context.Stroke (); CheckImage ("DrawPathTwoTimes.png"); } #endregion #region Hit test checking [Test] public void DrawingPathPointInFill () { DrawingPath p = new DrawingPath (); p.Rectangle (10, 10, 20, 20); Assert.IsTrue (p.IsPointInFill (15, 15)); Assert.IsFalse (p.IsPointInFill (9, 9)); } [Test] public void ContextPointInStroke () { InitBlank (50, 50); context.Rectangle (10, 10, 20, 20); context.SetLineWidth (3); Assert.IsTrue (context.IsPointInStroke (10, 10)); Assert.IsTrue (context.IsPointInStroke (11, 11)); Assert.IsFalse (context.IsPointInStroke (15, 15)); context.MoveTo (15, 15); context.RelLineTo (5, 0); Assert.IsTrue (context.IsPointInStroke (15, 15)); } [Test] public void ContextPointInFillWithTransform () { InitBlank (50, 50); context.Translate (50, 50); context.Rectangle (10, 10, 20, 20); context.SetLineWidth (3); Assert.IsTrue (context.IsPointInStroke (10, 10)); Assert.IsTrue (context.IsPointInStroke (11, 11)); Assert.IsFalse (context.IsPointInStroke (15, 15)); Assert.IsTrue (context.IsPointInFill (15, 15)); Assert.IsFalse (context.IsPointInFill (9, 9)); context.Translate (50, 50); Assert.IsTrue (context.IsPointInStroke (-40, -40)); Assert.IsTrue (context.IsPointInStroke (-41, -41)); Assert.IsFalse (context.IsPointInStroke (-45, -45)); Assert.IsTrue (context.IsPointInFill (-35, -35)); Assert.IsFalse (context.IsPointInFill (15, 15)); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using EFSqlTranslator.Translation.DbObjects; using EFSqlTranslator.Translation.Extensions; using EFSqlTranslator.Translation.MethodTranslators; namespace EFSqlTranslator.Translation { public class ExpressionTranslator : ExpressionVisitor { private readonly IModelInfoProvider _infoProvider; private readonly IDbObjectFactory _dbFactory; private readonly TranslationState _state; private readonly UniqueNameGenerator _nameGenerator = new UniqueNameGenerator(); private readonly TranslationPlugIns _plugIns = new TranslationPlugIns(); public ExpressionTranslator( IModelInfoProvider infoProvider, IDbObjectFactory dbFactory, TranslationState state = null, IEnumerable<AbstractMethodTranslator> methodTranslators = null) { _infoProvider = infoProvider; _dbFactory = dbFactory; _state = state ?? new TranslationState(); RegisterDefaultPlugIns(); if (methodTranslators == null) return; foreach (var translator in methodTranslators) translator.Register(_plugIns); } private void RegisterDefaultPlugIns() { new WhereTranslator(_infoProvider, _dbFactory).Register(_plugIns); new AnyTranslator(_infoProvider, _dbFactory).Register(_plugIns); new JoinTranslator(_infoProvider, _dbFactory).Register(_plugIns); new GroupByTranslator(_infoProvider, _dbFactory).Register(_plugIns); new OrderByTranslator(_infoProvider, _dbFactory).Register(_plugIns); new SelectTranslator(_infoProvider, _dbFactory).Register(_plugIns); new CountTranslator(_infoProvider, _dbFactory).Register(_plugIns); new AggregationTranslator(_infoProvider, _dbFactory).Register(_plugIns); new StringStartsEndsTranslator(_infoProvider, _dbFactory).Register(_plugIns); new ContainsTranslator(_infoProvider, _dbFactory).Register(_plugIns); new InTranslator(_infoProvider, _dbFactory).Register(_plugIns); new LimitTranslator(_infoProvider, _dbFactory).Register(_plugIns); new DistinctTranslator(_infoProvider, _dbFactory).Register(_plugIns); new DistinctCountTranslator(_infoProvider, _dbFactory).Register(_plugIns); } internal IDbObject GetElement() { return _state.ResultStack.Peek(); } public override Expression Visit(Expression e) { return base.Visit(e); } protected override Expression VisitConstant(ConstantExpression c) { var entityInfo = _infoProvider.FindEntityInfo(c.Type); if (entityInfo != null) { var dbTable = _dbFactory.BuildTable(entityInfo); var dbRef = _dbFactory.BuildRef(dbTable); var dbSelect = _dbFactory.BuildSelect(dbRef); dbRef.Alias = _nameGenerator.GenerateAlias(dbSelect, dbTable.TableName); _state.ResultStack.Push(dbSelect); } else if (!c.Type.IsAnonymouse()) { var dbConstant = _dbFactory.BuildConstant(c.Value, true); _state.ResultStack.Push(dbConstant); } return c; } protected override Expression VisitNew(NewExpression n) { var list = _dbFactory.BuildList<DbKeyValue>(); if (n.Members != null) { for (var i = 0; i < n.Members.Count; i++) { var member = n.Members[i]; var assignment = n.Arguments[i]; Visit(assignment); var dbObj = _state.ResultStack.Pop(); var dbKeyValue = _dbFactory.BuildKeyValue(member.Name, dbObj); list.Add(dbKeyValue); } _state.ResultStack.Push(list); return n; } _state.ResultStack.Push(list); return base.VisitNew(n); } protected override MemberAssignment VisitMemberAssignment(MemberAssignment ma) { var list = (IDbList<DbKeyValue>)_state.ResultStack.Pop(); var member = ma.Member; var assignment = ma.Expression; Visit(assignment); var dbObj = _state.ResultStack.Pop(); var dbKeyValue = _dbFactory.BuildKeyValue(member.Name, dbObj); list.Add(dbKeyValue); _state.ResultStack.Push(list); return ma; } protected override Expression VisitParameter(ParameterExpression p) { return VisitParameterInteral(p, false); } private Expression VisitParameterInteral(ParameterExpression p, bool ignoreParamStack) { DbReference dbRef = null; if (p.Type.IsAnonymouse() || p.Type.IsGrouping()) { var dbSelect = _state.GetLastSelect(); dbRef = _dbFactory.BuildRef(null); dbRef.OwnerSelect = dbSelect; var collection = p.Type.IsGrouping() ? dbSelect.GroupBys.AsEnumerable() : dbSelect.Selection; foreach (var selectable in collection) dbRef.RefSelection[selectable.GetAliasOrName()] = selectable; } if (dbRef == null && !ignoreParamStack && _state.ParamterStack.Count > 0) { var dbRefs = _state.ParamterStack.Peek(); if (dbRefs.ContainsKey(p)) dbRef = dbRefs[p]; } // if we can not find the parameter expression in the ParamterStack, // it means this is the first time we translates the parameter, so we // need to look for it in the most recently translated select // this is required because we may not always has select on the top // of the stack, especially we translating arguments for method calls if (dbRef == null) { var dbSelect = _state.GetLastSelect(); var refCol = (_state.ResultStack.Peek() as IDbRefColumn) ?? dbSelect.Selection.OfType<IDbRefColumn>().LastOrDefault(); dbRef = refCol != null ? refCol.Ref : dbSelect.From; } if (dbRef == null) throw new NullReferenceException(); _state.ResultStack.Push(dbRef); return p; } protected override Expression VisitMember(MemberExpression m) { var expression = Visit(m.Expression); if (expression is ConstantExpression constExpr) { var container = constExpr.Value; var member = m.Member; object value = null; var valueRetrieved = false; switch (member) { case FieldInfo field: value = field.GetValue(container); valueRetrieved = true; break; case PropertyInfo prop: value = prop.GetValue(container, null); valueRetrieved = true; break; } if (valueRetrieved) { var dbObject = _dbFactory.BuildConstant(value, true); _state.ResultStack.Push(dbObject); return m; } } var typeInfo = m.Type.GetTypeInfo(); if (m.Expression.Type.IsAnonymouse()) { var dbRef = (DbReference)_state.ResultStack.Peek(); if (dbRef.RefSelection.ContainsKey(m.Member.Name)) { var dbObj = dbRef.RefSelection[m.Member.Name]; // pop out the dbRef from the stack, it was the result of // translate a parameter, and it is not required for following translation _state.ResultStack.Pop(); _state.ResultStack.Push(dbObj); return m; } } if (m.Expression.Type.IsGrouping()) { var dbRef = (DbReference)_state.ResultStack.Pop(); var dbSelect = dbRef.OwnerSelect; if (dbSelect.GroupBys.IsSingleKey) { var kColumn = dbSelect.GroupBys.Single(); _state.ResultStack.Push(kColumn); } else { _state.ResultStack.Push(dbRef); } return m; } // if the member is a queryable entity, we need to translate it // into a relation, which means a join var entityInfo = _infoProvider.FindEntityInfo(m.Type); if (entityInfo != null) { var dbObj = _state.ResultStack.Pop(); var refCol = dbObj as IDbRefColumn; var fromRef = refCol != null ? refCol.Ref : (DbReference)dbObj; var fromEntity = _infoProvider.FindEntityInfo(m.Expression.Type); var relation = fromEntity.GetRelation(m.Member.Name); var dbJoin = GetOrCreateJoin(relation, fromRef, refCol ?? fromRef.ReferredRefColumn); // RefColumnAlias is used as alias in case we need to create a ref column for this dbRef dbJoin.To.RefColumnAlias = m.Member.Name; if (refCol != null) { refCol = _dbFactory.BuildRefColumn(dbJoin.To, m.Member.Name); if (dbJoin.To.Referee is IDbSelect subSelect) refCol.RefTo = subSelect.Selection.OfType<IDbRefColumn>().Single(); _state.ResultStack.Push(refCol); return m; } _state.ResultStack.Push(relation.IsChildRelation ? dbJoin.To.Referee : dbJoin.To); return m; } if (typeInfo.Namespace.StartsWith("System")) { var dbObj = _state.ResultStack.Pop(); var refCol = dbObj as IDbRefColumn; var dbRef = refCol != null ? refCol.Ref : (DbReference)dbObj; var fieldInfo = _infoProvider.FindFieldInfo(m.Member); var col = _dbFactory.BuildColumn(dbRef, fieldInfo.DbName, fieldInfo.ValType); _state.ResultStack.Push(col); // if we create a column whose DbRef is using by a RefColumn // we need to make sure the column is added to the ref column's owner select // This normally happen when we are accessing a column from a child relation refCol = refCol ?? dbRef.ReferredRefColumn; // if the ref column is not now, and it is referring another ref column // we need to make sure the column we translated is in the sub select which // owns the ref column that referred by the current refColumn refCol?.RefTo?.AddToReferedSelect(_dbFactory, fieldInfo.DbName, fieldInfo.ValType); return m; } return base.VisitMember(m); } /// Create a join for the relation /// For parent relation, we create a join that joins to the parent table /// For child relation, we will create a sub select that returns the child table, /// and then joins to the sub select. /// The reason for joining to sub select for child relation, is that we want to be /// able to group on the join key, so that we will not repeat the parent row. private IDbJoin GetOrCreateJoin(EntityRelation relation, DbReference fromRef, IDbRefColumn refCol) { var dbSelect = fromRef.OwnerSelect; var tupleKey = Tuple.Create(dbSelect, relation); if (!relation.IsChildRelation && _state.CreatedJoins.ContainsKey(tupleKey)) return _state.CreatedJoins[tupleKey]; var toEntity = relation.ToEntity; var dbTable = _dbFactory.BuildTable(toEntity); DbReference joinTo; DbReference childRef = null; IDbSelect childSelect = null; // Create the join. For parent join, we just need to join to a Ref to the table // For child relation, we will firstly create a sub select that return the child table // and then join to then sub select if (!relation.IsChildRelation) { var tableAlias = _nameGenerator.GenerateAlias(dbSelect, dbTable.TableName); joinTo = _dbFactory.BuildRef(dbTable, tableAlias); } else { childRef = _dbFactory.BuildRef(dbTable); childSelect = _dbFactory.BuildSelect(childRef); childRef.Alias = _nameGenerator.GenerateAlias(childSelect, dbTable.TableName); var tableAlias = _nameGenerator.GenerateAlias(dbSelect, TranslationConstants.SubSelectPrefix, true); joinTo = _dbFactory.BuildRef(childSelect, tableAlias); } var dbJoin = _dbFactory.BuildJoin(joinTo, dbSelect); dbSelect.Joins.Add(dbJoin); // build join condition IDbBinary condition = null; for (var i = 0; i < relation.FromKeys.Count; i++) { var fromKey = relation.FromKeys[i]; var toKey = relation.ToKeys[i]; var fromColumn = _dbFactory.BuildColumn(fromRef, fromKey.DbName, fromKey.ValType); var toColumn = _dbFactory.BuildColumn(joinTo, toKey.DbName, toKey.ValType); // If we have created a sub for child relation, we need to the columns // that are used in join condition selected from the sub select. if (childRef != null && childSelect != null) { var alias = _nameGenerator.GenerateAlias(childSelect, toKey.DbName + TranslationConstants.JoinKeySuffix, true); var childColumn = _dbFactory.BuildColumn(childRef, toKey.DbName, toKey.ValType, alias, true); /** * We need to also put the join key in the group of the sub select. * This is to make sure the sub select is grouped by the key so that * the parent (outer select) will not be repeated * This operation needs to happen here not in the aggregation method call. * The reason is that in aggregtion method calls we do not know which column * from the entity is used in relation, so they will not be able to create * the correct column */ childSelect.Selection.Add(_dbFactory.BuildRefColumn(childRef)); childSelect.Selection.Add(childColumn); childSelect.GroupBys.Add(childColumn); toColumn.Name = alias; toColumn.Alias = string.Empty; } // if the relation is found on a fromRef which is referring a sub-select, // it means the from key of the join is not on a table but a derived select. // In this case, we need to add the from key into the derived select, as we will // be using it in the join if (fromRef.Referee is IDbSelect) { var alias = _nameGenerator.GenerateAlias(dbSelect, toKey.DbName + TranslationConstants.JoinKeySuffix, true); fromColumn.Name = alias; fromColumn.Alias = string.Empty; // try to recursively add the join key to all connected sub select. refCol.RefTo?.AddToReferedSelect(_dbFactory, fromKey.DbName, fromKey.ValType, alias); } var binary = _dbFactory.BuildBinary(fromColumn, DbOperator.Equal, toColumn); condition = condition.UpdateBinary(binary, _dbFactory); } dbJoin.Condition = condition; // all relations need to follow the join type if (fromRef.OwnerJoin != null) dbJoin.Type = fromRef.OwnerJoin.Type; if (relation.IsChildRelation) dbJoin.Type = DbJoinType.LeftOuter; return _state.CreatedJoins[tupleKey] = dbJoin; } protected override Expression VisitMethodCall(MethodCallExpression m) { var caller = m.GetCaller(); var args = m.GetArguments(); Visit(caller); // remove unneed DbReference from stack, this is a side effect of translation of the caller // we need to translate the caller to have the required select on the stack // but we dont neeed other thing that come with it, such as the DbReference while (_state.ResultStack.Count > 0 && _state.ResultStack.Peek() is DbReference) _state.ResultStack.Pop(); VistMethodArguments(args); if (!_plugIns.TranslateMethodCall(m, _state, _nameGenerator)) throw new NotSupportedException(); return m; } private void VistMethodArguments(Expression[] args) { if (args == null) throw new ArgumentNullException(nameof(args)); foreach (var argExpr in args) Visit(argExpr); } protected override Expression VisitLambda<T>(Expression<T> l) { var pList = new Dictionary<ParameterExpression, DbReference>(); // the order of the parameters need to be reversed, as the first // query that be translated will be at the bottom of the stack, and the query // for the last parameter will be at the top var results = new Stack<IDbObject>(); foreach (var p in l.Parameters.Reverse()) { VisitParameterInteral(p, true); var dbRef = (DbReference)_state.ResultStack.Pop(); pList[p] = dbRef; // pop out used select for the parameter just translated // so that the next parameter will be assigned with current select while (_state.ResultStack.Count > 0) { var dbObj = _state.ResultStack.Pop(); results.Push(dbObj); if (dbObj is IDbSelect) break; } } while (results.Count > 0) _state.ResultStack.Push(results.Pop()); _state.ParamterStack.Push(pList); Visit(l.Body); _state.ParamterStack.Pop(); return l; } protected override Expression VisitBinary(BinaryExpression b) { Visit(b.Left); var left = _state.ResultStack.Pop(); Visit(b.Right); var right = _state.ResultStack.Pop(); var dbOptr = _dbFactory.GetDbOperator(b.NodeType, b.Left.Type, b.Right.Type); if (left.IsNullVal() || right.IsNullVal()) { dbOptr = dbOptr == DbOperator.Equal ? DbOperator.Is : dbOptr == DbOperator.NotEqual ? DbOperator.IsNot : dbOptr; } var dbBinary = _dbFactory.BuildBinary(left, dbOptr, right); if (dbOptr == DbOperator.Or) { var dbRefs = dbBinary.GetOperands().OfType<IDbSelectable>().Select(s => s.Ref); foreach (var dbRef in dbRefs) SqlTranslationHelper.UpdateJoinType(dbRef); } _state.ResultStack.Push(dbBinary); return b; } protected override Expression VisitUnary(UnaryExpression node) { if (node.NodeType == ExpressionType.Not) { var expression = Visit(node.Operand); var dbElement = _state.ResultStack.Pop(); var one = _dbFactory.BuildConstant(true); var dbBinary = _dbFactory.BuildBinary(dbElement, DbOperator.NotEqual, one); _state.ResultStack.Push(dbBinary); return expression; } return base.VisitUnary(node); } } }
namespace Umbraco.Cms.Core { public static partial class Constants { /// <summary> /// Defines the identifiers for property-type alias conventions that are used within the Umbraco core. /// </summary> public static class Conventions { public static class Migrations { public const string UmbracoUpgradePlanName = "Umbraco.Core"; public const string KeyValuePrefix = "Umbraco.Core.Upgrader.State+"; public const string UmbracoUpgradePlanKey = KeyValuePrefix + UmbracoUpgradePlanName; } public static class PermissionCategories { public const string ContentCategory = "content"; public const string AdministrationCategory = "administration"; public const string StructureCategory = "structure"; public const string OtherCategory = "other"; } public static class PublicAccess { public const string MemberUsernameRuleType = "MemberUsername"; public const string MemberRoleRuleType = "MemberRole"; } public static class DataTypes { public const string ListViewPrefix = "List View - "; } /// <summary> /// Constants for Umbraco Content property aliases. /// </summary> public static class Content { /// <summary> /// Property alias for the Content's Url (internal) redirect. /// </summary> public const string InternalRedirectId = "umbracoInternalRedirectId"; /// <summary> /// Property alias for the Content's navigational hide, (not actually used in core code). /// </summary> public const string NaviHide = "umbracoNaviHide"; /// <summary> /// Property alias for the Content's Url redirect. /// </summary> public const string Redirect = "umbracoRedirect"; /// <summary> /// Property alias for the Content's Url alias. /// </summary> public const string UrlAlias = "umbracoUrlAlias"; /// <summary> /// Property alias for the Content's Url name. /// </summary> public const string UrlName = "umbracoUrlName"; } /// <summary> /// Constants for Umbraco Media property aliases. /// </summary> public static class Media { /// <summary> /// Property alias for the Media's file name. /// </summary> public const string File = "umbracoFile"; /// <summary> /// Property alias for the Media's width. /// </summary> public const string Width = "umbracoWidth"; /// <summary> /// Property alias for the Media's height. /// </summary> public const string Height = "umbracoHeight"; /// <summary> /// Property alias for the Media's file size (in bytes). /// </summary> public const string Bytes = "umbracoBytes"; /// <summary> /// Property alias for the Media's file extension. /// </summary> public const string Extension = "umbracoExtension"; /// <summary> /// The default height/width of an image file if the size can't be determined from the metadata /// </summary> public const int DefaultSize = 200; } /// <summary> /// Defines the alias identifiers for Umbraco media types. /// </summary> public static class MediaTypes { /// <summary> /// MediaType alias for a file. /// </summary> public const string File = "File"; /// <summary> /// MediaType alias for a folder. /// </summary> public const string Folder = "Folder"; /// <summary> /// MediaType alias for an image. /// </summary> public const string Image = "Image"; /// <summary> /// MediaType name for a video. /// </summary> public const string Video = "Video"; /// <summary> /// MediaType name for an audio. /// </summary> public const string Audio = "Audio"; /// <summary> /// MediaType name for an article. /// </summary> public const string Article = "Article"; /// <summary> /// MediaType name for vector graphics. /// </summary> public const string VectorGraphics = "VectorGraphics"; /// <summary> /// MediaType alias for a video. /// </summary> public const string VideoAlias = "umbracoMediaVideo"; /// <summary> /// MediaType alias for an audio. /// </summary> public const string AudioAlias = "umbracoMediaAudio"; /// <summary> /// MediaType alias for an article. /// </summary> public const string ArticleAlias = "umbracoMediaArticle"; /// <summary> /// MediaType alias for vector graphics. /// </summary> public const string VectorGraphicsAlias = "umbracoMediaVectorGraphics"; /// <summary> /// MediaType alias indicating allowing auto-selection. /// </summary> public const string AutoSelect = "umbracoAutoSelect"; } /// <summary> /// Constants for Umbraco Member property aliases. /// </summary> public static class Member { /// <summary> /// if a role starts with __umbracoRole we won't show it as it's an internal role used for public access /// </summary> public static readonly string InternalRolePrefix = "__umbracoRole"; /// <summary> /// Property alias for the Comments on a Member /// </summary> public const string Comments = "umbracoMemberComments"; public const string CommentsLabel = "Comments"; /// <summary> /// Property alias for the Approved boolean of a Member /// </summary> public const string IsApproved = "umbracoMemberApproved"; public const string IsApprovedLabel = "Is Approved"; /// <summary> /// Property alias for the Locked out boolean of a Member /// </summary> public const string IsLockedOut = "umbracoMemberLockedOut"; public const string IsLockedOutLabel = "Is Locked Out"; /// <summary> /// Property alias for the last date the Member logged in /// </summary> public const string LastLoginDate = "umbracoMemberLastLogin"; public const string LastLoginDateLabel = "Last Login Date"; /// <summary> /// Property alias for the last date a Member changed its password /// </summary> public const string LastPasswordChangeDate = "umbracoMemberLastPasswordChangeDate"; public const string LastPasswordChangeDateLabel = "Last Password Change Date"; /// <summary> /// Property alias for the last date a Member was locked out /// </summary> public const string LastLockoutDate = "umbracoMemberLastLockoutDate"; public const string LastLockoutDateLabel = "Last Lockout Date"; /// <summary> /// Property alias for the number of failed login attempts /// </summary> public const string FailedPasswordAttempts = "umbracoMemberFailedPasswordAttempts"; public const string FailedPasswordAttemptsLabel = "Failed Password Attempts"; /// <summary> /// The standard properties group alias for membership properties. /// </summary> public const string StandardPropertiesGroupAlias = "membership"; /// <summary> /// The standard properties group name for membership properties. /// </summary> public const string StandardPropertiesGroupName = "Membership"; } /// <summary> /// Defines the alias identifiers for Umbraco member types. /// </summary> public static class MemberTypes { /// <summary> /// MemberType alias for default member type. /// </summary> public const string DefaultAlias = "Member"; public const string SystemDefaultProtectType = "_umbracoSystemDefaultProtectType"; public const string AllMembersListId = "all-members"; } /// <summary> /// Constants for Umbraco URLs/Querystrings. /// </summary> public static class Url { /// <summary> /// Querystring parameter name used for Umbraco's alternative template functionality. /// </summary> public const string AltTemplate = "altTemplate"; } /// <summary> /// Defines the alias identifiers for built-in Umbraco relation types. /// </summary> public static class RelationTypes { /// <summary> /// Name for default relation type "Related Media". /// </summary> public const string RelatedMediaName = "Related Media"; /// <summary> /// Alias for default relation type "Related Media" /// </summary> public const string RelatedMediaAlias = "umbMedia"; /// <summary> /// Name for default relation type "Related Document". /// </summary> public const string RelatedDocumentName = "Related Document"; /// <summary> /// Alias for default relation type "Related Document" /// </summary> public const string RelatedDocumentAlias = "umbDocument"; /// <summary> /// Name for default relation type "Relate Document On Copy". /// </summary> public const string RelateDocumentOnCopyName = "Relate Document On Copy"; /// <summary> /// Alias for default relation type "Relate Document On Copy". /// </summary> public const string RelateDocumentOnCopyAlias = "relateDocumentOnCopy"; /// <summary> /// Name for default relation type "Relate Parent Document On Delete". /// </summary> public const string RelateParentDocumentOnDeleteName = "Relate Parent Document On Delete"; /// <summary> /// Alias for default relation type "Relate Parent Document On Delete". /// </summary> public const string RelateParentDocumentOnDeleteAlias = "relateParentDocumentOnDelete"; /// <summary> /// Name for default relation type "Relate Parent Media Folder On Delete". /// </summary> public const string RelateParentMediaFolderOnDeleteName = "Relate Parent Media Folder On Delete"; /// <summary> /// Alias for default relation type "Relate Parent Media Folder On Delete". /// </summary> public const string RelateParentMediaFolderOnDeleteAlias = "relateParentMediaFolderOnDelete"; /// <summary> /// Returns the types of relations that are automatically tracked /// </summary> /// <remarks> /// Developers should not manually use these relation types since they will all be cleared whenever an entity /// (content, media or member) is saved since they are auto-populated based on property values. /// </remarks> public static string[] AutomaticRelationTypes { get; } = new[] { RelatedMediaAlias, RelatedDocumentAlias }; //TODO: return a list of built in types so we can use that to prevent deletion in the uI } } } }
using System; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using System.IO; using System.Drawing; using BizHawk.Common; using BizHawk.Client.Common; using BizHawk.Client.EmuHawk; using BizHawk.Client.EmuHawk.FilterManager; using BizHawk.Bizware.BizwareGL; using BizHawk.Bizware.BizwareGL.Drivers.OpenTK; using OpenTK; using OpenTK.Graphics; namespace BizHawk.Client.EmuHawk.Filters { /// <summary> /// applies letterboxing logic to figure out how to fit the source dimensions into the target dimensions. /// In the future this could also apply rules like integer-only scaling, etc. /// </summary> class LetterboxingLogic { /// <summary> /// the location within the destination region of the output content (scaled and translated) /// </summary> public int vx, vy, vw, vh; /// <summary> /// the scale factor eventually used /// </summary> public float WidthScale, HeightScale; /// <summary> /// In case you want to do it yourself /// </summary> public LetterboxingLogic() { } //do maths on the viewport and the native resolution and the user settings to get a display rectangle public LetterboxingLogic(bool maintainAspect, bool maintainInteger, int targetWidth, int targetHeight, int sourceWidth, int sourceHeight, Size textureSize, Size virtualSize) { int textureWidth = textureSize.Width; int textureHeight = textureSize.Height; int virtualWidth = virtualSize.Width; int virtualHeight = virtualSize.Height; //zero 02-jun-2014 - we passed these in, but ignored them. kind of weird.. int oldSourceWidth = sourceWidth; int oldSourceHeight = sourceHeight; sourceWidth = (int)virtualWidth; sourceHeight = (int)virtualHeight; //this doesnt make sense if (!maintainAspect) maintainInteger = false; float widthScale = (float)targetWidth / sourceWidth; float heightScale = (float)targetHeight / sourceHeight; if (maintainAspect //zero 20-jul-2014 - hacks upon hacks, this function needs rewriting && !maintainInteger ) { if (widthScale > heightScale) widthScale = heightScale; if (heightScale > widthScale) heightScale = widthScale; } if (maintainInteger) { //just totally different code //apply the zooming algorithm (pasted and reworked, for now) //ALERT COPYPASTE LAUNDROMAT Vector2 VS = new Vector2(virtualWidth, virtualHeight); Vector2 BS = new Vector2(textureWidth, textureHeight); Vector2 AR = Vector2.Divide(VS, BS); float target_par = (AR.X / AR.Y); Vector2 PS = new Vector2(1, 1); //this would malfunction for AR <= 0.5 or AR >= 2.0 for(;;) { //TODO - would be good not to run this per frame.... Vector2[] trials = new[] { PS + new Vector2(1, 0), PS + new Vector2(0, 1), PS + new Vector2(1, 1) }; bool[] trials_limited = new bool[3] { false,false,false}; int bestIndex = -1; float bestValue = 1000.0f; for (int t = 0; t < trials.Length; t++) { Vector2 vTrial = trials[t]; trials_limited[t] = false; //check whether this is going to exceed our allotted area int test_vw = (int)(vTrial.X * textureWidth); int test_vh = (int)(vTrial.Y * textureHeight); if (test_vw > targetWidth) trials_limited[t] = true; if (test_vh > targetHeight) trials_limited[t] = true; //I. float test_ar = vTrial.X / vTrial.Y; //II. //Vector2 calc = Vector2.Multiply(trials[t], VS); //float test_ar = calc.X / calc.Y; //not clear which approach is superior float deviation_linear = Math.Abs(test_ar - target_par); float deviation_geom = test_ar / target_par; if (deviation_geom < 1) deviation_geom = 1.0f / deviation_geom; float value = deviation_linear; if (value < bestValue) { bestIndex = t; bestValue = value; } } //last result was best, so bail out if (bestIndex == -1) break; //if the winner ran off the edge, bail out if (trials_limited[bestIndex]) break; PS = trials[bestIndex]; } //"fix problems with gameextrapadding in >1x window scales" (other edits were made, maybe theyre whats important) //vw = (int)(PS.X * oldSourceWidth); //vh = (int)(PS.Y * oldSourceHeight); vw = (int)(PS.X * sourceWidth); vh = (int)(PS.Y * sourceHeight); widthScale = PS.X; heightScale = PS.Y; } else { vw = (int)(widthScale * sourceWidth); vh = (int)(heightScale * sourceHeight); } //theres only one sensible way to letterbox in case we're shrinking a dimension: "pan & scan" to the center //this is unlikely to be what the user wants except in the one case of maybe shrinking off some overscan area //instead, since we're more about biz than gaming, lets shrink the view to fit in the small dimension if (targetWidth < vw) vw = targetWidth; if (targetHeight < vh) vh = targetHeight; //determine letterboxing parameters vx = (targetWidth - vw) / 2; vy = (targetHeight - vh) / 2; //zero 09-oct-2014 - changed this for TransformPoint. scenario: basic 1x (but system-specified AR) NES window. //vw would be 293 but WidthScale would be 1.0. I think it should be something different. //FinalPresentation doesnt use the LL.WidthScale, so this is unlikely to be breaking anything old that depends on it //WidthScale = widthScale; //HeightScale = heightScale; WidthScale = (float)vw / oldSourceWidth; HeightScale = (float)vh / oldSourceHeight; } } public class FinalPresentation : BaseFilter { public enum eFilterOption { None, Bilinear, Bicubic } public eFilterOption FilterOption = eFilterOption.None; public RetroShaderChain BicubicFilter; public FinalPresentation(Size size) { this.OutputSize = size; } Size OutputSize, InputSize; public Size TextureSize, VirtualTextureSize; public int BackgroundColor; public bool AutoPrescale; public IGuiRenderer GuiRenderer; public bool Flip; public IGL GL; bool nop; LetterboxingLogic LL; Size ContentSize; public bool Config_FixAspectRatio, Config_FixScaleInteger, Config_PadOnly; /// <summary> /// only use with Config_PadOnly /// </summary> public System.Windows.Forms.Padding Padding; public override void Initialize() { DeclareInput(); nop = false; } public override Size PresizeOutput(string channel, Size size) { if (FilterOption == eFilterOption.Bicubic) { size.Width = LL.vw; size.Height = LL.vh; return size; } return base.PresizeOutput(channel, size); } public override Size PresizeInput(string channel, Size size) { if (FilterOption != eFilterOption.Bicubic) return size; if (Config_PadOnly) { //TODO - redundant fix LL = new LetterboxingLogic(); LL.vx += Padding.Left; LL.vy += Padding.Top; LL.vw = size.Width; LL.vh = size.Height; } else { LL = new LetterboxingLogic(Config_FixAspectRatio, Config_FixScaleInteger, OutputSize.Width, OutputSize.Height, size.Width, size.Height, TextureSize, VirtualTextureSize); LL.vx += Padding.Left; LL.vy += Padding.Top; } return size; } public override void SetInputFormat(string channel, SurfaceState state) { bool need = false; if (state.SurfaceFormat.Size != OutputSize) need = true; if (FilterOption != eFilterOption.None) need = true; if (Flip) need = true; if (!need) { nop = true; ContentSize = state.SurfaceFormat.Size; return; } FindInput().SurfaceDisposition = SurfaceDisposition.Texture; DeclareOutput(new SurfaceState(new SurfaceFormat(OutputSize), SurfaceDisposition.RenderTarget)); InputSize = state.SurfaceFormat.Size; if (Config_PadOnly) { //TODO - redundant fix LL = new LetterboxingLogic(); LL.vx += Padding.Left; LL.vy += Padding.Top; LL.vw = InputSize.Width; LL.vh = InputSize.Height; LL.WidthScale = 1; LL.HeightScale = 1; } else { int ow = OutputSize.Width; int oh = OutputSize.Height; ow -= Padding.Horizontal; oh -= Padding.Vertical; LL = new LetterboxingLogic(Config_FixAspectRatio, Config_FixScaleInteger, ow, oh, InputSize.Width, InputSize.Height, TextureSize, VirtualTextureSize); LL.vx += Padding.Left; LL.vy += Padding.Top; } ContentSize = new Size(LL.vw,LL.vh); if (InputSize == OutputSize) //any reason we need to check vx and vy? IsNOP = true; } public Size GetContentSize() { return ContentSize; } public override Vector2 UntransformPoint(string channel, Vector2 point) { if (nop) return point; point.X -= LL.vx; point.Y -= LL.vy; point.X /= LL.WidthScale; point.Y /= LL.HeightScale; return point; } public override Vector2 TransformPoint(string channel, Vector2 point) { if (nop) return point; point.X *= LL.WidthScale; point.Y *= LL.HeightScale; point.X += LL.vx; point.Y += LL.vy; return point; } public override void Run() { if (nop) return; GL.SetClearColor(Color.FromArgb(BackgroundColor)); GL.Clear(OpenTK.Graphics.OpenGL.ClearBufferMask.ColorBufferBit); GuiRenderer.Begin(OutputSize.Width, OutputSize.Height); GuiRenderer.SetBlendState(GL.BlendNoneCopy); if(FilterOption != eFilterOption.None) InputTexture.SetFilterLinear(); else InputTexture.SetFilterNearest(); if (FilterOption == eFilterOption.Bicubic) { //this was handled earlier by another filter } GuiRenderer.Modelview.Translate(LL.vx, LL.vy); if (Flip) { GuiRenderer.Modelview.Scale(1, -1); GuiRenderer.Modelview.Translate(0, -LL.vh); } GuiRenderer.Draw(InputTexture,0,0,LL.vw,LL.vh); GuiRenderer.End(); } } //TODO - turn this into a NOP at 1x, just in case something accidentally activates it with 1x public class PrescaleFilter : BaseFilter { public int Scale; public override void Initialize() { DeclareInput(SurfaceDisposition.Texture); } public override void SetInputFormat(string channel, SurfaceState state) { var OutputSize = state.SurfaceFormat.Size; OutputSize.Width *= Scale; OutputSize.Height *= Scale; var ss = new SurfaceState(new SurfaceFormat(OutputSize), SurfaceDisposition.RenderTarget); DeclareOutput(ss, channel); } public override void Run() { var outSize = FindOutput().SurfaceFormat.Size; FilterProgram.GuiRenderer.Begin(outSize); FilterProgram.GuiRenderer.SetBlendState(FilterProgram.GL.BlendNoneCopy); FilterProgram.GuiRenderer.Modelview.Scale(Scale); FilterProgram.GuiRenderer.Draw(InputTexture); FilterProgram.GuiRenderer.End(); } } public class AutoPrescaleFilter : BaseFilter { Size OutputSize, InputSize; int XIS, YIS; public override void Initialize() { DeclareInput(SurfaceDisposition.Texture); } public override void SetInputFormat(string channel, SurfaceState state) { //calculate integer scaling factors XIS = OutputSize.Width / state.SurfaceFormat.Size.Width; YIS = OutputSize.Height / state.SurfaceFormat.Size.Height; OutputSize = state.SurfaceFormat.Size; if (XIS <= 1 && YIS <= 1) { IsNOP = true; } else { OutputSize.Width *= XIS; OutputSize.Height *= YIS; } var outState = new SurfaceState(); outState.SurfaceFormat = new SurfaceFormat(OutputSize); outState.SurfaceDisposition = SurfaceDisposition.RenderTarget; DeclareOutput(outState); } public override Size PresizeOutput(string channel, Size size) { OutputSize = size; return base.PresizeOutput(channel, size); } public override Size PresizeInput(string channel, Size insize) { InputSize = insize; return insize; } public override void Run() { FilterProgram.GuiRenderer.Begin(OutputSize); //hope this didnt change FilterProgram.GuiRenderer.SetBlendState(FilterProgram.GL.BlendNoneCopy); FilterProgram.GuiRenderer.Modelview.Scale(XIS,YIS); FilterProgram.GuiRenderer.Draw(InputTexture); FilterProgram.GuiRenderer.End(); } } public class LuaLayer : BaseFilter { public override void Initialize() { DeclareInput(SurfaceDisposition.RenderTarget); } public override void SetInputFormat(string channel, SurfaceState state) { DeclareOutput(state); } Texture2d Texture; public void SetTexture(Texture2d tex) { Texture = tex; } public override void Run() { var outSize = FindOutput().SurfaceFormat.Size; FilterProgram.GuiRenderer.Begin(outSize); FilterProgram.GuiRenderer.SetBlendState(FilterProgram.GL.BlendNormal); FilterProgram.GuiRenderer.Draw(Texture); FilterProgram.GuiRenderer.End(); } } public class OSD : BaseFilter { //this class has the ability to disable its operations for higher performance when the callback is removed, //without having to take it out of the chain. although, its presence in the chain may slow down performance due to added resolves/renders //so, we should probably rebuild the chain. public override void Initialize() { if (RenderCallback == null) return; DeclareInput(SurfaceDisposition.RenderTarget); } public override void SetInputFormat(string channel, SurfaceState state) { if (RenderCallback == null) return; DeclareOutput(state); } public Action RenderCallback; public override void Run() { if (RenderCallback == null) return; RenderCallback(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using DocIdSet = Lucene.Net.Search.DocIdSet; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; namespace Lucene.Net.Util { /// <summary> Stores and iterate on sorted integers in compressed form in RAM. <br/> /// The code for compressing the differences between ascending integers was /// borrowed from {@link Lucene.Net.Store.IndexInput} and /// {@link Lucene.Net.Store.IndexOutput}. /// <p/> /// <b>NOTE:</b> this class assumes the stored integers are doc Ids (hence why it /// extends {@link DocIdSet}). Therefore its {@link #Iterator()} assumes {@link /// DocIdSetIterator#NO_MORE_DOCS} can be used as sentinel. If you intent to use /// this value, then make sure it's not used during search flow. /// </summary> public class SortedVIntList:DocIdSet { private class AnonymousClassDocIdSetIterator:DocIdSetIterator { public AnonymousClassDocIdSetIterator(SortedVIntList enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(SortedVIntList enclosingInstance) { this.enclosingInstance = enclosingInstance; } private SortedVIntList enclosingInstance; public SortedVIntList Enclosing_Instance { get { return enclosingInstance; } } internal int bytePos = 0; internal int lastInt = 0; internal int doc = - 1; private void Advance() { // See Lucene.Net.Store.IndexInput.readVInt() sbyte b = Enclosing_Instance.bytes[bytePos++]; lastInt += (b & Lucene.Net.Util.SortedVIntList.VB1); for (int s = Lucene.Net.Util.SortedVIntList.BIT_SHIFT; (b & ~ Lucene.Net.Util.SortedVIntList.VB1) != 0; s += Lucene.Net.Util.SortedVIntList.BIT_SHIFT) { b = Enclosing_Instance.bytes[bytePos++]; lastInt += ((b & Lucene.Net.Util.SortedVIntList.VB1) << s); } } /// <deprecated> use {@link #DocID()} instead. /// </deprecated> [Obsolete("use DocID() instead.")] public override int Doc() { return lastInt; } public override int DocID() { return doc; } /// <deprecated> use {@link #NextDoc()} instead. /// </deprecated> [Obsolete("use NextDoc() instead.")] public override bool Next() { return NextDoc() != NO_MORE_DOCS; } public override int NextDoc() { if (bytePos >= Enclosing_Instance.lastBytePos) { doc = NO_MORE_DOCS; } else { Advance(); doc = lastInt; } return doc; } /// <deprecated> use {@link #Advance(int)} instead. /// </deprecated> [Obsolete("use Advance(int) instead.")] public override bool SkipTo(int docNr) { return Advance(docNr) != NO_MORE_DOCS; } public override int Advance(int target) { while (bytePos < Enclosing_Instance.lastBytePos) { Advance(); if (lastInt >= target) { return doc = lastInt; } } return doc = NO_MORE_DOCS; } } /// <summary>When a BitSet has fewer than 1 in BITS2VINTLIST_SIZE bits set, /// a SortedVIntList representing the index numbers of the set bits /// will be smaller than that BitSet. /// </summary> internal const int BITS2VINTLIST_SIZE = 8; private int size; private sbyte[] bytes; private int lastBytePos; /// <summary> Create a SortedVIntList from all elements of an array of integers. /// /// </summary> /// <param name="sortedInts"> A sorted array of non negative integers. /// </param> public SortedVIntList(int[] sortedInts):this(sortedInts, sortedInts.Length) { } /// <summary> Create a SortedVIntList from an array of integers.</summary> /// <param name="sortedInts"> An array of sorted non negative integers. /// </param> /// <param name="inputSize"> The number of integers to be used from the array. /// </param> public SortedVIntList(int[] sortedInts, int inputSize) { SortedVIntListBuilder builder = new SortedVIntListBuilder(this); for (int i = 0; i < inputSize; i++) { builder.AddInt(sortedInts[i]); } builder.Done(); } /// <summary> Create a SortedVIntList from a BitSet.</summary> /// <param name="bits"> A bit set representing a set of integers. /// </param> public SortedVIntList(System.Collections.BitArray bits) { SortedVIntListBuilder builder = new SortedVIntListBuilder(this); int nextInt = SupportClass.BitSetSupport.NextSetBit(bits, 0); while (nextInt != - 1) { builder.AddInt(nextInt); nextInt = SupportClass.BitSetSupport.NextSetBit(bits, nextInt + 1); } builder.Done(); } /// <summary> Create a SortedVIntList from an OpenBitSet.</summary> /// <param name="bits"> A bit set representing a set of integers. /// </param> public SortedVIntList(OpenBitSet bits) { SortedVIntListBuilder builder = new SortedVIntListBuilder(this); int nextInt = bits.NextSetBit(0); while (nextInt != - 1) { builder.AddInt(nextInt); nextInt = bits.NextSetBit(nextInt + 1); } builder.Done(); } /// <summary> Create a SortedVIntList.</summary> /// <param name="docIdSetIterator"> An iterator providing document numbers as a set of integers. /// This DocIdSetIterator is iterated completely when this constructor /// is called and it must provide the integers in non /// decreasing order. /// </param> public SortedVIntList(DocIdSetIterator docIdSetIterator) { SortedVIntListBuilder builder = new SortedVIntListBuilder(this); int doc; while ((doc = docIdSetIterator.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { builder.AddInt(doc); } builder.Done(); } private class SortedVIntListBuilder { private void InitBlock(SortedVIntList enclosingInstance) { this.enclosingInstance = enclosingInstance; } private SortedVIntList enclosingInstance; public SortedVIntList Enclosing_Instance { get { return enclosingInstance; } } private int lastInt = 0; internal SortedVIntListBuilder(SortedVIntList enclosingInstance) { InitBlock(enclosingInstance); Enclosing_Instance.InitBytes(); lastInt = 0; } internal virtual void AddInt(int nextInt) { int diff = nextInt - lastInt; if (diff < 0) { throw new System.ArgumentException("Input not sorted or first element negative."); } if ((Enclosing_Instance.lastBytePos + Enclosing_Instance.MAX_BYTES_PER_INT) > Enclosing_Instance.bytes.Length) { // biggest possible int does not fit Enclosing_Instance.ResizeBytes((Enclosing_Instance.bytes.Length * 2) + Enclosing_Instance.MAX_BYTES_PER_INT); } // See Lucene.Net.Store.IndexOutput.writeVInt() while ((diff & ~ Lucene.Net.Util.SortedVIntList.VB1) != 0) { // The high bit of the next byte needs to be set. Enclosing_Instance.bytes[Enclosing_Instance.lastBytePos++] = (sbyte) ((diff & Lucene.Net.Util.SortedVIntList.VB1) | ~ Lucene.Net.Util.SortedVIntList.VB1); diff = SupportClass.Number.URShift(diff, Lucene.Net.Util.SortedVIntList.BIT_SHIFT); } Enclosing_Instance.bytes[Enclosing_Instance.lastBytePos++] = (sbyte) diff; // Last byte, high bit not set. Enclosing_Instance.size++; lastInt = nextInt; } internal virtual void Done() { Enclosing_Instance.ResizeBytes(Enclosing_Instance.lastBytePos); } } private void InitBytes() { size = 0; bytes = new sbyte[128]; // initial byte size lastBytePos = 0; } private void ResizeBytes(int newSize) { if (newSize != bytes.Length) { sbyte[] newBytes = new sbyte[newSize]; Array.Copy(bytes, 0, newBytes, 0, lastBytePos); bytes = newBytes; } } private const int VB1 = 0x7F; private const int BIT_SHIFT = 7; private int MAX_BYTES_PER_INT = (31 / BIT_SHIFT) + 1; /// <returns> The total number of sorted integers. /// </returns> public virtual int Size() { return size; } /// <returns> The size of the byte array storing the compressed sorted integers. /// </returns> public virtual int GetByteSize() { return bytes.Length; } /// <summary>This DocIdSet implementation is cacheable. </summary> public override bool IsCacheable() { return true; } /// <returns> An iterator over the sorted integers. /// </returns> public override DocIdSetIterator Iterator() { return new AnonymousClassDocIdSetIterator(this); } } }
using System; using System.ComponentModel; using System.Data.SqlClient; using System.Reflection; using System.Windows.Forms; using BLToolkit.Aspects; using bv.common; using bv.common.Core; using bv.common.Resources; using bv.model.Model.Core; using bv.winclient.BasePanel; using bv.common.Enums; namespace bv.winclient.Core { public partial class ErrorForm : BvForm { public ErrorForm() { InitializeComponent(); this.HelpTopicId = Help2.HomePage; Splash.HideSplash(); if (!WinUtils.IsComponentInDesignMode(this)) { cmdDetail.Click += cmdDetail_Click; if (BaseFormManager.MainForm != null) Icon = BaseFormManager.MainForm.Icon; } } public enum FormType { Error, Message, Warning, Confirmation } bool m_ShowDetail = false; [Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ErrorText { get { return lbErrorText.Text; } set { lbErrorText.Text = value; // if (value != null) // { // cmdDetail_Click(null, EventArgs.Empty); // //cmdSend.Visible = value.IsCriticalError; // } } } [Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string FullErrorText { get { return txtFullErrorText.Text; } set { txtFullErrorText.Text = value; if (value != null) { DefineButtonsVisibility(); //cmdDetail_Click(null, EventArgs.Empty); //cmdSend.Visible = value.IsCriticalError; } } } private FormType m_FormType; [Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public FormType Type { get { return m_FormType; } set { m_FormType = value; Text = GetMessage(m_FormType.ToString()); DefineButtonsVisibility(); } } [Browsable(false), Localizable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public static BaseStringsStorage Messages { get; set; } static ErrorForm() { UnitTestMode = false; } public static bool UnitTestMode { get; set; } private void DefineButtonsVisibility() { //if (m_FormType != FormType.Error) //{ cmdDetail.Visible = txtFullErrorText.Text != ""; cmdDetail_Click(null, EventArgs.Empty); cmdSend.Visible = false; cmdOk.Visible = m_FormType != FormType.Confirmation; btnNo.Visible = m_FormType == FormType.Confirmation; btnYes.Visible = m_FormType == FormType.Confirmation; //} //else //{ //cmdDetail.Visible = txtFullErrorText.Text != ""; //cmdDetail_Click(null, EventArgs.Empty); //cmdSend.Visible = false; //if (m_Error != null) //{ // cmdSend.Visible = m_Error.IsCriticalError; //} //else //{ // cmdSend.Visible = false; //} //} } #region "Shared methods" private static Exception GetInnerException(Exception ex) { while (ex != null && ex.InnerException != null) return GetInnerException(ex.InnerException); return ex; } private static bool HandleException(Exception ex) { if (ex == null) return false; ex = GetInnerException(ex); if (ex is SqlException) { string msgId = SqlExceptionMessage.Get(ex as SqlException); if (msgId != null) { ShowError(msgId); return true; } } return false; } public static string GetMessage(string resourceKey, string resourceValue = null) { if (resourceKey == null) return String.Empty; var s = BvMessages.Get(resourceKey, resourceValue); if (BvMessages.Instance.IsValueExists) return s; if (Messages != null) { s = Messages.GetString(resourceKey, resourceValue); return s; } return String.Empty; } private static DialogResult ShowForm(ErrorForm f, Form owner) { if (owner == null) owner = Form.ActiveForm; try { WaitDialog.Hide(); f.TopMost = true; if (UnitTestMode) { f.Show(owner); System.Threading.Thread.Sleep(2000); return DialogResult.OK; } return f.ShowDialog(owner); } finally { WaitDialog.Restore(); } } private static ErrorForm Create(Form owner, string msg, FormType fType, string detailError = null) { if(owner ==null) { owner = Form.ActiveForm; } var f = new ErrorForm(); f.ErrorText = msg; f.Type = fType; //f.cmdDetail.Visible = !string.IsNullOrEmpty(detailError); if (!string.IsNullOrEmpty(detailError)) { f.FullErrorText = detailError; } //f.cmdDetail_Click(null, EventArgs.Empty); f.StartPosition = owner != null ? FormStartPosition.CenterParent : FormStartPosition.CenterScreen; return f; } public static void ShowMessageDirect(Form owner, string msg, FormType fType, string detailError = null) { if (BaseFormManager.IsReportsServiceRunning || BaseFormManager.IsAvrServiceRunning) { string error = string.Format("Could not show message form from the service.{0}Error message:{0}'{1}'{0} Error details:{0}'{2}'", Environment.NewLine, msg, detailError); throw new ApplicationException(error); } using (ErrorForm f = Create(owner, msg, fType, detailError)) { ShowForm(f, owner); } } public static void ShowMessageDirect(string msg, FormType fType, string detailError = null) { ShowMessageDirect(null, msg, fType, detailError); } public static void ShowMessageDirect(string msg) { ShowMessageDirect(msg, FormType.Message); } public static void ShowMessage(string str, string defaultStr) { ShowMessageDirect(GetMessage(str, defaultStr)); } public static void ShowWarning(string str, string defaultStr = null) { ShowWarningDirect(GetMessage(str, defaultStr)); } public static void ShowWarningFormat(string str, string defaultStr, params object[] args) { ShowWarningFormatWithPrefix(str, defaultStr, "", args); } public static void ShowWarningFormatWithPrefix(string str, string defaultStr, string prefix, params object[] args) { ShowMessageDirect( prefix + (args == null ? GetMessage(str, defaultStr) : String.Format(GetMessage(str, defaultStr), args)) , FormType.Warning); } public static void ShowWarningDirect(string str) { ShowMessageDirect(str, FormType.Warning); } public static void ShowError(StandardError errType, Exception ex) { if (HandleException(ex)) return; string error = StandardErrorHelper.Error(errType); string detailError = ex.ToString(); ShowMessageDirect(error, FormType.Error, detailError); } public static void ShowError(Exception ex) { ShowError(StandardError.UnprocessedError, ex); } public static void ShowError(string errResourceName) { ShowMessageDirect(GetMessage(errResourceName), FormType.Error); } public static void ShowError(string errResourceName, string errMsg) { ShowMessageDirect(GetMessage(errResourceName, errMsg), FormType.Error); } private static Exception m_currentException = null; public static void ShowError(string errResourceName, string errMsg, Exception ex) { if (m_currentException != null) return; if (HandleException(ex)) return; m_currentException = ex; string detailError = null; if (ex != null) detailError = ex.ToString(); ShowMessageDirect(GetMessage(errResourceName, errMsg), FormType.Error, detailError); m_currentException = null; } public static void ShowError(string errResourceName, string errMsg, params object[] args) { ShowMessageDirect( args == null ? GetMessage(errResourceName, errMsg) : String.Format(GetMessage(errResourceName, errMsg), args) , FormType.Error); } public static void ShowErrorDirect(string errMessage, Exception ex = null) { string detailError = null; if (ex != null) detailError = ex.ToString(); ShowMessageDirect(errMessage, FormType.Error, detailError); } public static void ShowErrorDirect(Form owner, string errMessage, Exception ex = null) { string detailError = null; if (ex != null) detailError = ex.ToString(); ShowMessageDirect(owner, errMessage, FormType.Error, detailError); } public static void ShowErrorDirect(string errMessage, params object[] args) { ShowMessageDirect(String.Format(errMessage, args), FormType.Error); } public static void ShowErrorDirect(Form owner, string errMessage, params object[] args) { ShowMessageDirect(owner, String.Format(errMessage, args), FormType.Error); } public static void ShowError(string errMsg, Exception ex) { if (HandleException(ex)) return; ShowMessageDirect(errMsg, FormType.Error, ex.ToString()); } public static DialogResult ShowConfirmationDialog(Form owner, string msg, string detailError) { using (var f = Create(owner, msg, FormType.Confirmation, detailError)) { return ShowForm(f, owner); } } private delegate void ExceptionDelegate(Exception ex); public static void ShowErrorThreadSafe(Exception ex) { ExceptionDelegate o = ShowError; if (BaseFormManager.MainForm == null) { throw (ex); } BaseFormManager.MainForm.BeginInvoke(o, ex); } #endregion #region "Private methods" private void cmdDetail_Click(object sender, EventArgs e) { SuspendLayout(); if (string.IsNullOrEmpty(txtFullErrorText.Text)) { m_ShowDetail = false; cmdDetail.Visible = false; pnDetails.Visible = false; if (Height - pnDetails.Height > 100) Height -= pnDetails.Height; ResumeLayout(); return; } if (m_ShowDetail) { cmdDetail.Text = GetMessage("btnShowErrDetail", "Show Details"); Height -= pnDetails.Height; } else { cmdDetail.Text = GetMessage("btnHideErrDetail", "Hide Details"); Height += pnDetails.Height; } m_ShowDetail = !m_ShowDetail; pnDetails.Visible = m_ShowDetail; ResumeLayout(); } #endregion protected override void OnResize(EventArgs e) { PerformLayout(); } } }
#region Copyright (c) 2004 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2004 Ian Davis and James Carlyle 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 namespace SemPlan.Spiral.Tests.Core { using SemPlan.Spiral.Core; using System; using System.Collections; using System.Collections.Specialized; using System.Text.RegularExpressions; /// <summary> /// Compares a list of NTriples against an expected list to see if the two lists are equivilent /// </summary> /// <remarks> /// $Id: NTripleListVerifier.cs,v 1.2 2005/05/26 14:24:30 ian Exp $ ///</remarks> public class NTripleListVerifier { private StringCollection itsExpectedTriples; private StringCollection itsReceivedTriples; private StringCollection itsExpectedBlankNodes; private StringCollection itsReceivedBlankNodes; private StringCollection itsExpectedNonBlankNodes; private StringCollection itsReceivedNonBlankNodes; private string itsLastFailureDescription = ""; private static Regex tripleRegex = new Regex(@"^(\S+)\s+(\S+)\s+(\S.*\S)\s*\.\s*$", RegexOptions.Compiled); private static Regex blankNode = new Regex(@"^_:(\S+)*$", RegexOptions.Compiled); public NTripleListVerifier() { itsExpectedTriples = new StringCollection(); itsReceivedTriples = new StringCollection(); itsExpectedBlankNodes = new StringCollection(); itsReceivedBlankNodes = new StringCollection(); itsExpectedNonBlankNodes = new StringCollection(); itsReceivedNonBlankNodes = new StringCollection(); } public void Expect(string nTriple) { Match matchTriple = tripleRegex.Match(nTriple); if (matchTriple.Success) { string subjectPart = matchTriple.Groups[1].Value; Match matchSubjectBlankNode = blankNode.Match(subjectPart); if (matchSubjectBlankNode.Success) { string nodeId = matchSubjectBlankNode.Groups[1].Value; if (! itsExpectedBlankNodes.Contains(nodeId) ) { itsExpectedBlankNodes.Add(nodeId); } } else { itsExpectedNonBlankNodes.Add(subjectPart); } string objectPart = matchTriple.Groups[3].Value; Match matchObjectBlankNode = blankNode.Match(objectPart); if (matchObjectBlankNode.Success) { string nodeId = matchObjectBlankNode.Groups[1].Value; if (! itsExpectedBlankNodes.Contains(nodeId) ) { itsExpectedBlankNodes.Add(nodeId); } } else { itsExpectedNonBlankNodes.Add(objectPart); } itsExpectedTriples.Add(matchTriple.Groups[1].Value + " " + matchTriple.Groups[2].Value + " " + matchTriple.Groups[3].Value + " ."); } } public void Receive(string nTriple) { Match matchTriple = tripleRegex.Match(nTriple); if (matchTriple.Success) { string subjectPart = matchTriple.Groups[1].Value; Match matchSubjectBlankNode = blankNode.Match(subjectPart); if (matchSubjectBlankNode.Success) { string nodeId = matchSubjectBlankNode.Groups[1].Value; if (! itsReceivedBlankNodes.Contains(nodeId) ) { itsReceivedBlankNodes.Add(nodeId); } } else { itsReceivedNonBlankNodes.Add(subjectPart); } string objectPart = matchTriple.Groups[3].Value; Match matchObjectBlankNode = blankNode.Match(objectPart); if (matchObjectBlankNode.Success) { string nodeId = matchObjectBlankNode.Groups[1].Value; if (! itsReceivedBlankNodes.Contains(nodeId) ) { itsReceivedBlankNodes.Add(nodeId); } } else { itsReceivedNonBlankNodes.Add(objectPart); } } itsReceivedTriples.Add(nTriple); } public bool VerifyCounts() { if (itsExpectedTriples.Count != itsReceivedTriples.Count) { itsLastFailureDescription = "Received " + itsReceivedTriples.Count +" triples but was expecting " + itsExpectedTriples.Count; return false; } if (itsExpectedBlankNodes.Count != itsReceivedBlankNodes.Count) { itsLastFailureDescription = "Received " + itsReceivedBlankNodes.Count +" blank nodes but was expecting " + itsExpectedBlankNodes.Count; return false; } if (itsExpectedNonBlankNodes.Count != itsReceivedNonBlankNodes.Count) { itsLastFailureDescription = "Received " + itsReceivedNonBlankNodes.Count +" non-blank nodes but was expecting " + itsExpectedNonBlankNodes.Count; return false; } return true; } public bool Verify() { if ( ! VerifyCounts() ) { return false; } bool verified = false; StringCollection mappedTriples = new StringCollection(); if (itsReceivedBlankNodes.Count > 0 && itsExpectedBlankNodes.Count > 0) { ArrayList mappingPermutations = new ArrayList(); if (itsReceivedBlankNodes.Count== 1) { Hashtable nodeIdMapping = new Hashtable(); nodeIdMapping[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[0]; mappingPermutations.Add(nodeIdMapping); } else if (itsReceivedBlankNodes.Count== 2) { Hashtable nodeIdMapping1= new Hashtable(); nodeIdMapping1[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[0]; nodeIdMapping1[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[1]; mappingPermutations.Add(nodeIdMapping1); Hashtable nodeIdMapping2= new Hashtable(); nodeIdMapping2[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[1]; nodeIdMapping2[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[0]; mappingPermutations.Add(nodeIdMapping2); } else if (itsReceivedBlankNodes.Count== 3) { Hashtable nodeIdMapping1= new Hashtable(); nodeIdMapping1[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[0]; nodeIdMapping1[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[1]; nodeIdMapping1[itsReceivedBlankNodes[2]] = itsExpectedBlankNodes[2]; mappingPermutations.Add(nodeIdMapping1); Hashtable nodeIdMapping2= new Hashtable(); nodeIdMapping2[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[0]; nodeIdMapping2[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[2]; nodeIdMapping2[itsReceivedBlankNodes[2]] = itsExpectedBlankNodes[1]; mappingPermutations.Add(nodeIdMapping2); Hashtable nodeIdMapping3= new Hashtable(); nodeIdMapping3[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[1]; nodeIdMapping3[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[0]; nodeIdMapping3[itsReceivedBlankNodes[2]] = itsExpectedBlankNodes[2]; mappingPermutations.Add(nodeIdMapping3); Hashtable nodeIdMapping4= new Hashtable(); nodeIdMapping4[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[2]; nodeIdMapping4[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[0]; nodeIdMapping4[itsReceivedBlankNodes[2]] = itsExpectedBlankNodes[1]; mappingPermutations.Add(nodeIdMapping4); Hashtable nodeIdMapping5= new Hashtable(); nodeIdMapping5[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[2]; nodeIdMapping5[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[1]; nodeIdMapping5[itsReceivedBlankNodes[2]] = itsExpectedBlankNodes[0]; mappingPermutations.Add(nodeIdMapping5); Hashtable nodeIdMapping6= new Hashtable(); nodeIdMapping6[itsReceivedBlankNodes[0]] = itsExpectedBlankNodes[1]; nodeIdMapping6[itsReceivedBlankNodes[1]] = itsExpectedBlankNodes[2]; nodeIdMapping6[itsReceivedBlankNodes[2]] = itsExpectedBlankNodes[0]; mappingPermutations.Add(nodeIdMapping6); } else { throw new NotImplementedException("Cannot compare ntriples with more than three different blank nodes"); /* Permutations of 4: 1 2 3 4 1 2 4 3 1 3 2 4 1 3 4 2 1 4 3 2 1 4 2 3 2 1 3 4 2 1 4 3 2 3 1 4 2 3 4 1 2 4 3 1 2 4 1 3 3 2 1 4 3 2 4 1 3 1 2 4 3 1 4 2 3 4 1 2 3 4 2 1 4 2 3 1 4 2 1 3 4 3 2 1 4 3 1 2 4 1 3 2 4 1 2 3 */ } foreach (object mappingPermutation in mappingPermutations) { verified = VerifyAgainstExpected( ApplyNodeIdMapping( (Hashtable) mappingPermutation) ); if (verified) { break; } } } else { verified = VerifyAgainstExpected(itsReceivedTriples); } return verified; } public bool VerifyAgainstExpected(StringCollection triplesToVerify) { foreach (string expected in itsExpectedTriples) { if (! triplesToVerify.Contains(expected)) { itsLastFailureDescription = "Did not receive expected triple: " + expected; return false; } } return true; } public StringCollection ApplyNodeIdMapping(Hashtable nodeIdMapping) { StringCollection mappedTriples = new StringCollection(); foreach (string received in itsReceivedTriples) { Match matchTriple = tripleRegex.Match(received); if (matchTriple.Success) { string subjectPart = matchTriple.Groups[1].Value; string predicatePart = matchTriple.Groups[2].Value; string objectPart = matchTriple.Groups[3].Value; Match matchSubjectBlankNode = blankNode.Match(subjectPart); Match matchObjectBlankNode = blankNode.Match(objectPart); if (matchSubjectBlankNode.Success) { string subjectNodeId = matchSubjectBlankNode.Groups[1].Value; if (matchObjectBlankNode.Success) { string objectNodeId = matchObjectBlankNode.Groups[1].Value; mappedTriples.Add("_:" + nodeIdMapping[subjectNodeId] + " " + predicatePart + " _:" + nodeIdMapping[objectNodeId] + " ."); } else { mappedTriples.Add("_:" + nodeIdMapping[subjectNodeId] + " " + predicatePart + " " + objectPart+ " ."); } } else { if (matchObjectBlankNode.Success) { string objectNodeId = matchObjectBlankNode.Groups[1].Value; mappedTriples.Add(subjectPart + " " + predicatePart + " _:" + nodeIdMapping[objectNodeId] + " ."); } else { mappedTriples.Add(received); } } } else { mappedTriples.Add(received); } } return mappedTriples; } public string GetLastFailureDescription() { return itsLastFailureDescription; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/24/2010 3:37:19 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** //ORIGINAL HEADER FROM C++ source which was converted to C# by Ted Dunsford 2/24/2010 /****************************************************************************** * $Id: hfafield.cpp, v 1.21 2006/05/07 04:04:03 fwarmerdam Exp $ * * Project: Erdas Imagine (.img) Translator * Purpose: Implementation of the HFAField class for managing information * about one field in a HFA dictionary type. Managed by HFAType. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 1999, Intergraph Corporation * * 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. ****************************************************************************** * * $Log: hfafield.cpp, v $ * Revision 1.21 2006/05/07 04:04:03 fwarmerdam * fixed serious multithreading issue with ExtractInstValue (bug 1132) * * Revision 1.20 2006/04/03 04:33:16 fwarmerdam * Report basedata type. Support reading basedata as a 1D array. Fix * bug in basedata reading ... wasn't skippig 2 byte code before data. * * Revision 1.19 2006/03/29 14:24:04 fwarmerdam * added preliminary nodata support (readonly) * * Revision 1.18 2005/10/02 15:14:48 fwarmerdam * fixed size for <8bit basedata items * * Revision 1.17 2005/09/28 19:38:07 fwarmerdam * Added partial support for inline defined types. * * Revision 1.16 2005/05/10 00:56:17 fwarmerdam * fixed bug with setting entries in an array (with count setting) * * Revision 1.15 2004/02/13 15:58:11 warmerda * Fixed serious bug with GetInstBytes() for BASEDATA * fields with * a count of zero. Such as the Excluded field of most stats nodes! * * Revision 1.14 2003/12/08 19:09:34 warmerda * implemented DumpInstValue and GetInstBytes for basedata * * Revision 1.13 2003/05/21 15:35:05 warmerda * cleanup type conversion warnings * * Revision 1.12 2003/04/22 19:40:36 warmerda * fixed email address * * Revision 1.11 2001/07/18 04:51:57 warmerda * added CPL_CVSID * * Revision 1.10 2000/12/29 16:37:32 warmerda * Use GUInt32 for all file offsets * * Revision 1.9 2000/10/12 19:30:32 warmerda * substantially improved write support * * Revision 1.8 2000/09/29 21:42:38 warmerda * preliminary write support implemented * * Revision 1.7 1999/06/01 13:07:59 warmerda * added speed up for indexing into fixes size object arrays * * Revision 1.6 1999/02/15 19:06:18 warmerda * Disable warning on field offsets for Intergraph delivery * * Revision 1.5 1999/01/28 18:28:28 warmerda * minor simplification of code * * Revision 1.4 1999/01/28 18:03:07 warmerda * Fixed some byte swapping problems, and problems with accessing data from * the file that isn't on a word boundary. * * Revision 1.3 1999/01/22 19:23:11 warmerda * Fixed bug with offset into arrays of structures. * * Revision 1.2 1999/01/22 17:37:59 warmerda * Fixed up support for variable sizes, and arrays of variable sized objects * * Revision 1.1 1999/01/04 22:52:10 warmerda * New */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace DotSpatial.Data { /// <summary> /// HfaField /// </summary> public class HfaField { #region Private Variables private const int MAX_ENTRY_REPORT = 16; private List<string> _enumNames; private string _fieldName; private int _itemCount; private HfaType _itemObjectType; private string _itemObjectTypeString; private char _itemType; private int _numBytes; private char _pointer; #endregion #region Constructors #endregion #region Methods /// <summary> /// /// </summary> /// <param name="dict"></param> public void CompleteDefn(HfaDictionary dict) { // Get a reference to the type object if we have a type name // for this field (not a build in). if (_itemObjectTypeString != null) { _itemObjectType = dict[_itemObjectTypeString]; } // Figure out the size if (_pointer == 'p') { _numBytes = -1; } else if (_itemObjectType != null) { _itemObjectType.CompleteDefn(dict); if (_itemObjectType.NumBytes == -1) { _numBytes = -1; } else { _numBytes = (short)(_itemObjectType.NumBytes * _itemCount); } if (_pointer == '*' && _numBytes != -1) _numBytes += 8; } else { _numBytes = (short)(HfaDictionary.GetItemSize(_itemType) * _itemCount); } } /// <summary> /// This writes formatted content for this field to the specified IO stream. /// </summary> /// <param name="stream">The stream to write to.</param> public void Dump(Stream stream) { string typename = string.Empty; StreamWriter sw = new StreamWriter(stream); switch (_itemType) { case '1': typename = "U1"; break; case '2': typename = "U2"; break; case '4': typename = "U4"; break; case 'c': typename = "UChar"; break; case 'C': typename = "CHAR"; break; case 'e': typename = "ENUM"; break; case 's': typename = "USHORT"; break; case 'S': typename = "SHORT"; break; case 't': typename = "TIME"; break; case 'l': typename = "ULONG"; break; case 'L': typename = "LONG"; break; case 'f': typename = "FLOAT"; break; case 'd': typename = "DOUBLE"; break; case 'm': typename = "COMPLEX"; break; case 'M': typename = "DCOMPLEX"; break; case 'b': typename = "BASEDATA"; break; case 'o': typename = _itemObjectTypeString; break; case 'x': typename = "InlineType"; break; default: typename = "Unknowm"; break; } string tc = (_pointer == 'p' || _pointer == '*') ? _pointer.ToString() : " "; string name = typename.PadRight(19); sw.WriteLine(" " + name + " " + tc + " " + _fieldName + "[" + _itemCount + "];"); if (_enumNames == null || _enumNames.Count <= 0) return; for (int i = 0; i < _enumNames.Count; i++) { sw.Write(" " + _enumNames[i] + "=" + i); } } /// <summary> /// /// </summary> /// <param name="fpOut"></param> /// <param name="data"></param> /// <param name="dataOffset"></param> /// <param name="dataSize"></param> /// <param name="prefix"></param> public void DumpInstValue(Stream fpOut, byte[] data, long dataOffset, int dataSize, string prefix) { StreamWriter sw = new StreamWriter(fpOut); int extraOffset; int nEntries = GetInstCount(data, dataOffset); // Special case for arrays of characters or uchars which are printed as a string if ((_itemType == 'c' || _itemType == 'C') && nEntries > 0) { object value; if (ExtractInstValue(null, 0, data, dataOffset, dataSize, 's', out value, out extraOffset)) { sw.WriteLine(prefix + _fieldName + " = '" + (string)value + "'"); } else { sw.WriteLine(prefix + _fieldName + " = (access failed)"); } } for (int iEntry = 0; iEntry < Math.Min(MAX_ENTRY_REPORT, nEntries); iEntry++) { sw.Write(prefix + _fieldName); if (nEntries > 1) sw.Write("[" + iEntry + "]"); sw.Write(" = "); object value; switch (_itemType) { case 'f': case 'd': if (ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 'd', out value, out extraOffset)) { sw.Write(value + "\n"); } else { sw.Write("(access failed)\n"); } break; case 'b': int nRows = Hfa.ReadInt32(data, dataOffset + 8); int nColumns = Hfa.ReadInt32(data, dataOffset + 12); HfaEPT type = Hfa.ReadType(data, dataOffset + 16); sw.Write(nRows + "x" + nColumns + " basedata of type " + type); break; case 'e': if (ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 's', out value, out extraOffset)) { sw.Write((string)value); } else { sw.Write("(accessfailed)"); } break; case 'o': if (!ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 'p', out value, out extraOffset)) { sw.WriteLine("(access failed)"); } else { // the pointer logic here is death! Originally the pointer address was used // nByteOffset = ((GByte*) val) - pabyData; // This doesn't work in a safe context. sw.Write("\n"); string szLongFieldName = prefix; if (prefix.Length > 256) szLongFieldName = prefix.Substring(0, 256); _itemObjectType.DumpInstValue(fpOut, data, dataOffset + extraOffset, dataSize - extraOffset, szLongFieldName); } break; default: if (ExtractInstValue(null, iEntry, data, dataOffset, dataSize, 'i', out value, out extraOffset)) { sw.WriteLine(value); } else { sw.WriteLine("(access failed)\n"); } break; } } if (nEntries > MAX_ENTRY_REPORT) { sw.Write(prefix + " ... remaining instances omitted ...\n"); } if (nEntries == 0) { sw.Write(prefix + _fieldName + " = (no values)\n"); } } /// <summary> /// SetInstValue /// </summary> /// <param name="sField"></param> /// <param name="indexValue"></param> /// <param name="data"></param> /// <param name="dataOffset"></param> /// <param name="dataSize"></param> /// <param name="reqType"></param> /// <param name="value"></param> /// <exception cref="HfaPointerInsertNotSupportedException">Attempting to insert a pointer is not supported.</exception> /// <exception cref="HfaEnumerationNotFoundException">Occurs if the specified value is not a valid member of the enumeration for this field.</exception> public void SetInstValue(string sField, int indexValue, byte[] data, long dataOffset, int dataSize, char reqType, object value) { // If this field contains a pointer, then we wil adjust the data offset relative to it. // This updates the offset info, but doesn't change the first four bytes. if (_pointer != '\0') { int nCount; if (NumBytes > -1) { nCount = _itemCount; } else if (reqType == 's' && (_itemType == 'c' || _itemType == 'C')) { // Either a string or a character array nCount = 0; IEnumerable<char> strVal = value as IEnumerable<char>; if (strVal != null) nCount = strVal.Count() + 1; } else { nCount = indexValue + 1; } uint nOffset = (uint)nCount; Array.Copy(Hfa.LittleEndian(nOffset), 0, data, dataOffset + 4, 4); dataOffset += 8; dataSize -= 8; } // Pointers to char or uchar arrays requested as strings are handled as a special case if ((_itemType == 'c' || _itemType == 'C') && reqType == 's') { int nBytesToCopy = NumBytes; IEnumerable<char> strVal = value as IEnumerable<char>; if (strVal != null) nBytesToCopy = strVal.Count(); if (NumBytes == -1 && strVal != null) nBytesToCopy = strVal.Count(); // Force a blank erase to remove previous characters byte[] blank = new byte[nBytesToCopy]; Array.Copy(blank, 0, data, dataOffset, nBytesToCopy); if (strVal != null) { ASCIIEncoding ascii = new ASCIIEncoding(); string str = new string(strVal.ToArray()); byte[] charData = ascii.GetBytes(str); Array.Copy(charData, 0, data, dataOffset, charData.Length); } return; } // Translate the passed type into different representations int nIntValue; double dfDoubleValue; if (reqType == 's') { nIntValue = int.Parse((string)value); dfDoubleValue = double.Parse((string)value); } else if (reqType == 'd') { dfDoubleValue = (double)value; nIntValue = Convert.ToInt32((double)value); } else if (reqType == 'i') { dfDoubleValue = Convert.ToDouble((int)value); nIntValue = (int)value; } else if (reqType == 'p') { throw new HfaPointerInsertNotSupportedException(); } else { return; } // Handle by type switch (_itemType) { case 'c': // Char64 case 'C': // Char128 if (reqType == 's') { // handled earlier as special case, } else { data[dataOffset + nIntValue] = (byte)nIntValue; } break; case 'e': // enums are stored as ushort case 's': // little s = ushort type { if (_itemType == 'e' && reqType == 's') { nIntValue = _enumNames.IndexOf((string)value); if (nIntValue == -1) { throw new HfaEnumerationNotFoundException((string)value); } } } // Each enumeration is stored as a 2-bit unsigned short entry. ushort num = (ushort)nIntValue; Array.Copy(Hfa.LittleEndian(num), 0, data, dataOffset + 2 * indexValue, 2); break; case 'S': // signed short { short nNumber = (short)nIntValue; Array.Copy(Hfa.LittleEndian(nNumber), 0, data, dataOffset + indexValue * 2, 2); } break; case 't': case 'l': { uint nNumber = (uint)nIntValue; Array.Copy(Hfa.LittleEndian(nNumber), 0, data, dataOffset + indexValue * 4, 4); } break; case 'L': // Int32 { int nNumber = nIntValue; Array.Copy(Hfa.LittleEndian(nNumber), 0, data, dataOffset + indexValue * 4, 4); } break; case 'f': // Float (32 bit) { float dfNumber = Convert.ToSingle(dfDoubleValue); Array.Copy(Hfa.LittleEndian(dfNumber), 0, data, dataOffset + indexValue * 4, 4); } break; case 'd': // Double (float 64) { Array.Copy(Hfa.LittleEndian(dfDoubleValue), 0, data, dataOffset + 8 * indexValue, 8); } break; case 'o': // object { if (_itemObjectType == null) break; int nExtraOffset = 0; if (_itemObjectType.NumBytes > 0) { nExtraOffset = _itemObjectType.NumBytes * indexValue; } else { for (int iIndexCounter = 0; iIndexCounter < indexValue; iIndexCounter++) { nExtraOffset += _itemObjectType.GetInstBytes(data, dataOffset + nExtraOffset); } } if (!string.IsNullOrEmpty(sField)) { _itemObjectType.SetInstValue(sField, data, dataOffset + nExtraOffset, dataSize - nExtraOffset, reqType, value); } } break; default: throw new ArgumentException(); } } /// <summary> /// Scans through the array and estimates the byte size of the field in this case. /// </summary> /// <param name="data"></param> /// <param name="dataOffset"></param> /// <returns></returns> public int GetInstBytes(byte[] data, long dataOffset) { int nCount; int nInstBytes = 0; long offset = dataOffset; // Hard sized fields just return their constant size if (NumBytes > -1) return NumBytes; // Pointers have a 4 byte integer count and a 4 byte uint offset if (_pointer != '\0') { nCount = Hfa.ReadInt32(data, offset); offset += 8; nInstBytes += 8; } else { // Anything other than a pointer only can have one item. nCount = 1; } if (_itemType == 'b' && nCount != 0) { // BASEDATA int nRows = Hfa.ReadInt32(data, offset); offset += 4; int nColumns = Hfa.ReadInt32(data, offset); offset += 4; HfaEPT baseItemType = (HfaEPT)Hfa.ReadInt16(data, offset); nInstBytes += 12; nInstBytes += ((baseItemType.GetBitCount() + 7) / 8) * nRows * nColumns; } else if (_itemObjectType == null) { nInstBytes += nCount * HfaDictionary.GetItemSize(_itemType); } else { for (int i = 0; i < nCount; i++) { nInstBytes += _itemObjectType.GetInstBytes(data, offset + nInstBytes); } } return nInstBytes; } /// <summary> /// Gets the count for a particular instance of a field. This will normally be /// the built in value, but for variable fields, this is extracted from the /// data itself. /// </summary> /// <param name="data"></param> /// <param name="dataOffset"></param> /// <returns></returns> public int GetInstCount(byte[] data, long dataOffset) { if (_pointer == '\0') { return _itemCount; } else if (_itemType == 'b') { int numRows = Hfa.ReadInt32(data, dataOffset + 8); int numColumns = Hfa.ReadInt32(data, dataOffset + 12); return numRows * numColumns; } else { return Hfa.ReadInt32(data, dataOffset); } } /// <summary> /// /// </summary> /// <param name="pszField"></param> /// <param name="nIndexValue"></param> /// <param name="data"></param> /// <param name="dataOffset"></param> /// <param name="nDataSize"></param> /// <param name="reqType"></param> /// <param name="pReqReturn"></param> /// <param name="extraOffset">This is used in the case of 'object' pointers where the indexed object is further in the data block.</param> /// <returns></returns> /// <exception cref="HfaInvalidCountException">Occurs if the count is less than zero for the header of a block of base data</exception> public bool ExtractInstValue(string pszField, int nIndexValue, byte[] data, long dataOffset, int nDataSize, char reqType, out object pReqReturn, out int extraOffset) { extraOffset = 0; pReqReturn = null; string returnString = null; int nIntRet = 0; double dfDoubleRet = 0.0; // it doesn't appear like remove this line will have side effects. //int size = GetInstBytes(data, dataOffset); int nInstItemCount = GetInstCount(data, dataOffset); byte[] rawData = null; long offset = dataOffset; // Check the index value is valid. Eventually this will have to account for variable fields. if (nIndexValue < 0 || nIndexValue >= nInstItemCount) return false; // if this field contains a pointer then we will adjust the data offset relative to it. if (_pointer != '\0') { long nOffset = Hfa.ReadUInt32(data, dataOffset + 4); if (nOffset != (uint)(dataOffset + 8)) { // It seems there was originally an exception that would have gone here. // Original exception would have been pszFieldname.pszField points at nOffset, not nDataOffset +8 as expected. } offset += 8; dataOffset += 8; nDataSize -= 8; } // pointers to chara or uchar arrays are read as strings and then handled as a special case. if ((_itemType == 'c' || _itemType == 'C') && reqType == 's') { // Ok, nasty, the original code simply "pointed" to the byte data at this point and cast the pointer. // We probably need to cycle through until we reach the null character. List<char> chars = new List<char>(); while ((char)data[offset] != '\0') { chars.Add((char)data[offset]); offset++; dataOffset++; } pReqReturn = new String(chars.ToArray()); } switch (_itemType) { case 'c': case 'C': nIntRet = data[dataOffset + nIndexValue]; dfDoubleRet = nIntRet; break; case 'e': case 's': { int nNumber = Hfa.ReadUInt16(data, dataOffset + nIndexValue * 2); nIntRet = nNumber; dfDoubleRet = nIntRet; if (_itemType == 'e' && nIntRet >= 0 && nIntRet < _enumNames.Count()) { returnString = _enumNames[nIntRet]; } } break; case 'S': { short nNumber = Hfa.ReadInt16(data, dataOffset + nIndexValue * 2); nIntRet = nNumber; dfDoubleRet = nNumber; } break; case 't': case 'l': { long nNumber = Hfa.ReadUInt32(data, dataOffset + nIndexValue * 2); nIntRet = (int)nNumber; dfDoubleRet = nNumber; } break; case 'L': { int nNumber = Hfa.ReadInt32(data, dataOffset + nIndexValue * 2); nIntRet = nNumber; dfDoubleRet = nNumber; } break; case 'f': { float fNumber = Hfa.ReadSingle(data, dataOffset + nIndexValue * 4); dfDoubleRet = fNumber; nIntRet = Convert.ToInt32(fNumber); } break; case 'd': { dfDoubleRet = Hfa.ReadDouble(data, dataOffset + nInstItemCount * 8); nIntRet = Convert.ToInt32(dfDoubleRet); } break; case 'b': // BASE DATA { int nRows = Hfa.ReadInt32(data, dataOffset); int nColumns = Hfa.ReadInt32(data, dataOffset + 4); if (nIndexValue < 0 || nIndexValue >= nRows * nColumns) return false; HfaEPT type = (HfaEPT)Hfa.ReadUInt16(data, dataOffset + 8); // Ignore the 2 byte objecttype value dataOffset += 12; if (nRows < 0 || nColumns < 0) throw new HfaInvalidCountException(nRows, nColumns); switch (type) { case HfaEPT.U8: dfDoubleRet = data[dataOffset + nIndexValue]; nIntRet = data[offset + nIndexValue]; break; case HfaEPT.S16: short tShort = Hfa.ReadInt16(data, dataOffset + nIndexValue * 2); dfDoubleRet = tShort; nIntRet = tShort; break; case HfaEPT.U16: int tUShort = Hfa.ReadUInt16(data, dataOffset + nIndexValue * 2); dfDoubleRet = tUShort; nIntRet = tUShort; break; case HfaEPT.Single: Single tSingle = Hfa.ReadSingle(data, dataOffset + nIndexValue * 4); dfDoubleRet = tSingle; nIntRet = Convert.ToInt32(tSingle); break; case HfaEPT.Double: dfDoubleRet = Hfa.ReadDouble(data, dataOffset + nIndexValue * 8); nIntRet = Convert.ToInt32(dfDoubleRet); break; default: pReqReturn = null; return false; } } break; case 'o': if (_itemObjectType != null) { if (_itemObjectType.NumBytes > 0) { extraOffset = _itemObjectType.NumBytes * nIndexValue; } else { for (int iIndexCounter = 0; iIndexCounter < nIndexValue; iIndexCounter++) { extraOffset += _itemObjectType.GetInstBytes(data, dataOffset + extraOffset); } } int len = _itemObjectType.GetInstBytes(data, dataOffset + extraOffset); rawData = new byte[len]; Array.Copy(data, dataOffset + extraOffset, rawData, 0, len); if (!string.IsNullOrEmpty(pszField)) { return (_itemObjectType.ExtractInstValue(pszField, rawData, 0, rawData.Length, reqType, out pReqReturn)); } } break; default: return false; } // Handle appropriate representations switch (reqType) { case 's': { if (returnString == null) { returnString = nIntRet.ToString(); } pReqReturn = returnString; return true; } case 'd': pReqReturn = dfDoubleRet; return true; case 'i': pReqReturn = nIntRet; return true; case 'p': pReqReturn = rawData; return true; default: return false; } } /// <summary> /// Parses the input string into a valid HfaField, or returns null /// if one could not be created. /// </summary> /// <param name="input"></param> /// <returns></returns> public string Initialize(string input) { int length = input.Length; int start = 0; // Read the number if (!input.Contains(":")) return null; _itemCount = short.Parse(input.ExtractTo(ref start, ":")); // is this a pointer? if (input[start] == 'p' || input[start] == '*') { start += 1; _pointer = input[start]; } // Get the general type start += 1; if (start == length) return null; _itemType = input[start]; if (!"124cCesStlLfdmMbox".Contains(_itemType.ToString())) { throw new HfaFieldTypeException(_itemType); } // If this is an object, we extract the type of the object if (_itemType == 'o') { _itemObjectTypeString = input.ExtractTo(ref start, ","); } // If this is an inline object, we need to skip past the // definition, and then extract the object class name. // we ignore the actual definition, so if the object type isn't // already defined, things will not work properly. See the // file lceugr250)00)pct.aus for an example of inline defs. if (_itemType == 'x' && input[start] == '{') { int braceDepth = 1; start += 1; // Skip past the definition in braces while (braceDepth > 0 && start < input.Length) { if (input[start] == '{') braceDepth++; if (input[start] == '}') braceDepth--; start++; } _itemType = 'o'; _itemObjectTypeString = input.ExtractTo(ref start, ","); } // If this is an enumeration, we have to extract all the values. if (_itemType == 'e') { if (!input.Contains(":")) return null; int enumCount = int.Parse(input.ExtractTo(ref start, ":")); if (_enumNames == null) _enumNames = new List<string>(); for (int ienum = 0; ienum < enumCount; ienum++) { _enumNames.Add(input.ExtractTo(ref start, ",")); } } // Extract the field name _fieldName = input.ExtractTo(ref start, ","); // Return whatever is left in the string, which should be a new field. return input.Substring(start, input.Length - start); } #endregion #region Properties /// <summary> /// Gets or sets the short integer number of bytes /// </summary> public int NumBytes { get { return _numBytes; } set { _numBytes = value; } } /// <summary> /// Gets or sets the short integer item count /// </summary> public int ItemCount { get { return _itemCount; } set { _itemCount = value; } } /// <summary> /// Gets or sets '\0', '*' or 'p' /// </summary> public char Pointer { get { return _pointer; } set { _pointer = value; } } /// <summary> /// Gets or sets 1|2|4|e|... /// </summary> public char ItemType { get { return _itemType; } set { _itemType = value; } } /// <summary> /// If ItemType == 'o' /// </summary> public string ItemObjectTypeString { get { return _itemObjectTypeString; } set { _itemObjectTypeString = value; } } /// <summary> /// Gets or sets the item object type /// </summary> public HfaType ItemObjectType { get { return _itemObjectType; } set { _itemObjectType = value; } } /// <summary> /// Normally null unless this is an enum /// </summary> public List<string> EnumNames { get { return _enumNames; } set { _enumNames = value; } } /// <summary> /// Gets or sets the field name /// </summary> public string FieldName { get { return _fieldName; } set { _fieldName = value; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; using System.IO; using System.Runtime; using System.ServiceModel.Security; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal abstract class FramingDuplexSessionChannel : TransportDuplexSessionChannel { private static EndpointAddress s_anonymousEndpointAddress = new EndpointAddress(EndpointAddress.AnonymousUri, new AddressHeader[0]); private IConnection _connection; private bool _exposeConnectionProperty; private FramingDuplexSessionChannel(ChannelManagerBase manager, IConnectionOrientedTransportFactorySettings settings, EndpointAddress localAddress, Uri localVia, EndpointAddress remoteAddresss, Uri via, bool exposeConnectionProperty) : base(manager, settings, localAddress, localVia, remoteAddresss, via) { _exposeConnectionProperty = exposeConnectionProperty; } protected FramingDuplexSessionChannel(ChannelManagerBase factory, IConnectionOrientedTransportFactorySettings settings, EndpointAddress remoteAddresss, Uri via, bool exposeConnectionProperty) : this(factory, settings, s_anonymousEndpointAddress, settings.MessageVersion.Addressing == AddressingVersion.None ? null : new Uri("http://www.w3.org/2005/08/addressing/anonymous"), remoteAddresss, via, exposeConnectionProperty) { this.Session = FramingConnectionDuplexSession.CreateSession(this, settings.Upgrade); } protected IConnection Connection { get { return _connection; } set { _connection = value; } } protected override bool IsStreamedOutput { get { return false; } } protected override void CloseOutputSessionCore(TimeSpan timeout) { Connection.Write(SessionEncoder.EndBytes, 0, SessionEncoder.EndBytes.Length, true, timeout); } protected override async Task CloseOutputSessionCoreAsync(TimeSpan timeout) { var tcs = new TaskCompletionSource<bool>(); AsyncCompletionResult result = Connection.BeginWrite(SessionEncoder.EndBytes, 0, SessionEncoder.EndBytes.Length, true, timeout, OnIoComplete, tcs); if (result == AsyncCompletionResult.Completed) { tcs.TrySetResult(true); } await tcs.Task; Connection.EndWrite(); } internal static void OnIoComplete(object state) { if (state == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("state"); } var tcs = state as TaskCompletionSource<bool>; if (tcs == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("state", SR.SPS_InvalidAsyncResult); } tcs.TrySetResult(true); } protected override void CompleteClose(TimeSpan timeout) { this.ReturnConnectionIfNecessary(false, timeout); } protected override void PrepareMessage(Message message) { if (_exposeConnectionProperty) { message.Properties[ConnectionMessageProperty.Name] = _connection; } base.PrepareMessage(message); } protected override void OnSendCore(Message message, TimeSpan timeout) { bool allowOutputBatching; ArraySegment<byte> messageData; allowOutputBatching = message.Properties.AllowOutputBatching; messageData = this.EncodeMessage(message); this.Connection.Write(messageData.Array, messageData.Offset, messageData.Count, !allowOutputBatching, timeout, this.BufferManager); } protected override AsyncCompletionResult BeginCloseOutput(TimeSpan timeout, Action<object> callback, object state) { return this.Connection.BeginWrite(SessionEncoder.EndBytes, 0, SessionEncoder.EndBytes.Length, true, timeout, callback, state); } protected override void FinishWritingMessage() { this.Connection.EndWrite(); } protected override AsyncCompletionResult StartWritingBufferedMessage(Message message, ArraySegment<byte> messageData, bool allowOutputBatching, TimeSpan timeout, Action<object> callback, object state) { return this.Connection.BeginWrite(messageData.Array, messageData.Offset, messageData.Count, !allowOutputBatching, timeout, callback, state); } protected override AsyncCompletionResult StartWritingStreamedMessage(Message message, TimeSpan timeout, Action<object> callback, object state) { Contract.Assert(false, "Streamed output should never be called in this channel."); throw new InvalidOperationException(); } protected override ArraySegment<byte> EncodeMessage(Message message) { ArraySegment<byte> messageData = MessageEncoder.WriteMessage(message, int.MaxValue, this.BufferManager, SessionEncoder.MaxMessageFrameSize); messageData = SessionEncoder.EncodeMessageFrame(messageData); return messageData; } internal class FramingConnectionDuplexSession : ConnectionDuplexSession { private FramingConnectionDuplexSession(FramingDuplexSessionChannel channel) : base(channel) { } public static FramingConnectionDuplexSession CreateSession(FramingDuplexSessionChannel channel, StreamUpgradeProvider upgrade) { StreamSecurityUpgradeProvider security = upgrade as StreamSecurityUpgradeProvider; if (security == null) { return new FramingConnectionDuplexSession(channel); } throw ExceptionHelper.PlatformNotSupported("SecureConnectionDuplexSession is not supported."); } } } internal class ClientFramingDuplexSessionChannel : FramingDuplexSessionChannel { private IConnectionOrientedTransportChannelFactorySettings _settings; private ClientDuplexDecoder _decoder; private StreamUpgradeProvider _upgrade; private ConnectionPoolHelper _connectionPoolHelper; private bool _flowIdentity; public ClientFramingDuplexSessionChannel(ChannelManagerBase factory, IConnectionOrientedTransportChannelFactorySettings settings, EndpointAddress remoteAddresss, Uri via, IConnectionInitiator connectionInitiator, ConnectionPool connectionPool, bool exposeConnectionProperty, bool flowIdentity) : base(factory, settings, remoteAddresss, via, exposeConnectionProperty) { _settings = settings; this.MessageEncoder = settings.MessageEncoderFactory.CreateSessionEncoder(); _upgrade = settings.Upgrade; _flowIdentity = flowIdentity; _connectionPoolHelper = new DuplexConnectionPoolHelper(this, connectionPool, connectionInitiator); } private ArraySegment<byte> CreatePreamble() { EncodedVia encodedVia = new EncodedVia(this.Via.AbsoluteUri); EncodedContentType encodedContentType = EncodedContentType.Create(this.MessageEncoder.ContentType); // calculate preamble length int startSize = ClientDuplexEncoder.ModeBytes.Length + SessionEncoder.CalcStartSize(encodedVia, encodedContentType); int preambleEndOffset = 0; if (_upgrade == null) { preambleEndOffset = startSize; startSize += ClientDuplexEncoder.PreambleEndBytes.Length; } byte[] startBytes = Fx.AllocateByteArray(startSize); Buffer.BlockCopy(ClientDuplexEncoder.ModeBytes, 0, startBytes, 0, ClientDuplexEncoder.ModeBytes.Length); SessionEncoder.EncodeStart(startBytes, ClientDuplexEncoder.ModeBytes.Length, encodedVia, encodedContentType); if (preambleEndOffset > 0) { Buffer.BlockCopy(ClientDuplexEncoder.PreambleEndBytes, 0, startBytes, preambleEndOffset, ClientDuplexEncoder.PreambleEndBytes.Length); } return new ArraySegment<byte>(startBytes, 0, startSize); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return OnOpenAsync(timeout).ToApm(callback, state); } protected override void OnEndOpen(IAsyncResult result) { result.ToApmEnd(); } public override T GetProperty<T>() { T result = base.GetProperty<T>(); if (result == null && _upgrade != null) { result = _upgrade.GetProperty<T>(); } return result; } private async Task<IConnection> SendPreambleAsync(IConnection connection, ArraySegment<byte> preamble, TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout); // initialize a new decoder _decoder = new ClientDuplexDecoder(0); byte[] ackBuffer = new byte[1]; var tcs = new TaskCompletionSource<bool>(); var result = connection.BeginWrite(preamble.Array, preamble.Offset, preamble.Count, true, timeoutHelper.RemainingTime(), FramingDuplexSessionChannel.OnIoComplete, tcs); if (result == AsyncCompletionResult.Completed) { tcs.SetResult(true); } await tcs.Task; connection.EndWrite(); // read ACK tcs = new TaskCompletionSource<bool>(); //ackBuffer result = connection.BeginRead(0, ackBuffer.Length, timeoutHelper.RemainingTime(), OnIoComplete, tcs); if (result == AsyncCompletionResult.Completed) { tcs.SetResult(true); } await tcs.Task; int ackBytesRead = connection.EndRead(); Buffer.BlockCopy((Array)connection.AsyncReadBuffer, 0, (Array)ackBuffer, 0, ackBytesRead); if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, _decoder, Via)) { await ConnectionUpgradeHelper.DecodeFramingFaultAsync(_decoder, connection, Via, MessageEncoder.ContentType, timeoutHelper.RemainingTime()); } return connection; } private IConnection SendPreamble(IConnection connection, ArraySegment<byte> preamble, ref TimeoutHelper timeoutHelper) { // initialize a new decoder _decoder = new ClientDuplexDecoder(0); byte[] ackBuffer = new byte[1]; connection.Write(preamble.Array, preamble.Offset, preamble.Count, true, timeoutHelper.RemainingTime()); // read ACK int ackBytesRead = connection.Read(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime()); if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, _decoder, Via)) { ConnectionUpgradeHelper.DecodeFramingFault(_decoder, connection, Via, MessageEncoder.ContentType, ref timeoutHelper); } return connection; } private IAsyncResult BeginSendPreamble(IConnection connection, ArraySegment<byte> preamble, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state) { return SendPreambleAsync(connection, preamble, timeoutHelper.RemainingTime()).ToApm(callback, state); } private IConnection EndSendPreamble(IAsyncResult result) { return result.ToApmEnd<IConnection>(); } protected internal override async Task OnOpenAsync(TimeSpan timeout) { IConnection connection; try { connection = await _connectionPoolHelper.EstablishConnectionAsync(timeout); } catch (TimeoutException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TimeoutException(SR.Format(SR.TimeoutOnOpen, timeout), exception)); } bool connectionAccepted = false; try { AcceptConnection(connection); connectionAccepted = true; } finally { if (!connectionAccepted) { _connectionPoolHelper.Abort(); } } } protected override void OnOpen(TimeSpan timeout) { IConnection connection; try { connection = _connectionPoolHelper.EstablishConnection(timeout); } catch (TimeoutException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TimeoutException(SR.Format(SR.TimeoutOnOpen, timeout), exception)); } bool connectionAccepted = false; try { AcceptConnection(connection); connectionAccepted = true; } finally { if (!connectionAccepted) { _connectionPoolHelper.Abort(); } } } protected override void ReturnConnectionIfNecessary(bool abort, TimeSpan timeout) { lock (ThisLock) { if (abort) { _connectionPoolHelper.Abort(); } else { _connectionPoolHelper.Close(timeout); } } } private void AcceptConnection(IConnection connection) { base.SetMessageSource(new ClientDuplexConnectionReader(this, connection, _decoder, _settings, MessageEncoder)); lock (ThisLock) { if (this.State != CommunicationState.Opening) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationObjectAbortedException(SR.Format(SR.DuplexChannelAbortedDuringOpen, this.Via))); } this.Connection = connection; } } protected override void PrepareMessage(Message message) { base.PrepareMessage(message); } internal class DuplexConnectionPoolHelper : ConnectionPoolHelper { private ClientFramingDuplexSessionChannel _channel; private ArraySegment<byte> _preamble; public DuplexConnectionPoolHelper(ClientFramingDuplexSessionChannel channel, ConnectionPool connectionPool, IConnectionInitiator connectionInitiator) : base(connectionPool, connectionInitiator, channel.Via) { _channel = channel; _preamble = channel.CreatePreamble(); } protected override TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException) { return new TimeoutException(SR.Format(SR.OpenTimedOutEstablishingTransportSession, timeout, _channel.Via.AbsoluteUri), innerException); } protected override IConnection AcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper) { return _channel.SendPreamble(connection, _preamble, ref timeoutHelper); } protected override Task<IConnection> AcceptPooledConnectionAsync(IConnection connection, ref TimeoutHelper timeoutHelper) { return _channel.SendPreambleAsync(connection, _preamble, timeoutHelper.RemainingTime()); } } } // used by StreamedFramingRequestChannel and ClientFramingDuplexSessionChannel internal class ConnectionUpgradeHelper { public static async Task DecodeFramingFaultAsync(ClientFramingDecoder decoder, IConnection connection, Uri via, string contentType, TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout); ValidateReadingFaultString(decoder); var tcs = new TaskCompletionSource<bool>(); var result = connection.BeginRead(0, Math.Min(FaultStringDecoder.FaultSizeQuota, connection.AsyncReadBufferSize), timeoutHelper.RemainingTime(), FramingDuplexSessionChannel.OnIoComplete, tcs); if (result == AsyncCompletionResult.Completed) { tcs.TrySetResult(true); } await tcs.Task; int offset = 0; int size = connection.EndRead(); while (size > 0) { int bytesDecoded = decoder.Decode(connection.AsyncReadBuffer, offset, size); offset += bytesDecoded; size -= bytesDecoded; if (decoder.CurrentState == ClientFramingDecoderState.Fault) { ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( FaultStringDecoder.GetFaultException(decoder.Fault, via.ToString(), contentType)); } else { if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString) { throw new Exception("invalid framing client state machine"); } if (size == 0) { offset = 0; tcs = new TaskCompletionSource<bool>(); result = connection.BeginRead(0, Math.Min(FaultStringDecoder.FaultSizeQuota, connection.AsyncReadBufferSize), timeoutHelper.RemainingTime(), FramingDuplexSessionChannel.OnIoComplete, tcs); if (result == AsyncCompletionResult.Completed) { tcs.TrySetResult(true); } await tcs.Task; size = connection.EndRead(); } } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException()); } public static void DecodeFramingFault(ClientFramingDecoder decoder, IConnection connection, Uri via, string contentType, ref TimeoutHelper timeoutHelper) { ValidateReadingFaultString(decoder); int offset = 0; byte[] faultBuffer = Fx.AllocateByteArray(FaultStringDecoder.FaultSizeQuota); int size = connection.Read(faultBuffer, offset, faultBuffer.Length, timeoutHelper.RemainingTime()); while (size > 0) { int bytesDecoded = decoder.Decode(faultBuffer, offset, size); offset += bytesDecoded; size -= bytesDecoded; if (decoder.CurrentState == ClientFramingDecoderState.Fault) { ConnectionUtilities.CloseNoThrow(connection, timeoutHelper.RemainingTime()); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( FaultStringDecoder.GetFaultException(decoder.Fault, via.ToString(), contentType)); } else { if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString) { throw new Exception("invalid framing client state machine"); } if (size == 0) { offset = 0; size = connection.Read(faultBuffer, offset, faultBuffer.Length, timeoutHelper.RemainingTime()); } } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException()); } public static bool InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, ref IConnection connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, ref TimeoutHelper timeoutHelper) { string upgradeContentType = upgradeInitiator.GetNextUpgrade(); while (upgradeContentType != null) { EncodedUpgrade encodedUpgrade = new EncodedUpgrade(upgradeContentType); // write upgrade request framing for synchronization connection.Write(encodedUpgrade.EncodedBytes, 0, encodedUpgrade.EncodedBytes.Length, true, timeoutHelper.RemainingTime()); byte[] buffer = new byte[1]; // read upgrade response framing int size = connection.Read(buffer, 0, buffer.Length, timeoutHelper.RemainingTime()); if (!ValidateUpgradeResponse(buffer, size, decoder)) // we have a problem { return false; } // initiate wire upgrade ConnectionStream connectionStream = new ConnectionStream(connection, defaultTimeouts); Stream upgradedStream = upgradeInitiator.InitiateUpgrade(connectionStream); // and re-wrap connection connection = new StreamConnection(upgradedStream, connectionStream); upgradeContentType = upgradeInitiator.GetNextUpgrade(); } return true; } private static void ValidateReadingFaultString(ClientFramingDecoder decoder) { if (decoder.CurrentState != ClientFramingDecoderState.ReadingFaultString) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new System.ServiceModel.Security.MessageSecurityException( SR.ServerRejectedUpgradeRequest)); } } public static bool ValidatePreambleResponse(byte[] buffer, int count, ClientFramingDecoder decoder, Uri via) { if (count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.ServerRejectedSessionPreamble, via), decoder.CreatePrematureEOFException())); } // decode until the framing byte has been processed (it always will be) while (decoder.Decode(buffer, 0, count) == 0) { // do nothing } if (decoder.CurrentState != ClientFramingDecoderState.Start) // we have a problem { return false; } return true; } private static bool ValidateUpgradeResponse(byte[] buffer, int count, ClientFramingDecoder decoder) { if (count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.ServerRejectedUpgradeRequest, decoder.CreatePrematureEOFException())); } // decode until the framing byte has been processed (it always will be) while (decoder.Decode(buffer, 0, count) == 0) { // do nothing } if (decoder.CurrentState != ClientFramingDecoderState.UpgradeResponse) // we have a problem { return false; } return true; } } }
using OpenMetaverse; /* * 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 copyrightD * 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; namespace OpenSim.Region.Physics.BulletSPlugin { public sealed class BSTerrainMesh : BSTerrainPhys { static string LogHeader = "[BULLETSIM TERRAIN MESH]"; private float[] m_savedHeightMap; int m_sizeX; int m_sizeY; BulletShape m_terrainShape; BulletBody m_terrainBody; public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, Vector3 regionSize) : base(physicsScene, regionBase, id) { } public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id /* parameters for making mesh */) : base(physicsScene, regionBase, id) { } // Create terrain mesh from a heightmap. public BSTerrainMesh(BSScene physicsScene, Vector3 regionBase, uint id, float[] initialMap, Vector3 minCoords, Vector3 maxCoords) : base(physicsScene, regionBase, id) { int indicesCount; int[] indices; int verticesCount; float[] vertices; m_savedHeightMap = initialMap; m_sizeX = (int)(maxCoords.X - minCoords.X); m_sizeY = (int)(maxCoords.Y - minCoords.Y); bool meshCreationSuccess = false; if (BSParam.TerrainMeshMagnification == 1) { // If a magnification of one, use the old routine that is tried and true. meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh(m_physicsScene, initialMap, m_sizeX, m_sizeY, // input size Vector3.Zero, // base for mesh out indicesCount, out indices, out verticesCount, out vertices); } else { // Other magnifications use the newer routine meshCreationSuccess = BSTerrainMesh.ConvertHeightmapToMesh2(m_physicsScene, initialMap, m_sizeX, m_sizeY, // input size BSParam.TerrainMeshMagnification, physicsScene.TerrainManager.DefaultRegionSize, Vector3.Zero, // base for mesh out indicesCount, out indices, out verticesCount, out vertices); } if (!meshCreationSuccess) { // DISASTER!! m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedConversionOfHeightmap,id={1}", BSScene.DetailLogZero, ID); m_physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } m_physicsScene.DetailLog("{0},BSTerrainMesh.create,meshed,id={1},indices={2},indSz={3},vertices={4},vertSz={5}", BSScene.DetailLogZero, ID, indicesCount, indices.Length, verticesCount, vertices.Length); m_terrainShape = m_physicsScene.PE.CreateMeshShape(m_physicsScene.World, indicesCount, indices, verticesCount, vertices); if (!m_terrainShape.HasPhysicalShape) { // DISASTER!! m_physicsScene.DetailLog("{0},BSTerrainMesh.create,failedCreationOfShape,id={1}", BSScene.DetailLogZero, ID); m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain mesh! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } Vector3 pos = regionBase; Quaternion rot = Quaternion.Identity; m_terrainBody = m_physicsScene.PE.CreateBodyWithDefaultMotionState(m_terrainShape, ID, pos, rot); if (!m_terrainBody.HasPhysicalBody) { // DISASTER!! m_physicsScene.Logger.ErrorFormat("{0} Failed creation of terrain body! base={1}", LogHeader, TerrainBase); // Something is very messed up and a crash is in our future. return; } physicsScene.PE.SetShapeCollisionMargin(m_terrainShape, BSParam.TerrainCollisionMargin); // Set current terrain attributes m_physicsScene.PE.SetFriction(m_terrainBody, BSParam.TerrainFriction); m_physicsScene.PE.SetHitFraction(m_terrainBody, BSParam.TerrainHitFraction); m_physicsScene.PE.SetRestitution(m_terrainBody, BSParam.TerrainRestitution); m_physicsScene.PE.SetContactProcessingThreshold(m_terrainBody, BSParam.TerrainContactProcessingThreshold); m_physicsScene.PE.SetCollisionFlags(m_terrainBody, CollisionFlags.CF_STATIC_OBJECT); // Static objects are not very massive. m_physicsScene.PE.SetMassProps(m_terrainBody, 0f, Vector3.Zero); // Put the new terrain to the world of physical objects m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, m_terrainBody); // Redo its bounding box now that it is in the world m_physicsScene.PE.UpdateSingleAabb(m_physicsScene.World, m_terrainBody); m_terrainBody.collisionType = CollisionType.Terrain; m_terrainBody.ApplyCollisionMask(m_physicsScene); if (BSParam.UseSingleSidedMeshes) { m_physicsScene.DetailLog("{0},BSTerrainMesh.settingCustomMaterial,id={1}", BSScene.DetailLogZero, id); m_physicsScene.PE.AddToCollisionFlags(m_terrainBody, CollisionFlags.CF_CUSTOM_MATERIAL_CALLBACK); } // Make it so the terrain will not move or be considered for movement. m_physicsScene.PE.ForceActivationState(m_terrainBody, ActivationState.DISABLE_SIMULATION); } public override void Dispose() { if (m_terrainBody.HasPhysicalBody) { m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, m_terrainBody); // Frees both the body and the shape. m_physicsScene.PE.DestroyObject(m_physicsScene.World, m_terrainBody); m_terrainBody.Clear(); m_terrainShape.Clear(); } } public override float GetTerrainHeightAtXYZ(Vector3 pos) { // For the moment use the saved heightmap to get the terrain height. // TODO: raycast downward to find the true terrain below the position. float ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; int mapIndex = (int)pos.Y * m_sizeY + (int)pos.X; try { ret = m_savedHeightMap[mapIndex]; } catch { // Sometimes they give us wonky values of X and Y. Give a warning and return something. m_physicsScene.Logger.WarnFormat("{0} Bad request for terrain height. terrainBase={1}, pos={2}", LogHeader, TerrainBase, pos); ret = BSTerrainManager.HEIGHT_GETHEIGHT_RET; } return ret; } // The passed position is relative to the base of the region. public override float GetWaterLevelAtXYZ(Vector3 pos) { return m_physicsScene.SimpleWaterLevel; } // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). // Return 'true' if successfully created. public static bool ConvertHeightmapToMesh( BSScene physicsScene, float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap Vector3 extentBase, // base to be added to all vertices out int indicesCountO, out int[] indicesO, out int verticesCountO, out float[] verticesO) { bool ret = false; int indicesCount = 0; int verticesCount = 0; int[] indices = new int[0]; float[] vertices = new float[0]; // Simple mesh creation which assumes magnification == 1. // TODO: do a more general solution that scales, adds new vertices and smoothes the result. // Create an array of vertices that is sizeX+1 by sizeY+1 (note the loop // from zero to <= sizeX). The triangle indices are then generated as two triangles // per heightmap point. There are sizeX by sizeY of these squares. The extra row and // column of vertices are used to complete the triangles of the last row and column // of the heightmap. try { // One vertice per heightmap value plus the vertices off the side and bottom edge. int totalVertices = (sizeX + 1) * (sizeY + 1); vertices = new float[totalVertices * 3]; int totalIndices = sizeX * sizeY * 6; indices = new int[totalIndices]; if (physicsScene != null) physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh,totVert={1},totInd={2},extentBase={3}", BSScene.DetailLogZero, totalVertices, totalIndices, extentBase); float minHeight = float.MaxValue; // Note that sizeX+1 vertices are created since there is land between this and the next region. for (int yy = 0; yy <= sizeY; yy++) { for (int xx = 0; xx <= sizeX; xx++) // Hint: the "<=" means we go around sizeX + 1 times { int offset = yy * sizeX + xx; // Extend the height with the height from the last row or column if (yy == sizeY) offset -= sizeX; if (xx == sizeX) offset -= 1; float height = heightMap[offset]; minHeight = Math.Min(minHeight, height); vertices[verticesCount + 0] = (float)xx + extentBase.X; vertices[verticesCount + 1] = (float)yy + extentBase.Y; vertices[verticesCount + 2] = height + extentBase.Z; verticesCount += 3; } } verticesCount = verticesCount / 3; for (int yy = 0; yy < sizeY; yy++) { for (int xx = 0; xx < sizeX; xx++) { int offset = yy * (sizeX + 1) + xx; // Each vertices is presumed to be the upper left corner of a box of two triangles indices[indicesCount + 0] = offset; indices[indicesCount + 1] = offset + 1; indices[indicesCount + 2] = offset + sizeX + 1; // accounting for the extra column indices[indicesCount + 3] = offset + 1; indices[indicesCount + 4] = offset + sizeX + 2; indices[indicesCount + 5] = offset + sizeX + 1; indicesCount += 6; } } ret = true; } catch (Exception e) { if (physicsScene != null) physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}", LogHeader, physicsScene.RegionName, extentBase, e); } indicesCountO = indicesCount; indicesO = indices; verticesCountO = verticesCount; verticesO = vertices; return ret; } private class HeightMapGetter { private float[] m_heightMap; private int m_sizeX; private int m_sizeY; public HeightMapGetter(float[] pHeightMap, int pSizeX, int pSizeY) { m_heightMap = pHeightMap; m_sizeX = pSizeX; m_sizeY = pSizeY; } // The heightmap is extended as an infinite plane at the last height public float GetHeight(int xx, int yy) { int offset = 0; // Extend the height with the height from the last row or column if (yy >= m_sizeY) if (xx >= m_sizeX) offset = (m_sizeY - 1) * m_sizeX + (m_sizeX - 1); else offset = (m_sizeY - 1) * m_sizeX + xx; else if (xx >= m_sizeX) offset = yy * m_sizeX + (m_sizeX - 1); else offset = yy * m_sizeX + xx; return m_heightMap[offset]; } } // Convert the passed heightmap to mesh information suitable for CreateMeshShape2(). // Version that handles magnification. // Return 'true' if successfully created. public static bool ConvertHeightmapToMesh2( BSScene physicsScene, float[] heightMap, int sizeX, int sizeY, // parameters of incoming heightmap int magnification, // number of vertices per heighmap step Vector3 extent, // dimensions of the output mesh Vector3 extentBase, // base to be added to all vertices out int indicesCountO, out int[] indicesO, out int verticesCountO, out float[] verticesO) { bool ret = false; int indicesCount = 0; int verticesCount = 0; int[] indices = new int[0]; float[] vertices = new float[0]; HeightMapGetter hmap = new HeightMapGetter(heightMap, sizeX, sizeY); // The vertices dimension of the output mesh int meshX = sizeX * magnification; int meshY = sizeY * magnification; // The output size of one mesh step float meshXStep = extent.X / meshX; float meshYStep = extent.Y / meshY; // Create an array of vertices that is meshX+1 by meshY+1 (note the loop // from zero to <= meshX). The triangle indices are then generated as two triangles // per heightmap point. There are meshX by meshY of these squares. The extra row and // column of vertices are used to complete the triangles of the last row and column // of the heightmap. try { // Vertices for the output heightmap plus one on the side and bottom to complete triangles int totalVertices = (meshX + 1) * (meshY + 1); vertices = new float[totalVertices * 3]; int totalIndices = meshX * meshY * 6; indices = new int[totalIndices]; if (physicsScene != null) physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,inSize={1},outSize={2},totVert={3},totInd={4},extentBase={5}", BSScene.DetailLogZero, new Vector2(sizeX, sizeY), new Vector2(meshX, meshY), totalVertices, totalIndices, extentBase); float minHeight = float.MaxValue; // Note that sizeX+1 vertices are created since there is land between this and the next region. // Loop through the output vertices and compute the mediun height in between the input vertices for (int yy = 0; yy <= meshY; yy++) { for (int xx = 0; xx <= meshX; xx++) // Hint: the "<=" means we go around sizeX + 1 times { float offsetY = (float)yy * (float)sizeY / (float)meshY; // The Y that is closest to the mesh point int stepY = (int)offsetY; float fractionalY = offsetY - (float)stepY; float offsetX = (float)xx * (float)sizeX / (float)meshX; // The X that is closest to the mesh point int stepX = (int)offsetX; float fractionalX = offsetX - (float)stepX; // physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,xx={1},yy={2},offX={3},stepX={4},fractX={5},offY={6},stepY={7},fractY={8}", // BSScene.DetailLogZero, xx, yy, offsetX, stepX, fractionalX, offsetY, stepY, fractionalY); // get the four corners of the heightmap square the mesh point is in float heightUL = hmap.GetHeight(stepX , stepY ); float heightUR = hmap.GetHeight(stepX + 1, stepY ); float heightLL = hmap.GetHeight(stepX , stepY + 1); float heightLR = hmap.GetHeight(stepX + 1, stepY + 1); // bilinear interplolation float height = heightUL * (1 - fractionalX) * (1 - fractionalY) + heightUR * fractionalX * (1 - fractionalY) + heightLL * (1 - fractionalX) * fractionalY + heightLR * fractionalX * fractionalY; // physicsScene.DetailLog("{0},BSTerrainMesh.ConvertHeightMapToMesh2,heightUL={1},heightUR={2},heightLL={3},heightLR={4},heightMap={5}", // BSScene.DetailLogZero, heightUL, heightUR, heightLL, heightLR, height); minHeight = Math.Min(minHeight, height); vertices[verticesCount + 0] = (float)xx * meshXStep + extentBase.X; vertices[verticesCount + 1] = (float)yy * meshYStep + extentBase.Y; vertices[verticesCount + 2] = height + extentBase.Z; verticesCount += 3; } } // The number of vertices generated verticesCount /= 3; // Loop through all the heightmap squares and create indices for the two triangles for that square for (int yy = 0; yy < meshY; yy++) { for (int xx = 0; xx < meshX; xx++) { int offset = yy * (meshX + 1) + xx; // Each vertices is presumed to be the upper left corner of a box of two triangles indices[indicesCount + 0] = offset; indices[indicesCount + 1] = offset + 1; indices[indicesCount + 2] = offset + meshX + 1; // accounting for the extra column indices[indicesCount + 3] = offset + 1; indices[indicesCount + 4] = offset + meshX + 2; indices[indicesCount + 5] = offset + meshX + 1; indicesCount += 6; } } ret = true; } catch (Exception e) { if (physicsScene != null) physicsScene.Logger.ErrorFormat("{0} Failed conversion of heightmap to mesh. For={1}/{2}, e={3}", LogHeader, physicsScene.RegionName, extentBase, e); } indicesCountO = indicesCount; indicesO = indices; verticesCountO = verticesCount; verticesO = vertices; return ret; } } }
//------------------------------------------------------------------------------ // <copyright file="RecordManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data { using System; using System.Collections.Generic; using System.Diagnostics; internal sealed class RecordManager { private readonly DataTable table; private int lastFreeRecord; private int minimumCapacity = 50; private int recordCapacity = 0; private readonly List<int> freeRecordList = new List<int>(); DataRow[] rows; internal RecordManager(DataTable table) { if (table == null) { throw ExceptionBuilder.ArgumentNull("table"); } this.table = table; } private void GrowRecordCapacity() { if (NewCapacity(recordCapacity) < NormalizedMinimumCapacity(minimumCapacity)) RecordCapacity = NormalizedMinimumCapacity(minimumCapacity); else RecordCapacity = NewCapacity(recordCapacity); // set up internal map : record --> row DataRow[] newRows = table.NewRowArray(recordCapacity); if (rows != null) { Array.Copy(rows, 0, newRows, 0, Math.Min(lastFreeRecord, rows.Length)); } rows = newRows; } internal int LastFreeRecord { get { return lastFreeRecord; } } internal int MinimumCapacity { get { return minimumCapacity; } set { if (minimumCapacity != value) { if (value < 0) { throw ExceptionBuilder.NegativeMinimumCapacity(); } minimumCapacity = value; } } } internal int RecordCapacity { get { return recordCapacity; } set { if (recordCapacity != value) { for (int i = 0; i < table.Columns.Count; i++) { table.Columns[i].SetCapacity(value); } recordCapacity = value; } } } internal static int NewCapacity(int capacity) { return (capacity < 128) ? 128 : (capacity + capacity); } // Normalization: 64, 256, 1024, 2k, 3k, .... private int NormalizedMinimumCapacity(int capacity) { if (capacity < 1024 - 10) { if (capacity < 256 - 10) { if ( capacity < 54 ) return 64; return 256; } return 1024; } return (((capacity + 10) >> 10) + 1) << 10; } internal int NewRecordBase() { int record; if (freeRecordList.Count != 0) { record = freeRecordList[freeRecordList.Count - 1]; freeRecordList.RemoveAt(freeRecordList.Count - 1); } else { if (lastFreeRecord >= recordCapacity) { GrowRecordCapacity(); } record = lastFreeRecord; lastFreeRecord++; } Debug.Assert(record >=0 && record < recordCapacity, "NewRecord: Invalid record"); return record; } internal void FreeRecord(ref int record) { Debug.Assert(-1 <= record && record < recordCapacity, "invalid record"); // Debug.Assert(record < lastFreeRecord, "Attempt to Free() <outofbounds> record"); if (-1 != record) { this[record] = null; int count = table.columnCollection.Count; for(int i = 0; i < count; ++i) { table.columnCollection[i].FreeRecord(record); } // if freeing the last record, recycle it if (lastFreeRecord == record + 1) { lastFreeRecord--; } else if (record < lastFreeRecord) { // Debug.Assert(-1 == freeRecordList.IndexOf(record), "Attempt to double Free() record"); freeRecordList.Add(record); } record = -1; } } internal void Clear(bool clearAll) { if (clearAll) { for(int record = 0; record < recordCapacity; ++record) { rows[record] = null; } int count = table.columnCollection.Count; for(int i = 0; i < count; ++i) { // SQLBU 415729: Serious performance issue when calling Clear() // this improves performance by caching the column instead of obtaining it for each row DataColumn column = table.columnCollection[i]; for(int record = 0; record < recordCapacity; ++record) { column.FreeRecord(record); } } lastFreeRecord = 0; freeRecordList.Clear(); } else { // just clear attached rows freeRecordList.Capacity = freeRecordList.Count + table.Rows.Count; for(int record = 0; record < recordCapacity; ++record) { if (rows[record]!= null && rows[record].rowID != -1) { int tempRecord = record; FreeRecord(ref tempRecord); } } } } internal DataRow this[int record] { get { Debug.Assert(record >= 0 && record < rows.Length, "Invalid record number"); return rows[record]; } set { Debug.Assert(record >= 0 && record < rows.Length, "Invalid record number"); rows[record] = value; } } internal void SetKeyValues(int record, DataKey key, object[] keyValues) { for (int i = 0; i < keyValues.Length; i++) { key.ColumnsReference[i][record] = keyValues[i]; } } // Increases AutoIncrementCurrent internal int ImportRecord(DataTable src, int record) { return CopyRecord(src, record, -1); } // No impact on AutoIncrementCurrent if over written internal int CopyRecord(DataTable src, int record, int copy) { Debug.Assert(src != null, "Can not Merge record without a table"); if (record == -1) { return copy; } int newRecord = -1; try { if (copy == -1) { newRecord = table.NewUninitializedRecord(); } else { newRecord = copy; } int count = table.Columns.Count; for (int i = 0; i < count; ++i) { DataColumn dstColumn = table.Columns[i]; DataColumn srcColumn = src.Columns[dstColumn.ColumnName]; if (null != srcColumn) { object value = srcColumn[record]; ICloneable cloneableObject = value as ICloneable; if (null != cloneableObject) { dstColumn[newRecord] = cloneableObject.Clone(); } else { dstColumn[newRecord] = value; } } else if (-1 == copy) { dstColumn.Init(newRecord); } } } catch (Exception e){ // if (Common.ADP.IsCatchableOrSecurityExceptionType(e)) { if (-1 == copy) { FreeRecord(ref newRecord); } } throw; } return newRecord; } internal void SetRowCache(DataRow[] newRows) { rows = newRows; lastFreeRecord = rows.Length; recordCapacity = lastFreeRecord; } [Conditional("DEBUG")] internal void VerifyRecord(int record) { Debug.Assert((record < lastFreeRecord) && (-1 == freeRecordList.IndexOf(record)), "accesing free record"); Debug.Assert((null == rows[record]) || (record == rows[record].oldRecord) || (record == rows[record].newRecord) || (record == rows[record].tempRecord), "record of a different row"); } [Conditional("DEBUG")] internal void VerifyRecord(int record, DataRow row) { Debug.Assert((record < lastFreeRecord) && (-1 == freeRecordList.IndexOf(record)), "accesing free record"); Debug.Assert((null == rows[record]) || (row == rows[record]), "record of a different row"); } } }
namespace Macabresoft.Macabre2D.UI.Tests; using System; using System.Collections.Generic; using System.IO; using System.Linq; using FluentAssertions; using FluentAssertions.Execution; using Macabresoft.AvaloniaEx; using Macabresoft.Macabre2D.Framework; using Macabresoft.Macabre2D.UI.Common; using NSubstitute; public class ContentContainer { public const string Folder1 = "Folder1"; public const string Folder1A = "Folder1A"; public const string Folder2 = "Folder2"; private const string BinPath = "bin"; private const string PlatformsPath = "Platforms"; private readonly IList<string> _metadataFilePaths = new List<string>(); private readonly IPathService _pathService = new PathService(BinPath, PlatformsPath, PathService.ContentDirectoryName); private readonly IDictionary<string, HashSet<string>> _pathToDirectoryList = new Dictionary<string, HashSet<string>>(); private readonly IDictionary<string, HashSet<string>> _pathToFileList = new Dictionary<string, HashSet<string>>(); public ContentContainer( IEnumerable<ContentMetadata> existingMetadata, IEnumerable<ContentMetadata> metadataToArchive, IEnumerable<string> newContentFiles) { this.ExistingMetadata = existingMetadata.ToArray(); this.MetadataToArchive = metadataToArchive.ToArray(); this.NewContentFiles = newContentFiles.ToArray(); this.FileSystem.DoesDirectoryExist(this._pathService.PlatformsDirectoryPath).Returns(true); this.FileSystem.DoesDirectoryExist(this._pathService.ContentDirectoryPath).Returns(true); this.FileSystem.DoesDirectoryExist(this._pathService.MetadataDirectoryPath).Returns(true); this.FileSystem.DoesDirectoryExist(this._pathService.MetadataArchiveDirectoryPath).Returns(true); var projectFilePath = Path.Combine(this._pathService.ContentDirectoryPath, GameProject.ProjectFileName); this.FileSystem.DoesFileExist(projectFilePath).Returns(true); var project = new GameProject(this.GameSettings, GameProject.DefaultProjectName, Guid.Empty); this.Serializer.Deserialize<GameProject>(projectFilePath).Returns(project); this.SetupExistingMetadata(); this.SetupMetadataToArchive(); this.SetupNewContentFiles(); this.FileSystem.GetFiles(this._pathService.MetadataDirectoryPath, ContentMetadata.MetadataSearchPattern).Returns(this._metadataFilePaths); this.Instance = new ContentService( Substitute.For<IAssemblyService>(), this.AssetManager, Substitute.For<IBuildService>(), Substitute.For<ICommonDialogService>(), this.FileSystem, Substitute.For<ILoggingService>(), this._pathService, this.Serializer, Substitute.For<IEditorSettingsService>(), Substitute.For<IUndoService>(), Substitute.For<IValueControlService>()); } public IAssetManager AssetManager { get; } = Substitute.For<IAssetManager>(); public IReadOnlyCollection<ContentMetadata> ExistingMetadata { get; } public IFileSystemService FileSystem { get; } = Substitute.For<IFileSystemService>(); public IGameSettings GameSettings { get; } = Substitute.For<IGameSettings>(); public IContentService Instance { get; } public IReadOnlyCollection<ContentMetadata> MetadataToArchive { get; } public IReadOnlyCollection<string> NewContentFiles { get; } public ISerializer Serializer { get; } = Substitute.For<ISerializer>(); public void RunRefreshContentTest() { this.Instance.RefreshContent(false); using (new AssertionScope()) { this.AssertExistingMetadata(); this.AssertMetadataToArchive(); this.AssertNewContentFiles(); } } private void AddDirectoryToDirectory(string directoryPath, string newDirectoryName) { var newDirectoryPath = Path.Combine(directoryPath, newDirectoryName); if (this._pathToDirectoryList.TryGetValue(directoryPath, out var directories)) { directories.Add(newDirectoryPath); } else { directories = new HashSet<string> { newDirectoryPath }; this._pathToDirectoryList[directoryPath] = directories; this.FileSystem.GetDirectories(directoryPath).Returns(directories); } this.FileSystem.DoesDirectoryExist(newDirectoryPath).Returns(true); } private void AddFileToDirectory(string directoryPath, string fileName) { var splitDirectoryPath = directoryPath.Split(Path.DirectorySeparatorChar); if (splitDirectoryPath.Length > 1) { for (var i = 1; i < splitDirectoryPath.Length; i++) { this.AddDirectoryToDirectory(Path.Combine(splitDirectoryPath.Take(i).ToArray()), splitDirectoryPath[i]); } } var filePath = Path.Combine(directoryPath, fileName); if (this._pathToFileList.TryGetValue(directoryPath, out var files)) { files.Add(filePath); } else { files = new HashSet<string> { filePath }; this._pathToFileList[directoryPath] = files; this.FileSystem.GetFiles(directoryPath).Returns(files); } this.FileSystem.DoesFileExist(filePath).Returns(true); } private void AssertExistingMetadata() { foreach (var metadata in this.ExistingMetadata) { this.AssetManager.Received().RegisterMetadata(metadata); var contentFile = this.Instance.RootContentDirectory.TryFindNode(metadata.SplitContentPath.ToArray()); contentFile.Should().NotBeNull(); contentFile.NameWithoutExtension.Should().Be(metadata.GetFileNameWithoutExtension()); contentFile.Name.Should().Be(metadata.GetFileName()); contentFile.GetContentPath().Should().Be(metadata.GetContentPath()); contentFile.GetFullPath().Should().Be(Path.Combine(this._pathService.ContentDirectoryPath, $"{metadata.GetContentPath()}{metadata.ContentFileExtension}")); } } private void AssertMetadataToArchive() { foreach (var metadata in this.MetadataToArchive) { var current = Path.Combine(this._pathService.ContentDirectoryPath, ContentMetadata.GetMetadataPath(metadata.ContentId)); var moveTo = Path.Combine(this._pathService.ContentDirectoryPath, ContentMetadata.GetArchivePath(metadata.ContentId)); this.FileSystem.Received().MoveFile(current, moveTo); this.AssetManager.DidNotReceive().RegisterMetadata(metadata); this.Instance.RootContentDirectory.TryFindNode(metadata.SplitContentPath.ToArray(), out var node).Should().BeFalse(); node.Should().BeNull(); } } private void AssertNewContentFiles() { foreach (var file in this.NewContentFiles) { var splitContentPath = file.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries).ToList(); splitContentPath[^1] = Path.GetFileNameWithoutExtension(splitContentPath[^1]); var contentFile = this.Instance.RootContentDirectory.TryFindNode(splitContentPath.ToArray()) as ContentFile; contentFile.Should().NotBeNull(); if (contentFile != null) { this.AssetManager.Received().RegisterMetadata(contentFile.Metadata); this.Serializer.Received().Serialize(contentFile.Metadata, Path.Combine(this._pathService.ContentDirectoryPath, ContentMetadata.GetMetadataPath(contentFile.Metadata.ContentId))); } } } private void RegisterContent(ContentMetadata metadata, bool contentShouldExist) { var splitDirectoryPath = metadata.SplitContentPath.Take(metadata.SplitContentPath.Count - 1).ToList(); splitDirectoryPath.Insert(0, PathService.ContentDirectoryName); var fileName = metadata.GetFileName(); if (contentShouldExist) { var directoryPath = Path.Combine(splitDirectoryPath.ToArray()); this.AddFileToDirectory(directoryPath, fileName); } else { splitDirectoryPath.Add(fileName); this.FileSystem.DoesFileExist(Path.Combine(splitDirectoryPath.ToArray())).Returns(false); } } private void SetupExistingMetadata() { foreach (var metadata in this.ExistingMetadata) { var metadataFilePath = Path.Combine(this._pathService.ContentDirectoryPath, ContentMetadata.GetMetadataPath(metadata.ContentId)); this._metadataFilePaths.Add(metadataFilePath); this.Serializer.Deserialize<ContentMetadata>(metadataFilePath).Returns(metadata); this.RegisterContent(metadata, true); } } private void SetupMetadataToArchive() { foreach (var metadata in this.MetadataToArchive) { var metadataFilePath = Path.Combine(this._pathService.ContentDirectoryPath, ContentMetadata.GetMetadataPath(metadata.ContentId)); this._metadataFilePaths.Add(metadataFilePath); this.FileSystem.DoesFileExist(metadataFilePath).Returns(true); this.Serializer.Deserialize<ContentMetadata>(metadataFilePath).Returns(metadata); this.RegisterContent(metadata, false); } } private void SetupNewContentFiles() { foreach (var file in this.NewContentFiles) { var splitPath = file.Split(Path.DirectorySeparatorChar); var fileName = splitPath.Last(); var splitDirectoryPath = splitPath.Take(splitPath.Length - 1).ToList(); splitDirectoryPath.Insert(0, PathService.ContentDirectoryName); this.AddFileToDirectory(Path.Combine(splitDirectoryPath.ToArray()), fileName); this.FileSystem.DoesFileExist(Path.Combine(this._pathService.ContentDirectoryPath, file)).Returns(true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.Contracts; //using System.Globalization; using System.Runtime.CompilerServices; using System.Security; using System.Runtime.Serialization; namespace System.Collections.Generic { [Serializable] [TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")] public abstract class Comparer<T> : IComparer, IComparer<T> { static readonly Comparer<T> defaultComparer = CreateComparer(); public static Comparer<T> Default { get { Contract.Ensures(Contract.Result<Comparer<T>>() != null); return defaultComparer; } } public static Comparer<T> Create(Comparison<T> comparison) { Contract.Ensures(Contract.Result<Comparer<T>>() != null); if (comparison == null) throw new ArgumentNullException("comparison"); return new ComparisonComparer<T>(comparison); } // // Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen // saves the right instantiations // [System.Security.SecuritySafeCritical] // auto-generated private static Comparer<T> CreateComparer() { object result = null; RuntimeType t = (RuntimeType)typeof(T); // If T implements IComparable<T> return a GenericComparer<T> if (typeof(IComparable<T>).IsAssignableFrom(t)) { result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t); } else if (default(T) == null) { // If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U> if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) { RuntimeType u = (RuntimeType)t.GetGenericArguments()[0]; if (typeof(IComparable<>).MakeGenericType(u).IsAssignableFrom(u)) { result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), u); } } } else if (t.IsEnum) { // Explicitly call Enum.GetUnderlyingType here. Although GetTypeCode // ends up doing this anyway, we end up avoiding an unnecessary P/Invoke // and virtual method call. TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t)); // Depending on the enum type, we need to special case the comparers so that we avoid boxing // Specialize differently for signed/unsigned types so we avoid problems with large numbers switch (underlyingTypeCode) { case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int32EnumComparer<int>), t); break; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt32EnumComparer<uint>), t); break; // 64-bit enums: use UnsafeEnumCastLong case TypeCode.Int64: result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int64EnumComparer<long>), t); break; case TypeCode.UInt64: result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt64EnumComparer<ulong>), t); break; } } return result != null ? (Comparer<T>)result : new ObjectComparer<T>(); // Fallback to ObjectComparer, which uses boxing } public abstract int Compare(T x, T y); int IComparer.Compare(object x, object y) { if (x == null) return y == null ? 0 : -1; if (y == null) return 1; if (x is T && y is T) return Compare((T)x, (T)y); ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison); return 0; } } // Note: although there is a lot of shared code in the following // comparers, we do not incorporate it into a base class for perf // reasons. Adding another base class (even one with no fields) // means another generic instantiation, which can be costly esp. // for value types. [Serializable] internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T> { public override int Compare(T x, T y) { if (x != null) { if (y != null) return x.CompareTo(y); return 1; } if (y != null) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } [Serializable] internal sealed class NullableComparer<T> : Comparer<T?> where T : struct, IComparable<T> { public override int Compare(T? x, T? y) { if (x.HasValue) { if (y.HasValue) return x.value.CompareTo(y.value); return 1; } if (y.HasValue) return -1; return 0; } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } [Serializable] internal sealed class ObjectComparer<T> : Comparer<T> { public override int Compare(T x, T y) { return System.Collections.Comparer.Default.Compare(x, y); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); } [Serializable] internal sealed class ComparisonComparer<T> : Comparer<T> { private readonly Comparison<T> _comparison; public ComparisonComparer(Comparison<T> comparison) { _comparison = comparison; } public override int Compare(T x, T y) { return _comparison(x, y); } } // Enum comparers (specialized to avoid boxing) // NOTE: Each of these needs to implement ISerializable // and have a SerializationInfo/StreamingContext ctor, // since we want to serialize as ObjectComparer for // back-compat reasons (see below). [Serializable] internal sealed class Int32EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public Int32EnumComparer() { Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. private Int32EnumComparer(SerializationInfo info, StreamingContext context) { } public override int Compare(T x, T y) { int ix = JitHelpers.UnsafeEnumCast(x); int iy = JitHelpers.UnsafeEnumCast(y); return ix.CompareTo(iy); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); [SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { // Previously Comparer<T> was not specialized for enums, // and instead fell back to ObjectComparer which uses boxing. // Set the type as ObjectComparer here so code that serializes // Comparer for enums will not break. info.SetType(typeof(ObjectComparer<T>)); } } [Serializable] internal sealed class UInt32EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public UInt32EnumComparer() { Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. private UInt32EnumComparer(SerializationInfo info, StreamingContext context) { } public override int Compare(T x, T y) { uint ix = (uint)JitHelpers.UnsafeEnumCast(x); uint iy = (uint)JitHelpers.UnsafeEnumCast(y); return ix.CompareTo(iy); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); [SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(ObjectComparer<T>)); } } [Serializable] internal sealed class Int64EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public Int64EnumComparer() { Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. private Int64EnumComparer(SerializationInfo info, StreamingContext context) { } public override int Compare(T x, T y) { long lx = JitHelpers.UnsafeEnumCastLong(x); long ly = JitHelpers.UnsafeEnumCastLong(y); return lx.CompareTo(ly); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); [SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(ObjectComparer<T>)); } } [Serializable] internal sealed class UInt64EnumComparer<T> : Comparer<T>, ISerializable where T : struct { public UInt64EnumComparer() { Contract.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!"); } // Used by the serialization engine. private UInt64EnumComparer(SerializationInfo info, StreamingContext context) { } public override int Compare(T x, T y) { ulong lx = (ulong)JitHelpers.UnsafeEnumCastLong(x); ulong ly = (ulong)JitHelpers.UnsafeEnumCastLong(y); return lx.CompareTo(ly); } // Equals method for the comparer itself. public override bool Equals(Object obj) => obj != null && GetType() == obj.GetType(); public override int GetHashCode() => GetType().GetHashCode(); [SecurityCritical] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(ObjectComparer<T>)); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Portable; using Apache.Ignite.Core.Impl.Services; using Apache.Ignite.Core.Portable; using Apache.Ignite.Core.Services; using NUnit.Framework; /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality. /// </summary> public class ServiceProxyTest { /** */ private TestIgniteService _svc; /** */ private readonly PortableMarshaller _marsh = new PortableMarshaller(new PortableConfiguration { TypeConfigurations = new[] { new PortableTypeConfiguration(typeof (TestPortableClass)), new PortableTypeConfiguration(typeof (CustomExceptionPortable)) } }); /** */ protected readonly IPortables Portables; /** */ private readonly PlatformMemoryManager _memory = new PlatformMemoryManager(1024); /** */ protected bool KeepPortable; /** */ protected bool SrvKeepPortable; /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTest"/> class. /// </summary> public ServiceProxyTest() { Portables = new PortablesImpl(_marsh); } /// <summary> /// Tests object class methods proxying. /// </summary> [Test] public void TestObjectClassMethods() { var prx = GetProxy(); prx.IntProp = 12345; Assert.AreEqual("12345", prx.ToString()); Assert.AreEqual("12345", _svc.ToString()); Assert.AreEqual(12345, prx.GetHashCode()); Assert.AreEqual(12345, _svc.GetHashCode()); } /// <summary> /// Tests properties proxying. /// </summary> [Test] [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public void TestProperties() { var prx = GetProxy(); prx.IntProp = 10; Assert.AreEqual(10, prx.IntProp); Assert.AreEqual(10, _svc.IntProp); _svc.IntProp = 15; Assert.AreEqual(15, prx.IntProp); Assert.AreEqual(15, _svc.IntProp); prx.ObjProp = "prop1"; Assert.AreEqual("prop1", prx.ObjProp); Assert.AreEqual("prop1", _svc.ObjProp); prx.ObjProp = null; Assert.IsNull(prx.ObjProp); Assert.IsNull(_svc.ObjProp); prx.ObjProp = new TestClass {Prop = "prop2"}; Assert.AreEqual("prop2", ((TestClass)prx.ObjProp).Prop); Assert.AreEqual("prop2", ((TestClass)_svc.ObjProp).Prop); } /// <summary> /// Tests void methods proxying. /// </summary> [Test] public void TestVoidMethods() { var prx = GetProxy(); prx.VoidMethod(); Assert.AreEqual("VoidMethod", prx.InvokeResult); Assert.AreEqual("VoidMethod", _svc.InvokeResult); prx.VoidMethod(10); Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult); prx.VoidMethod(10, "string"); Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult); prx.VoidMethod(10, "string", "arg"); Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult); prx.VoidMethod(10, "string", "arg", "arg1", 2, 3, "arg4"); Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult); } /// <summary> /// Tests object methods proxying. /// </summary> [Test] public void TestObjectMethods() { var prx = GetProxy(); Assert.AreEqual("ObjectMethod", prx.ObjectMethod()); Assert.AreEqual("ObjectMethod987", prx.ObjectMethod(987)); Assert.AreEqual("ObjectMethod987str123", prx.ObjectMethod(987, "str123")); Assert.AreEqual("ObjectMethod987str123TestClass", prx.ObjectMethod(987, "str123", new TestClass())); Assert.AreEqual("ObjectMethod987str123TestClass34arg5arg6", prx.ObjectMethod(987, "str123", new TestClass(), 3, 4, "arg5", "arg6")); } /// <summary> /// Tests methods that exist in proxy interface, but do not exist in the actual service. /// </summary> [Test] public void TestMissingMethods() { var prx = GetProxy(); var ex = Assert.Throws<InvalidOperationException>(() => prx.MissingMethod()); Assert.AreEqual("Failed to invoke proxy: there is no method 'MissingMethod'" + " in type 'Apache.Ignite.Core.Tests.Services.ServiceProxyTest+TestIgniteService'", ex.Message); } /// <summary> /// Tests ambiguous methods handling (multiple methods with the same signature). /// </summary> [Test] public void TestAmbiguousMethods() { var prx = GetProxy(); var ex = Assert.Throws<InvalidOperationException>(() => prx.AmbiguousMethod(1)); Assert.AreEqual("Failed to invoke proxy: there are 2 methods 'AmbiguousMethod' in type " + "'Apache.Ignite.Core.Tests.Services.ServiceProxyTest+TestIgniteService' with (Int32) arguments, " + "can't resolve ambiguity.", ex.Message); } [Test] public void TestException() { var prx = GetProxy(); var err = Assert.Throws<ServiceInvocationException>(prx.ExceptionMethod); Assert.AreEqual("Expected exception", err.InnerException.Message); var ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionMethod()); Assert.IsTrue(ex.ToString().Contains("+CustomException")); } [Test] public void TestPortableMarshallingException() { var prx = GetProxy(); var ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionPortableMethod(false, false)); if (KeepPortable) { Assert.AreEqual("Proxy method invocation failed with a portable error. " + "Examine PortableCause for details.", ex.Message); Assert.IsNotNull(ex.PortableCause); Assert.IsNull(ex.InnerException); } else { Assert.AreEqual("Proxy method invocation failed with an exception. " + "Examine InnerException for details.", ex.Message); Assert.IsNull(ex.PortableCause); Assert.IsNotNull(ex.InnerException); } ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionPortableMethod(true, false)); Assert.IsTrue(ex.ToString().Contains( "Call completed with error, but error serialization failed [errType=CustomExceptionPortable, " + "serializationErrMsg=Expected exception in CustomExceptionPortable.WritePortable]")); ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionPortableMethod(true, true)); Assert.IsTrue(ex.ToString().Contains( "Call completed with error, but error serialization failed [errType=CustomExceptionPortable, " + "serializationErrMsg=Expected exception in CustomExceptionPortable.WritePortable]")); } /// <summary> /// Creates the proxy. /// </summary> protected ITestIgniteServiceProxyInterface GetProxy() { return GetProxy<ITestIgniteServiceProxyInterface>(); } /// <summary> /// Creates the proxy. /// </summary> protected T GetProxy<T>() { _svc = new TestIgniteService(Portables); var prx = new ServiceProxy<T>(InvokeProxyMethod).GetTransparentProxy(); Assert.IsFalse(ReferenceEquals(_svc, prx)); return prx; } /// <summary> /// Invokes the proxy. /// </summary> /// <param name="method">Method.</param> /// <param name="args">Arguments.</param> /// <returns> /// Invocation result. /// </returns> private object InvokeProxyMethod(MethodBase method, object[] args) { using (var inStream = new PlatformMemoryStream(_memory.Allocate())) using (var outStream = new PlatformMemoryStream(_memory.Allocate())) { // 1) Write to a stream inStream.WriteBool(SrvKeepPortable); // WriteProxyMethod does not do this, but Java does ServiceProxySerializer.WriteProxyMethod(_marsh.StartMarshal(inStream), method, args); inStream.SynchronizeOutput(); inStream.Seek(0, SeekOrigin.Begin); // 2) call InvokeServiceMethod string mthdName; object[] mthdArgs; ServiceProxySerializer.ReadProxyMethod(inStream, _marsh, out mthdName, out mthdArgs); var result = ServiceProxyInvoker.InvokeServiceMethod(_svc, mthdName, mthdArgs); ServiceProxySerializer.WriteInvocationResult(outStream, _marsh, result.Key, result.Value); _marsh.StartMarshal(outStream).WriteString("unused"); // fake Java exception details outStream.SynchronizeOutput(); outStream.Seek(0, SeekOrigin.Begin); return ServiceProxySerializer.ReadInvocationResult(outStream, _marsh, KeepPortable); } } /// <summary> /// Test service interface. /// </summary> protected interface ITestIgniteServiceProperties { /** */ int IntProp { get; set; } /** */ object ObjProp { get; set; } /** */ string InvokeResult { get; } } /// <summary> /// Test service interface to check ambiguity handling. /// </summary> protected interface ITestIgniteServiceAmbiguity { /** */ int AmbiguousMethod(int arg); } /// <summary> /// Test service interface. /// </summary> protected interface ITestIgniteService : ITestIgniteServiceProperties { /** */ void VoidMethod(); /** */ void VoidMethod(int arg); /** */ void VoidMethod(int arg, string arg1, object arg2 = null); /** */ void VoidMethod(int arg, string arg1, object arg2 = null, params object[] args); /** */ object ObjectMethod(); /** */ object ObjectMethod(int arg); /** */ object ObjectMethod(int arg, string arg1, object arg2 = null); /** */ object ObjectMethod(int arg, string arg1, object arg2 = null, params object[] args); /** */ void ExceptionMethod(); /** */ void CustomExceptionMethod(); /** */ void CustomExceptionPortableMethod(bool throwOnWrite, bool throwOnRead); /** */ TestPortableClass PortableArgMethod(int arg1, IPortableObject arg2); /** */ IPortableObject PortableResultMethod(int arg1, TestPortableClass arg2); /** */ IPortableObject PortableArgAndResultMethod(int arg1, IPortableObject arg2); /** */ int AmbiguousMethod(int arg); } /// <summary> /// Test service interface. Does not derive from actual interface, but has all the same method signatures. /// </summary> protected interface ITestIgniteServiceProxyInterface { /** */ int IntProp { get; set; } /** */ object ObjProp { get; set; } /** */ string InvokeResult { get; } /** */ void VoidMethod(); /** */ void VoidMethod(int arg); /** */ void VoidMethod(int arg, string arg1, object arg2 = null); /** */ void VoidMethod(int arg, string arg1, object arg2 = null, params object[] args); /** */ object ObjectMethod(); /** */ object ObjectMethod(int arg); /** */ object ObjectMethod(int arg, string arg1, object arg2 = null); /** */ object ObjectMethod(int arg, string arg1, object arg2 = null, params object[] args); /** */ void ExceptionMethod(); /** */ void CustomExceptionMethod(); /** */ void CustomExceptionPortableMethod(bool throwOnWrite, bool throwOnRead); /** */ TestPortableClass PortableArgMethod(int arg1, IPortableObject arg2); /** */ IPortableObject PortableResultMethod(int arg1, TestPortableClass arg2); /** */ IPortableObject PortableArgAndResultMethod(int arg1, IPortableObject arg2); /** */ void MissingMethod(); /** */ int AmbiguousMethod(int arg); } /// <summary> /// Test service. /// </summary> [Serializable] private class TestIgniteService : ITestIgniteService, ITestIgniteServiceAmbiguity { /** */ private readonly IPortables _portables; /// <summary> /// Initializes a new instance of the <see cref="TestIgniteService"/> class. /// </summary> /// <param name="portables">The portables.</param> public TestIgniteService(IPortables portables) { _portables = portables; } /** <inheritdoc /> */ public int IntProp { get; set; } /** <inheritdoc /> */ public object ObjProp { get; set; } /** <inheritdoc /> */ public string InvokeResult { get; private set; } /** <inheritdoc /> */ public void VoidMethod() { InvokeResult = "VoidMethod"; } /** <inheritdoc /> */ public void VoidMethod(int arg) { InvokeResult = "VoidMethod" + arg; } /** <inheritdoc /> */ public void VoidMethod(int arg, string arg1, object arg2 = null) { InvokeResult = "VoidMethod" + arg + arg1 + arg2; } /** <inheritdoc /> */ public void VoidMethod(int arg, string arg1, object arg2 = null, params object[] args) { InvokeResult = "VoidMethod" + arg + arg1 + arg2 + string.Concat(args.Select(x => x.ToString())); } /** <inheritdoc /> */ public object ObjectMethod() { return "ObjectMethod"; } /** <inheritdoc /> */ public object ObjectMethod(int arg) { return "ObjectMethod" + arg; } /** <inheritdoc /> */ public object ObjectMethod(int arg, string arg1, object arg2 = null) { return "ObjectMethod" + arg + arg1 + arg2; } /** <inheritdoc /> */ public object ObjectMethod(int arg, string arg1, object arg2 = null, params object[] args) { return "ObjectMethod" + arg + arg1 + arg2 + string.Concat(args.Select(x => x.ToString())); } /** <inheritdoc /> */ public void ExceptionMethod() { throw new ArithmeticException("Expected exception"); } /** <inheritdoc /> */ public void CustomExceptionMethod() { throw new CustomException(); } /** <inheritdoc /> */ public void CustomExceptionPortableMethod(bool throwOnWrite, bool throwOnRead) { throw new CustomExceptionPortable {ThrowOnRead = throwOnRead, ThrowOnWrite = throwOnWrite}; } /** <inheritdoc /> */ public TestPortableClass PortableArgMethod(int arg1, IPortableObject arg2) { return arg2.Deserialize<TestPortableClass>(); } /** <inheritdoc /> */ public IPortableObject PortableResultMethod(int arg1, TestPortableClass arg2) { return _portables.ToPortable<IPortableObject>(arg2); } /** <inheritdoc /> */ public IPortableObject PortableArgAndResultMethod(int arg1, IPortableObject arg2) { return _portables.ToPortable<IPortableObject>(arg2.Deserialize<TestPortableClass>()); } /** <inheritdoc /> */ public override string ToString() { return IntProp.ToString(); } /** <inheritdoc /> */ public override int GetHashCode() { return IntProp.GetHashCode(); } /** <inheritdoc /> */ int ITestIgniteService.AmbiguousMethod(int arg) { return arg; } /** <inheritdoc /> */ int ITestIgniteServiceAmbiguity.AmbiguousMethod(int arg) { return -arg; } } /// <summary> /// Test serializable class. /// </summary> [Serializable] private class TestClass { /** */ public string Prop { get; set; } /** <inheritdoc /> */ public override string ToString() { return "TestClass" + Prop; } } /// <summary> /// Custom non-serializable exception. /// </summary> private class CustomException : Exception { } /// <summary> /// Custom non-serializable exception. /// </summary> private class CustomExceptionPortable : Exception, IPortableMarshalAware { /** */ public bool ThrowOnWrite { get; set; } /** */ public bool ThrowOnRead { get; set; } /** <inheritdoc /> */ public void WritePortable(IPortableWriter writer) { writer.WriteBoolean("ThrowOnRead", ThrowOnRead); if (ThrowOnWrite) throw new Exception("Expected exception in CustomExceptionPortable.WritePortable"); } /** <inheritdoc /> */ public void ReadPortable(IPortableReader reader) { ThrowOnRead = reader.ReadBoolean("ThrowOnRead"); if (ThrowOnRead) throw new Exception("Expected exception in CustomExceptionPortable.ReadPortable"); } } /// <summary> /// Portable object for method argument/result. /// </summary> protected class TestPortableClass : IPortableMarshalAware { /** */ public string Prop { get; set; } /** */ public bool ThrowOnWrite { get; set; } /** */ public bool ThrowOnRead { get; set; } /** <inheritdoc /> */ public void WritePortable(IPortableWriter writer) { writer.WriteString("Prop", Prop); writer.WriteBoolean("ThrowOnRead", ThrowOnRead); if (ThrowOnWrite) throw new Exception("Expected exception in TestPortableClass.WritePortable"); } /** <inheritdoc /> */ public void ReadPortable(IPortableReader reader) { Prop = reader.ReadString("Prop"); ThrowOnRead = reader.ReadBoolean("ThrowOnRead"); if (ThrowOnRead) throw new Exception("Expected exception in TestPortableClass.ReadPortable"); } } } /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality with keepPortable mode enabled on client. /// </summary> public class ServiceProxyTestKeepPortableClient : ServiceProxyTest { /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTestKeepPortableClient"/> class. /// </summary> public ServiceProxyTestKeepPortableClient() { KeepPortable = true; } [Test] public void TestPortableMethods() { var prx = GetProxy(); var obj = new TestPortableClass { Prop = "PropValue" }; var result = prx.PortableResultMethod(1, obj); Assert.AreEqual(obj.Prop, result.Deserialize<TestPortableClass>().Prop); } } /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality with keepPortable mode enabled on server. /// </summary> public class ServiceProxyTestKeepPortableServer : ServiceProxyTest { /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTestKeepPortableServer"/> class. /// </summary> public ServiceProxyTestKeepPortableServer() { SrvKeepPortable = true; } [Test] public void TestPortableMethods() { var prx = GetProxy(); var obj = new TestPortableClass { Prop = "PropValue" }; var portObj = Portables.ToPortable<IPortableObject>(obj); var result = prx.PortableArgMethod(1, portObj); Assert.AreEqual(obj.Prop, result.Prop); } } /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality with keepPortable mode enabled on client and on server. /// </summary> public class ServiceProxyTestKeepPortableClientServer : ServiceProxyTest { /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTestKeepPortableClientServer"/> class. /// </summary> public ServiceProxyTestKeepPortableClientServer() { KeepPortable = true; SrvKeepPortable = true; } [Test] public void TestPortableMethods() { var prx = GetProxy(); var obj = new TestPortableClass { Prop = "PropValue" }; var portObj = Portables.ToPortable<IPortableObject>(obj); var result = prx.PortableArgAndResultMethod(1, portObj); Assert.AreEqual(obj.Prop, result.Deserialize<TestPortableClass>().Prop); } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_5_4_7 : EcmaTest { [Fact] [Trait("Category", "15.5.4.7")] public void TheStringPrototypeIndexofLengthPropertyHasTheAttributeReadonly() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A10.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void TheLengthPropertyOfTheIndexofMethodIs1() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A11.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T1.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition2() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T10.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition3() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T11.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition4() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T12.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition5() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T2.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition6() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T4.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition7() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T5.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition8() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T6.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition9() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T7.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition10() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T8.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofSearchstringPosition11() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A1_T9.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenLengthOfSearchstringLessThanLengthOfTostringThis1Returns() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A2_T1.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenLengthOfSearchstringLessThanLengthOfTostringThis1Returns2() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A2_T2.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenLengthOfSearchstringLessThanLengthOfTostringThis1Returns3() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A2_T3.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenLengthOfSearchstringLessThanLengthOfTostringThis1Returns4() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A2_T4.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void SinceWeDealWithMaxTointegerPos0IfTointegerPosLessThan0IndexofSearchstring0Returns() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A3_T1.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void SinceWeDealWithMaxTointegerPos0IfTointegerPosLessThan0IndexofSearchstring0Returns2() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A3_T2.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void SinceWeDealWithMaxTointegerPos0IfTointegerPosLessThan0IndexofSearchstring0Returns3() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A3_T3.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenStringPrototypeIndexofSearchstringPositionIsCalledFirstCallTostringGivingItTheThisValueAsItsArgumentThenCallTostringSearchstringAndCallTonumberPosition() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A4_T1.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenStringPrototypeIndexofSearchstringPositionIsCalledFirstCallTostringGivingItTheThisValueAsItsArgumentThenCallTostringSearchstringAndCallTonumberPosition2() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A4_T2.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenStringPrototypeIndexofSearchstringPositionIsCalledFirstCallTostringGivingItTheThisValueAsItsArgumentThenCallTostringSearchstringAndCallTonumberPosition3() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A4_T3.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenStringPrototypeIndexofSearchstringPositionIsCalledFirstCallTostringGivingItTheThisValueAsItsArgumentThenCallTostringSearchstringAndCallTonumberPosition4() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A4_T4.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void WhenStringPrototypeIndexofSearchstringPositionIsCalledFirstCallTostringGivingItTheThisValueAsItsArgumentThenCallTostringSearchstringAndCallTonumberPosition5() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A4_T5.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofWorksProperly() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A5_T1.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofWorksProperly2() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A5_T2.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofWorksProperly3() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A5_T3.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofWorksProperly4() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A5_T4.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofWorksProperly5() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A5_T5.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofWorksProperly6() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A5_T6.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofHasNotPrototypeProperty() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A6.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void StringPrototypeIndexofCanTBeUsedAsConstructor() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A7.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void TheStringPrototypeIndexofLengthPropertyHasTheAttributeDontenum() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A8.js", false); } [Fact] [Trait("Category", "15.5.4.7")] public void TheStringPrototypeIndexofLengthPropertyHasTheAttributeDontdelete() { RunTest(@"TestCases/ch15/15.5/15.5.4/15.5.4.7/S15.5.4.7_A9.js", false); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace ApplicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// RouteFiltersOperations operations. /// </summary> public partial interface IRouteFiltersOperations { /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='expand'> /// Expands referenced express route bgp peering resources. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> GetWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> UpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified route filter. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the create or update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, RouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates a route filter in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeFilterName'> /// The name of the route filter. /// </param> /// <param name='routeFilterParameters'> /// Parameters supplied to the update route filter operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RouteFilter>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string routeFilterName, PatchRouteFilter routeFilterParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route filters in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RouteFilter>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Security; namespace Alphaleonis.Win32.Filesystem { /// <summary>Provides access to information on a local or remote drive.</summary> /// <remarks> /// This class models a drive and provides methods and properties to query for drive information. /// Use DriveInfo to determine what drives are available, and what type of drives they are. /// You can also query to determine the capacity and available free space on the drive. /// </remarks> [Serializable] [SecurityCritical] public sealed class DriveInfo { #region Private Fields [NonSerialized] private readonly VolumeInfo _volumeInfo; [NonSerialized] private readonly DiskSpaceInfo _dsi; [NonSerialized] private bool _initDsie; [NonSerialized] private DriveType? _driveType; [NonSerialized] private string _dosDeviceName; [NonSerialized] private DirectoryInfo _rootDirectory; private readonly string _name; #endregion #region Constructors /// <summary>Provides access to information on the specified drive.</summary> /// <exception cref="ArgumentNullException"/> /// <exception cref="ArgumentException"/> /// <param name="driveName"> /// A valid drive path or drive letter. /// <para>This can be either uppercase or lowercase,</para> /// <para>'a' to 'z' or a network share in the format: \\server\share</para> /// </param> [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Utils.IsNullOrWhiteSpace validates arguments.")] [SecurityCritical] public DriveInfo(string driveName) { if (Utils.IsNullOrWhiteSpace(driveName)) throw new ArgumentNullException("driveName"); if (driveName.Length == 1) _name += Path.VolumeSeparatorChar; else _name = Path.GetPathRoot(driveName, false); if (Utils.IsNullOrWhiteSpace(_name)) throw new ArgumentException("Argument must be a drive letter (\"C\"), RootDir (\"C:\\\") or UNC path (\"\\\\server\\share\")"); // If an exception is thrown, the original drivePath is used. _name = Path.AddTrailingDirectorySeparator(_name, false); // Initiate VolumeInfo() lazyload instance. _volumeInfo = new VolumeInfo(_name, false, true); // Initiate DiskSpaceInfo() lazyload instance. _dsi = new DiskSpaceInfo(_name, null, false, true); } #endregion // Constructors #region Properties /// <summary>Indicates the amount of available free space on a drive.</summary> /// <returns>The amount of free space available on the drive, in bytes.</returns> /// <remarks>This property indicates the amount of free space available on the drive. Note that this number may be different from the <see cref="TotalFreeSpace"/> number because this property takes into account disk quotas.</remarks> public long AvailableFreeSpace { get { GetDeviceInfo(3, 0); return _dsi == null ? 0 : _dsi.FreeBytesAvailable; } } /// <summary>Gets the name of the file system, such as NTFS or FAT32.</summary> /// <remarks>Use DriveFormat to determine what formatting a drive uses.</remarks> public string DriveFormat { get { return (string)GetDeviceInfo(0, 1); } } /// <summary>Gets the drive type.</summary> /// <returns>One of the <see cref="System.IO.DriveType"/> values.</returns> /// <remarks> /// The DriveType property indicates whether a drive is any of: CDRom, Fixed, Unknown, Network, NoRootDirectory, /// Ram, Removable, or Unknown. Values are listed in the <see cref="System.IO.DriveType"/> enumeration. /// </remarks> public DriveType DriveType { get { return (DriveType)GetDeviceInfo(2, 0); } } /// <summary>Gets a value indicating whether a drive is ready.</summary> /// <returns><see langword="true"/> if the drive is ready; otherwise, <see langword="false"/>.</returns> /// <remarks> /// IsReady indicates whether a drive is ready. For example, it indicates whether a CD is in a CD drive or whether /// a removable storage device is ready for read/write operations. If you do not test whether a drive is ready, and /// it is not ready, querying the drive using DriveInfo will raise an IOException. /// /// Do not rely on IsReady() to avoid catching exceptions from other members such as TotalSize, TotalFreeSpace, and DriveFormat. /// Between the time that your code checks IsReady and then accesses one of the other properties /// (even if the access occurs immediately after the check), a drive may have been disconnected or a disk may have been removed. /// </remarks> public bool IsReady { get { return File.ExistsCore(true, null, Name, PathFormat.LongFullPath); } } /// <summary>Gets the name of the drive.</summary> /// <returns>The name of the drive.</returns> /// <remarks>This property is the name assigned to the drive, such as C:\ or E:\</remarks> public string Name { get { return _name; } } /// <summary>Gets the root directory of a drive.</summary> /// <returns>A DirectoryInfo object that contains the root directory of the drive.</returns> public DirectoryInfo RootDirectory { get { return (DirectoryInfo)GetDeviceInfo(2, 1); } } /// <summary>Gets the total amount of free space available on a drive.</summary> /// <returns>The total free space available on a drive, in bytes.</returns> /// <remarks>This property indicates the total amount of free space available on the drive, not just what is available to the current user.</remarks> public long TotalFreeSpace { get { GetDeviceInfo(3, 0); return _dsi == null ? 0 : _dsi.TotalNumberOfFreeBytes; } } /// <summary>Gets the total size of storage space on a drive.</summary> /// <returns>The total size of the drive, in bytes.</returns> /// <remarks>This property indicates the total size of the drive in bytes, not just what is available to the current user.</remarks> public long TotalSize { get { GetDeviceInfo(3, 0); return _dsi == null ? 0 : _dsi.TotalNumberOfBytes; } } /// <summary>Gets or sets the volume label of a drive.</summary> /// <returns>The volume label.</returns> /// <remarks> /// The label length is determined by the operating system. For example, NTFS allows a volume label /// to be up to 32 characters long. Note that <see langword="null"/> is a valid VolumeLabel. /// </remarks> public string VolumeLabel { get { return (string)GetDeviceInfo(0, 2); } set { Volume.SetVolumeLabel(Name, value); } } /// <summary>[AlphaFS] Returns the <see ref="Alphaleonis.Win32.Filesystem.DiskSpaceInfo"/> instance.</summary> public DiskSpaceInfo DiskSpaceInfo { get { GetDeviceInfo(3, 0); return _dsi; } } /// <summary>[AlphaFS] The MS-DOS device name.</summary> public string DosDeviceName { get { return (string)GetDeviceInfo(1, 0); } } /// <summary>[AlphaFS] Indicates if this drive is a SUBST.EXE / DefineDosDevice drive mapping.</summary> public bool IsDosDeviceSubstitute { get { return !Utils.IsNullOrWhiteSpace(DosDeviceName) && DosDeviceName.StartsWith(Path.SubstitutePrefix, StringComparison.OrdinalIgnoreCase); } } /// <summary>[AlphaFS] Indicates if this drive is a UNC path.</summary> /// <remarks>Only retrieve this information if we're dealing with a real network share mapping: http://alphafs.codeplex.com/discussions/316583</remarks> public bool IsUnc { get { return !IsDosDeviceSubstitute && DriveType == DriveType.Network; } } /// <summary>[AlphaFS] Determines whether the specified volume name is a defined volume on the current computer.</summary> public bool IsVolume { get { return GetDeviceInfo(0, 0) != null; } } /// <summary>[AlphaFS] Contains information about a file-system volume.</summary> /// <returns>A VolumeInfo object that contains file-system volume information of the drive.</returns> public VolumeInfo VolumeInfo { get { return (VolumeInfo)GetDeviceInfo(0, 0); } } #endregion // Properties #region Methods /// <summary>Retrieves the drive names of all logical drives on a computer.</summary> /// <returns>An array of type <see cref="Alphaleonis.Win32.Filesystem.DriveInfo"/> that represents the logical drives on a computer.</returns> [SecurityCritical] public static DriveInfo[] GetDrives() { return Directory.EnumerateLogicalDrivesCore(false, false).ToArray(); } /// <summary>Returns a drive name as a string.</summary> /// <returns>The name of the drive.</returns> /// <remarks>This method returns the Name property.</remarks> public override string ToString() { return _name; } /// <summary>[AlphaFS] Enumerates the drive names of all logical drives on a computer.</summary> /// <param name="fromEnvironment">Retrieve logical drives as known by the Environment.</param> /// <param name="isReady">Retrieve only when accessible (IsReady) logical drives.</param> /// <returns> /// An IEnumerable of type <see cref="Alphaleonis.Win32.Filesystem.DriveInfo"/> that represents /// the logical drives on a computer. /// </returns> [SecurityCritical] public static IEnumerable<DriveInfo> EnumerateDrives(bool fromEnvironment, bool isReady) { return Directory.EnumerateLogicalDrivesCore(fromEnvironment, isReady); } /// <summary>[AlphaFS] Gets the first available drive letter on the local system.</summary> /// <returns>A drive letter as <see cref="char"/>. When no drive letters are available, an exception is thrown.</returns> /// <remarks>The letters "A" and "B" are reserved for floppy drives and will never be returned by this function.</remarks> public static char GetFreeDriveLetter() { return GetFreeDriveLetter(false); } /// <summary>Gets an available drive letter on the local system.</summary> /// <param name="getLastAvailable">When <see langword="true"/> get the last available drive letter. When <see langword="false"/> gets the first available drive letter.</param> /// <returns>A drive letter as <see cref="char"/>. When no drive letters are available, an exception is thrown.</returns> /// <remarks>The letters "A" and "B" are reserved for floppy drives and will never be returned by this function.</remarks> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] public static char GetFreeDriveLetter(bool getLastAvailable) { IEnumerable<char> freeDriveLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ".Except(Directory.EnumerateLogicalDrivesCore(false, false).Select(d => d.Name[0])); try { return getLastAvailable ? freeDriveLetters.Last() : freeDriveLetters.First(); } catch { throw new Exception("There are no drive letters available."); } } #endregion // Methods #region Private Methods /// <summary>Retrieves information about the file system and volume associated with the specified root file or directorystream.</summary> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] private object GetDeviceInfo(int type, int mode) { try { switch (type) { #region Volume // VolumeInfo properties. case 0: if (Utils.IsNullOrWhiteSpace(_volumeInfo.FullPath)) _volumeInfo.Refresh(); switch (mode) { case 0: // IsVolume, VolumeInfo return _volumeInfo; case 1: // DriveFormat return _volumeInfo == null ? DriveType.Unknown.ToString() : _volumeInfo.FileSystemName ?? DriveType.Unknown.ToString(); case 2: // VolumeLabel return _volumeInfo == null ? string.Empty : _volumeInfo.Name ?? string.Empty; } break; // Volume related. case 1: switch (mode) { case 0: // DosDeviceName // Do not use ?? expression here. if (_dosDeviceName == null) _dosDeviceName = Volume.QueryDosDevice(Name).FirstOrDefault(); return _dosDeviceName; } break; #endregion // Volume #region Drive // Drive related. case 2: switch (mode) { case 0: // DriveType // Do not use ?? expression here. if (_driveType == null) _driveType = Volume.GetDriveType(Name); return _driveType; case 1: // RootDirectory // Do not use ?? expression here. if (_rootDirectory == null) _rootDirectory = new DirectoryInfo(null, Name, PathFormat.RelativePath); return _rootDirectory; } break; // DiskSpaceInfo related. case 3: switch (mode) { case 0: // AvailableFreeSpace, TotalFreeSpace, TotalSize, DiskSpaceInfo if (!_initDsie) { _dsi.Refresh(); _initDsie = true; } break; } break; #endregion // Drive } } catch { } return type == 0 && mode > 0 ? string.Empty : null; } #endregion // Private } }
// **************************************************************** // Copyright 2008, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.IO; using System.Threading; using System.Diagnostics; using System.Collections; using System.Collections.Specialized; using System.Runtime.Remoting; using System.Runtime.Remoting.Services; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using NUnit.Core; namespace NUnit.Util { /// <summary> /// Enumeration used to report AgentStatus /// </summary> public enum AgentStatus { Unknown, Starting, Ready, Busy, Stopping } /// <summary> /// The TestAgency class provides RemoteTestAgents /// on request and tracks their status. Agents /// are wrapped in an instance of the TestAgent /// class. Multiple agent types are supported /// but only one, ProcessAgent is implemented /// at this time. /// </summary> public class TestAgency : ServerBase, IAgency, IService { static Logger log = InternalTrace.GetLogger(typeof(TestAgency)); #region Private Fields private AgentDataBase agentData = new AgentDataBase(); #endregion #region Constructors public TestAgency() : this( "TestAgency", 0 ) { } public TestAgency( string uri, int port ) : base( uri, port ) { } #endregion #region ServerBase Overrides public override void Stop() { foreach( AgentRecord r in agentData ) { if ( !r.Process.HasExited ) { if ( r.Agent != null ) { r.Agent.Stop(); r.Process.WaitForExit(10000); } if ( !r.Process.HasExited ) r.Process.Kill(); } } agentData.Clear(); base.Stop (); } #endregion #region Public Methods - Called by Agents public void Register( TestAgent agent ) { AgentRecord r = agentData[agent.Id]; if ( r == null ) throw new ArgumentException( string.Format("Agent {0} is not in the agency database", agent.Id), "agentId"); r.Agent = agent; } public void ReportStatus( Guid agentId, AgentStatus status ) { AgentRecord r = agentData[agentId]; if ( r == null ) throw new ArgumentException( string.Format("Agent {0} is not in the agency database", agentId), "agentId" ); r.Status = status; } #endregion #region Public Methods - Called by Clients public TestAgent GetAgent() { return GetAgent( RuntimeFramework.CurrentFramework, Timeout.Infinite ); } public TestAgent GetAgent(int waitTime) { return GetAgent(RuntimeFramework.CurrentFramework, waitTime); } public TestAgent GetAgent(RuntimeFramework framework, int waitTime) { return GetAgent(framework, waitTime, false); } public TestAgent GetAgent(RuntimeFramework framework, int waitTime, bool enableDebug) { log.Info("Getting agent for use under {0}", framework); if (!framework.IsAvailable) throw new ArgumentException( string.Format("The {0} framework is not available", framework), "framework"); // TODO: Decide if we should reuse agents //AgentRecord r = FindAvailableRemoteAgent(type); //if ( r == null ) // r = CreateRemoteAgent(type, framework, waitTime); return CreateRemoteAgent(framework, waitTime, enableDebug); } public void ReleaseAgent( TestAgent agent ) { AgentRecord r = agentData[agent.Id]; if ( r == null ) log.Error( string.Format( "Unable to release agent {0} - not in database", agent.Id ) ); else { r.Status = AgentStatus.Ready; log.Debug( "Releasing agent " + agent.Id.ToString() ); } } //public void DestroyAgent( ITestAgent agent ) //{ // AgentRecord r = agentData[agent.Id]; // if ( r != null ) // { // if( !r.Process.HasExited ) // r.Agent.Stop(); // agentData[r.Id] = null; // } //} #endregion #region Helper Methods private Guid LaunchAgentProcess(RuntimeFramework targetRuntime, bool enableDebug) { string agentExePath = NUnitConfiguration.GetTestAgentExePath(targetRuntime.ClrVersion); if (agentExePath == null) throw new ArgumentException( string.Format("NUnit components for version {0} of the CLR are not installed", targetRuntime.ClrVersion.ToString()), "targetRuntime"); log.Debug("Using nunit-agent at " + agentExePath); Process p = new Process(); p.StartInfo.UseShellExecute = false; Guid agentId = Guid.NewGuid(); string arglist = agentId.ToString() + " " + ServerUrl; if (enableDebug) arglist += " --pause"; switch( targetRuntime.Runtime ) { case RuntimeType.Mono: p.StartInfo.FileName = NUnitConfiguration.MonoExePath; if (enableDebug) p.StartInfo.Arguments = string.Format("--debug \"{0}\" {1}", agentExePath, arglist); else p.StartInfo.Arguments = string.Format("\"{0}\" {1}", agentExePath, arglist); break; case RuntimeType.Net: p.StartInfo.FileName = agentExePath; if (targetRuntime.ClrVersion.Build < 0) targetRuntime = RuntimeFramework.GetBestAvailableFramework(targetRuntime); string envVar = "v" + targetRuntime.ClrVersion.ToString(3); p.StartInfo.EnvironmentVariables["COMPLUS_Version"] = envVar; p.StartInfo.Arguments = arglist; break; default: p.StartInfo.FileName = agentExePath; p.StartInfo.Arguments = arglist; break; } //p.Exited += new EventHandler(OnProcessExit); p.Start(); log.Info("Launched Agent process {0} - see nunit-agent_{0}.log", p.Id); log.Info("Command line: \"{0}\" {1}", p.StartInfo.FileName, p.StartInfo.Arguments); agentData.Add( new AgentRecord( agentId, p, null, AgentStatus.Starting ) ); return agentId; } //private void OnProcessExit(object sender, EventArgs e) //{ // Process p = sender as Process; // if (p != null) // agentData.Remove(p.Id); //} private AgentRecord FindAvailableAgent() { foreach( AgentRecord r in agentData ) if ( r.Status == AgentStatus.Ready) { log.Debug( "Reusing agent {0}", r.Id ); r.Status = AgentStatus.Busy; return r; } return null; } private TestAgent CreateRemoteAgent(RuntimeFramework framework, int waitTime, bool enableDebug) { Guid agentId = LaunchAgentProcess(framework, enableDebug); log.Debug( "Waiting for agent {0} to register", agentId.ToString("B") ); int pollTime = 200; bool infinite = waitTime == Timeout.Infinite; while( infinite || waitTime > 0 ) { Thread.Sleep( pollTime ); if ( !infinite ) waitTime -= pollTime; TestAgent agent = agentData[agentId].Agent; if ( agent != null ) { log.Debug( "Returning new agent {0}", agentId.ToString("B") ); return agent; } } return null; } #endregion #region IService Members public void UnloadService() { this.Stop(); } public void InitializeService() { this.Start(); } #endregion #region Nested Class - AgentRecord private class AgentRecord { public Guid Id; public Process Process; public TestAgent Agent; public AgentStatus Status; public AgentRecord( Guid id, Process p, TestAgent a, AgentStatus s ) { this.Id = id; this.Process = p; this.Agent = a; this.Status = s; } } #endregion #region Nested Class - AgentDataBase /// <summary> /// A simple class that tracks data about this /// agencies active and available agents /// </summary> private class AgentDataBase : IEnumerable { private ListDictionary agentData = new ListDictionary(); public AgentRecord this[Guid id] { get { return (AgentRecord)agentData[id]; } set { if ( value == null ) agentData.Remove( id ); else agentData[id] = value; } } public AgentRecord this[TestAgent agent] { get { foreach( System.Collections.DictionaryEntry entry in agentData ) { AgentRecord r = (AgentRecord)entry.Value; if ( r.Agent == agent ) return r; } return null; } } public void Add( AgentRecord r ) { agentData[r.Id] = r; } public void Remove(Guid agentId) { agentData.Remove(agentId); } public void Clear() { agentData.Clear(); } #region IEnumerable Members public IEnumerator GetEnumerator() { return new AgentDataEnumerator( agentData ); } #endregion #region Nested Class - AgentDataEnumerator public class AgentDataEnumerator : IEnumerator { IEnumerator innerEnum; public AgentDataEnumerator( IDictionary list ) { innerEnum = list.GetEnumerator(); } #region IEnumerator Members public void Reset() { innerEnum.Reset(); } public object Current { get { return ((DictionaryEntry)innerEnum.Current).Value; } } public bool MoveNext() { return innerEnum.MoveNext(); } #endregion } #endregion } #endregion } }
// // 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 System.IO; using Encog.App.Analyst.Script.ML; using Encog.App.Analyst.Script.Normalize; using Encog.App.Analyst.Script.Process; using Encog.App.Analyst.Script.Prop; using Encog.App.Analyst.Script.Segregate; using Encog.App.Analyst.Script.Task; using Encog.Persist; using Encog.Util.Arrayutil; using Encog.Util.CSV; namespace Encog.App.Analyst.Script { /// <summary> /// Used to load an Encog Analyst script. /// </summary> public class ScriptLoad { /// <summary> /// Column 1. /// </summary> public const int ColumnOne = 1; /// <summary> /// Column 2. /// </summary> public const int ColumnTwo = 2; /// <summary> /// Column 3. /// </summary> public const int ColumnThree = 3; /// <summary> /// Column 4. /// </summary> public const int ColumnFour = 4; /// <summary> /// Column 5. /// </summary> public const int ColumnFive = 5; /// <summary> /// The script being loaded. /// </summary> private readonly AnalystScript _script; /// <summary> /// Construct a script loader. /// </summary> /// <param name="theScript">The script to load into.</param> public ScriptLoad(AnalystScript theScript) { _script = theScript; } /// <summary> /// Handle loading the data classes. /// </summary> /// <param name="section">The section being loaded.</param> private void HandleDataClasses(EncogFileSection section) { var map = new Dictionary<String, List<AnalystClassItem>>(); bool first = true; foreach (String line in section.Lines) { if (!first) { IList<String> cols = EncogFileSection.SplitColumns(line); if (cols.Count < ColumnFour) { throw new AnalystError("Invalid data class: " + line); } String field = cols[0]; String code = cols[1]; String name = cols[2]; int count = Int32.Parse(cols[3]); DataField df = _script.FindDataField(field); if (df == null) { throw new AnalystError( "Attempting to add class to unknown field: " + name); } List<AnalystClassItem> classItems; if (!map.ContainsKey(field)) { classItems = new List<AnalystClassItem>(); map[field] = classItems; } else { classItems = map[field]; } classItems.Add(new AnalystClassItem(code, name, count)); } else { first = false; } } foreach (DataField field in _script.Fields) { if (field.Class) { List<AnalystClassItem> classList = map[field.Name]; if (classList != null) { classList.Sort(); field.ClassMembers.Clear(); foreach (AnalystClassItem item in classList) { field.ClassMembers.Add(item); } } } } } /// <summary> /// Handle loading data stats. /// </summary> /// <param name="section">The section being loaded.</param> private void HandleDataStats(EncogFileSection section) { IList<DataField> dfs = new List<DataField>(); bool first = true; foreach (String line in section.Lines) { if (!first) { IList<String> cols = EncogFileSection.SplitColumns(line); String name = cols[0]; bool isclass = Int32.Parse(cols[1]) > 0; bool iscomplete = Int32.Parse(cols[2]) > 0; bool isint = Int32.Parse(cols[ColumnThree]) > 0; bool isreal = Int32.Parse(cols[ColumnFour]) > 0; double amax = CSVFormat.EgFormat.Parse(cols[5]); double amin = CSVFormat.EgFormat.Parse(cols[6]); double mean = CSVFormat.EgFormat.Parse(cols[7]); double sdev = CSVFormat.EgFormat.Parse(cols[8]); String source = ""; // source was added in Encog 3.2, so it might not be there if (cols.Count > 9) { source = cols[9]; } var df = new DataField(name) { Class = isclass, Complete = iscomplete, Integer = isint, Real = isreal, Max = amax, Min = amin, Mean = mean, StandardDeviation = sdev, Source = source }; dfs.Add(df); } else { first = false; } } var array = new DataField[dfs.Count]; for (int i = 0; i < array.Length; i++) { array[i] = dfs[i]; } _script.Fields = array; } /// <summary> /// Handle loading the filenames. /// </summary> /// <param name="section">The section being loaded.</param> private void HandleFilenames(EncogFileSection section) { IDictionary<String, String> prop = section.ParseParams(); _script.Properties.ClearFilenames(); foreach (var e in prop) { _script.Properties.SetFilename(e.Key, e.Value); } } /// <summary> /// Handle normalization ranges. /// </summary> /// <param name="section">The section being loaded.</param> private void HandleNormalizeRange(EncogFileSection section) { _script.Normalize.NormalizedFields.Clear(); bool first = true; foreach (String line in section.Lines) { if (!first) { IList<String> cols = EncogFileSection.SplitColumns(line); String name = cols[0]; bool isOutput = cols[1].ToLower() .Equals("output"); int timeSlice = Int32.Parse(cols[2]); String action = cols[3]; double high = CSVFormat.EgFormat.Parse(cols[4]); double low = CSVFormat.EgFormat.Parse(cols[5]); NormalizationAction des; if (action.Equals("range")) { des = NormalizationAction.Normalize; } else if (action.Equals("ignore")) { des = NormalizationAction.Ignore; } else if (action.Equals("pass")) { des = NormalizationAction.PassThrough; } else if (action.Equals("equilateral")) { des = NormalizationAction.Equilateral; } else if (action.Equals("single")) { des = NormalizationAction.SingleField; } else if (action.Equals("oneof")) { des = NormalizationAction.OneOf; } else { throw new AnalystError("Unknown field type:" + action); } var nf = new AnalystField(name, des, high, low) {TimeSlice = timeSlice, Output = isOutput}; _script.Normalize.NormalizedFields.Add(nf); } else { first = false; } } } /// <summary> /// Handle loading segregation info. /// </summary> /// <param name="section">The section being loaded.</param> private void HandleSegregateFiles(EncogFileSection section) { IList<AnalystSegregateTarget> nfs = new List<AnalystSegregateTarget>(); bool first = true; foreach (String line in section.Lines) { if (!first) { IList<String> cols = EncogFileSection.SplitColumns(line); String filename = cols[0]; int percent = Int32.Parse(cols[1]); var nf = new AnalystSegregateTarget( filename, percent); nfs.Add(nf); } else { first = false; } } var array = new AnalystSegregateTarget[nfs.Count]; for (int i = 0; i < array.Length; i++) { array[i] = nfs[i]; } _script.Segregate.SegregateTargets = array; } /// <summary> /// Handle loading a task. /// </summary> /// <param name="section">The section.</param> private void HandleTask(EncogFileSection section) { var task = new AnalystTask(section.SubSectionName); foreach (String line in section.Lines) { task.Lines.Add(line); } _script.AddTask(task); } /// <summary> /// Load an Encog script. /// </summary> /// <param name="stream">The stream to load from.</param> public void Load(Stream stream) { EncogReadHelper reader = null; try { EncogFileSection section; reader = new EncogReadHelper(stream); while ((section = reader.ReadNextSection()) != null) { ProcessSubSection(section); } // init the script _script.Init(); } finally { if (reader != null) { reader.Close(); } } } /// <summary> /// Load a generic subsection. /// </summary> /// <param name="section">The section to load from.</param> private void LoadSubSection(EncogFileSection section) { IDictionary<String, String> prop = section.ParseParams(); foreach (String name in prop.Keys) { String key = section.SectionName.ToUpper() + ":" + section.SubSectionName.ToUpper() + "_" + name; String v = prop[name] ?? ""; ValidateProperty(section.SectionName, section.SubSectionName, name, v); _script.Properties.SetProperty(key, v); } } /// <summary> /// Process one of the subsections. /// </summary> /// <param name="section">The section.</param> private void ProcessSubSection(EncogFileSection section) { String currentSection = section.SectionName; String currentSubsection = section.SubSectionName; if (currentSection.Equals("SETUP") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("SETUP") && currentSubsection.Equals("FILENAMES", StringComparison.InvariantCultureIgnoreCase)) { HandleFilenames(section); } else if (currentSection.Equals("DATA") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("DATA") && currentSubsection.Equals("STATS", StringComparison.InvariantCultureIgnoreCase)) { HandleDataStats(section); } else if (currentSection.Equals("DATA") && currentSubsection.Equals("CLASSES", StringComparison.InvariantCultureIgnoreCase)) { HandleDataClasses(section); } else if (currentSection.Equals("NORMALIZE") && currentSubsection.Equals("RANGE", StringComparison.InvariantCultureIgnoreCase)) { HandleNormalizeRange(section); } else if (currentSection.Equals("NORMALIZE") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("NORMALIZE") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("CLUSTER") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("SERIES") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("RANDOMIZE") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("SEGREGATE") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("SEGREGATE") && currentSubsection.Equals("FILES", StringComparison.InvariantCultureIgnoreCase)) { HandleSegregateFiles(section); } else if (currentSection.Equals("GENERATE") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("HEADER") && currentSubsection.Equals("DATASOURCE", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("ML") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("ML") && currentSubsection.Equals("TRAIN", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("TASKS") && (currentSubsection.Length > 0)) { HandleTask(section); } else if (currentSection.Equals("BALANCE") && currentSubsection.Equals("CONFIG", StringComparison.InvariantCultureIgnoreCase)) { LoadSubSection(section); } else if (currentSection.Equals("CODE") && currentSubsection.Equals("CONFIG")) { LoadSubSection(section); } else if (currentSection.Equals("PROCESS") && currentSubsection.Equals("CONFIG")) { LoadSubSection(section); } else if (currentSection.Equals("PROCESS") && currentSubsection.Equals("FIELDS")) { HandleProcessFields(section); } } /// <summary> /// Validate a property. /// </summary> /// <param name="section">The section.</param> /// <param name="subSection">The sub section.</param> /// <param name="name">The name of the property.</param> /// <param name="value_ren">The new value for the property.</param> private void ValidateProperty(String section, String subSection, String name, String value_ren) { PropertyEntry entry = PropertyConstraints.Instance.GetEntry( section, subSection, name); if (entry == null) { throw new AnalystError("Unknown property: " + PropertyEntry.DotForm(section, subSection, name)); } entry.Validate(section, subSection, name, value_ren); } private void HandleProcessFields(EncogFileSection section) { IList<ProcessField> fields = _script.Process.Fields; bool first = true; fields.Clear(); foreach (string line in section.Lines) { if (!first) { IList<string> cols = EncogFileSection.SplitColumns(line); String name = cols[0]; String command = cols[1]; var pf = new ProcessField(name, command); fields.Add(pf); } else { first = false; } } } private void LoadOpcodes(EncogFileSection section) { bool first = true; foreach (string line in section.Lines) { if (!first) { IList<string> cols = EncogFileSection.SplitColumns(line); string name = cols[0]; int childCount = int.Parse(cols[1]); var opcode = new ScriptOpcode(name, childCount); _script.Opcodes.Add(opcode); } else { first = false; } } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GraphServiceDomainsCollectionRequest. /// </summary> public partial class GraphServiceDomainsCollectionRequest : BaseRequest, IGraphServiceDomainsCollectionRequest { /// <summary> /// Constructs a new GraphServiceDomainsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public GraphServiceDomainsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Domain to the collection via POST. /// </summary> /// <param name="domain">The Domain to add.</param> /// <returns>The created Domain.</returns> public System.Threading.Tasks.Task<Domain> AddAsync(Domain domain) { return this.AddAsync(domain, CancellationToken.None); } /// <summary> /// Adds the specified Domain to the collection via POST. /// </summary> /// <param name="domain">The Domain to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Domain.</returns> public System.Threading.Tasks.Task<Domain> AddAsync(Domain domain, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Domain>(domain, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IGraphServiceDomainsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IGraphServiceDomainsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<GraphServiceDomainsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest Expand(Expression<Func<Domain, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest Select(Expression<Func<Domain, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDomainsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.CodeGeneration; using Orleans.Configuration; using Orleans.Internal; using Orleans.Messaging; using Orleans.Providers; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using Orleans.Streams; namespace Orleans { internal class OutsideRuntimeClient : IRuntimeClient, IDisposable, IClusterConnectionStatusListener { internal static bool TestOnlyThrowExceptionDuringInit { get; set; } private readonly ILogger logger; private readonly ClientMessagingOptions clientMessagingOptions; private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks; private InvokableObjectManager localObjects; private bool disposing; private ClientProviderRuntime clientProviderRuntime; internal readonly ClientStatisticsManager ClientStatistics; private readonly MessagingTrace messagingTrace; private readonly ClientGrainId clientId; private ThreadTrackingStatistic incomingMessagesThreadTimeTracking; private static readonly TimeSpan ResetTimeout = TimeSpan.FromMinutes(1); private const string BARS = "----------"; public IInternalGrainFactory InternalGrainFactory { get; private set; } private MessageFactory messageFactory; private IPAddress localAddress; private readonly ILoggerFactory loggerFactory; private readonly IOptions<StatisticsOptions> statisticsOptions; private readonly ApplicationRequestsStatisticsGroup appRequestStatistics; private readonly StageAnalysisStatisticsGroup schedulerStageStatistics; private readonly SharedCallbackData sharedCallbackData; private SafeTimer callbackTimer; public ActivationAddress CurrentActivationAddress { get; private set; } public string CurrentActivationIdentity { get { return CurrentActivationAddress.ToString(); } } public IStreamProviderRuntime CurrentStreamProviderRuntime { get { return clientProviderRuntime; } } public IGrainReferenceRuntime GrainReferenceRuntime { get; private set; } internal ClientMessageCenter MessageCenter { get; private set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")] public OutsideRuntimeClient( ILoggerFactory loggerFactory, IOptions<ClientMessagingOptions> clientMessagingOptions, IOptions<StatisticsOptions> statisticsOptions, ApplicationRequestsStatisticsGroup appRequestStatistics, StageAnalysisStatisticsGroup schedulerStageStatistics, ClientStatisticsManager clientStatisticsManager, MessagingTrace messagingTrace) { this.loggerFactory = loggerFactory; this.statisticsOptions = statisticsOptions; this.appRequestStatistics = appRequestStatistics; this.schedulerStageStatistics = schedulerStageStatistics; this.ClientStatistics = clientStatisticsManager; this.messagingTrace = messagingTrace; this.logger = loggerFactory.CreateLogger<OutsideRuntimeClient>(); this.clientId = ClientGrainId.Create(); callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>(); this.clientMessagingOptions = clientMessagingOptions.Value; this.sharedCallbackData = new SharedCallbackData( msg => this.UnregisterCallback(msg.Id), this.loggerFactory.CreateLogger<CallbackData>(), this.clientMessagingOptions, this.appRequestStatistics, this.clientMessagingOptions.ResponseTimeout); } internal void ConsumeServices(IServiceProvider services) { try { this.ServiceProvider = services; var connectionLostHandlers = this.ServiceProvider.GetServices<ConnectionToClusterLostHandler>(); foreach (var handler in connectionLostHandlers) { this.ClusterConnectionLost += handler; } var gatewayCountChangedHandlers = this.ServiceProvider.GetServices<GatewayCountChangedHandler>(); foreach (var handler in gatewayCountChangedHandlers) { this.GatewayCountChanged += handler; } this.InternalGrainFactory = this.ServiceProvider.GetRequiredService<IInternalGrainFactory>(); this.messageFactory = this.ServiceProvider.GetService<MessageFactory>(); var serializationManager = this.ServiceProvider.GetRequiredService<SerializationManager>(); this.localObjects = new InvokableObjectManager( services.GetRequiredService<ClientGrainContext>(), this, serializationManager, this.messagingTrace, this.loggerFactory.CreateLogger<ClientGrainContext>()); var timerLogger = this.loggerFactory.CreateLogger<SafeTimer>(); var minTicks = Math.Min(this.clientMessagingOptions.ResponseTimeout.Ticks, TimeSpan.FromSeconds(1).Ticks); var period = TimeSpan.FromTicks(minTicks); this.callbackTimer = new SafeTimer(timerLogger, this.OnCallbackExpiryTick, null, period, period); this.GrainReferenceRuntime = this.ServiceProvider.GetRequiredService<IGrainReferenceRuntime>(); BufferPool.InitGlobalBufferPool(this.clientMessagingOptions); this.clientProviderRuntime = this.ServiceProvider.GetRequiredService<ClientProviderRuntime>(); this.localAddress = this.clientMessagingOptions.LocalAddress ?? ConfigUtilities.GetLocalIPAddress(this.clientMessagingOptions.PreferredFamily, this.clientMessagingOptions.NetworkInterfaceName); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, Dns.GetHostName(), localAddress, clientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}", BARS, RuntimeVersion.Current, PrintAppDomainDetails()); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit"); } var statisticsLevel = statisticsOptions.Value.CollectionLevel; if (statisticsLevel.CollectThreadTimeTrackingStats()) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver", this.loggerFactory, this.statisticsOptions, this.schedulerStageStatistics); } } catch (Exception exc) { if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); ConstructorReset(); throw; } } public IServiceProvider ServiceProvider { get; private set; } public async Task Start(Func<Exception, Task<bool>> retryFilter = null) { // Deliberately avoid capturing the current synchronization context during startup and execute on the default scheduler. // This helps to avoid any issues (such as deadlocks) caused by executing with the client's synchronization context/scheduler. await Task.Run(() => this.StartInternal(retryFilter)).ConfigureAwait(false); logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client ID: " + clientId); } // used for testing to (carefully!) allow two clients in the same process private async Task StartInternal(Func<Exception, Task<bool>> retryFilter) { var gatewayManager = this.ServiceProvider.GetRequiredService<GatewayManager>(); await ExecuteWithRetries(async () => await gatewayManager.StartAsync(CancellationToken.None), retryFilter); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative MessageCenter = ActivatorUtilities.CreateInstance<ClientMessageCenter>(this.ServiceProvider, localAddress, generation, clientId); MessageCenter.RegisterLocalMessageHandler(this.HandleMessage); MessageCenter.Start(); CurrentActivationAddress = ActivationAddress.NewActivationAddress(MessageCenter.MyAddress, clientId.GrainId); await ExecuteWithRetries( async () => await this.ServiceProvider.GetRequiredService<ClientClusterManifestProvider>().StartAsync(), retryFilter); ClientStatistics.Start(MessageCenter, clientId.GrainId); clientProviderRuntime.StreamingInitialize(); async Task ExecuteWithRetries(Func<Task> task, Func<Exception, Task<bool>> shouldRetry) { while (true) { try { await task(); return; } catch (Exception exception) when (shouldRetry != null) { var retry = await shouldRetry(exception); if (!retry) throw; } } } } private void HandleMessage(Message message) { switch (message.Direction) { case Message.Directions.Response: { ReceiveResponse(message); break; } case Message.Directions.OneWay: case Message.Directions.Request: { this.localObjects.Dispatch(message); break; } default: logger.Error(ErrorCode.Runtime_Error_100327, $"Message not supported: {message}."); break; } } public void SendResponse(Message request, Response response) { var message = this.messageFactory.CreateResponseMessage(request); OrleansOutsideRuntimeClientEvent.Log.SendResponse(message); message.BodyObject = response; MessageCenter.SendMessage(message); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")] public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, InvokeMethodOptions options) { var message = this.messageFactory.CreateMessage(request, options); OrleansOutsideRuntimeClientEvent.Log.SendRequest(message); SendRequestMessage(target, message, context, options); } private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, InvokeMethodOptions options) { message.InterfaceType = target.InterfaceType; message.InterfaceVersion = target.InterfaceVersion; var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (SystemTargetGrainId.TryParse(targetGrainId, out var systemTargetGrainId)) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = systemTargetGrainId.GetSiloAddress(); message.TargetActivation = ActivationId.GetDeterministic(targetGrainId); } if (message.IsExpirableMessage(this.clientMessagingOptions.DropExpiredMessages)) { // don't set expiration for system target messages. message.TimeToLive = this.clientMessagingOptions.ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData(this.sharedCallbackData, context, message); callbacks.TryAdd(message.Id, callbackData); } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Send {0}", message); MessageCenter.SendMessage(message); } public void ReceiveResponse(Message response) { OrleansOutsideRuntimeClientEvent.Log.ReceiveResponse(response); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Received {0}", response); // ignore duplicate requests if (response.Result == Message.ResponseTypes.Rejection && (response.RejectionType == Message.RejectionTypes.DuplicateRequest || response.RejectionType == Message.RejectionTypes.CacheInvalidation)) { return; } CallbackData callbackData; var found = callbacks.TryRemove(response.Id, out callbackData); if (found) { // We need to import the RequestContext here as well. // Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task. // RequestContextExtensions.Import(response.RequestContextData); callbackData.DoCallback(response); } else { logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response); } } private void UnregisterCallback(CorrelationId id) { CallbackData ignore; callbacks.TryRemove(id, out ignore); } public void Reset(bool cleanup) { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId); } }, this.logger); Utils.SafeExecute(() => { if (clientProviderRuntime != null) { clientProviderRuntime.Reset(cleanup).WaitWithThrow(ResetTimeout); } }, logger, "Client.clientProviderRuntime.Reset"); Utils.SafeExecute(() => { incomingMessagesThreadTimeTracking?.OnStopExecution(); }, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution"); Utils.SafeExecute(() => { if (MessageCenter != null) { MessageCenter.Stop(); } }, logger, "Client.Stop-Transport"); Utils.SafeExecute(() => { if (ClientStatistics != null) { ClientStatistics.Stop(); } }, logger, "Client.Stop-ClientStatistics"); ConstructorReset(); } private void ConstructorReset() { Utils.SafeExecute(() => { if (logger != null) { logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId); } }); try { if (clientProviderRuntime != null) { clientProviderRuntime.Reset().WaitWithThrow(ResetTimeout); } } catch (Exception) { } Utils.SafeExecute(() => this.Dispose()); } /// <inheritdoc /> public TimeSpan GetResponseTimeout() => this.sharedCallbackData.ResponseTimeout; /// <inheritdoc /> public void SetResponseTimeout(TimeSpan timeout) => this.sharedCallbackData.ResponseTimeout = timeout; public IAddressable CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker) { if (obj is GrainReference) throw new ArgumentException("Argument obj is already a grain reference.", nameof(obj)); if (obj is Grain) throw new ArgumentException("Argument must not be a grain class.", nameof(obj)); var observerId = ObserverGrainId.Create(this.clientId); var reference = this.InternalGrainFactory.GetGrain(observerId.GrainId); if (!localObjects.TryRegister(obj, observerId, invoker)) { throw new ArgumentException($"Failed to add new observer {reference} to localObjects collection.", "reference"); } return reference; } public void DeleteObjectReference(IAddressable obj) { if (!(obj is GrainReference reference)) { throw new ArgumentException("Argument reference is not a grain reference."); } if (!ObserverGrainId.TryParse(reference.GrainId, out var observerId)) { throw new ArgumentException($"Reference {reference.GrainId} is not an observer reference"); } if (!localObjects.TryDeregister(observerId)) { throw new ArgumentException("Reference is not associated with a local object.", "reference"); } } private string PrintAppDomainDetails() { return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName); } public void Dispose() { if (this.disposing) return; this.disposing = true; Utils.SafeExecute(() => this.callbackTimer?.Dispose()); Utils.SafeExecute(() => MessageCenter?.Dispose()); this.ClusterConnectionLost = null; this.GatewayCountChanged = null; GC.SuppressFinalize(this); } public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo) { foreach (var callback in callbacks) { if (deadSilo.Equals(callback.Value.Message.TargetSilo)) { callback.Value.OnTargetSiloFail(); } } } /// <inheritdoc /> public event ConnectionToClusterLostHandler ClusterConnectionLost; /// <inheritdoc /> public event GatewayCountChangedHandler GatewayCountChanged; /// <inheritdoc /> public void NotifyClusterConnectionLost() { try { this.ClusterConnectionLost?.Invoke(this, EventArgs.Empty); } catch (Exception ex) { this.logger.Error(ErrorCode.ClientError, "Error when sending cluster disconnection notification", ex); } } /// <inheritdoc /> public void NotifyGatewayCountChanged(int currentNumberOfGateways, int previousNumberOfGateways) { try { this.GatewayCountChanged?.Invoke(this, new GatewayCountChangedEventArgs(currentNumberOfGateways, previousNumberOfGateways)); } catch (Exception ex) { this.logger.Error(ErrorCode.ClientError, "Error when sending gateway count changed notification", ex); } } private void OnCallbackExpiryTick(object state) { var currentStopwatchTicks = Stopwatch.GetTimestamp(); foreach (var pair in callbacks) { var callback = pair.Value; if (callback.IsCompleted) continue; if (callback.IsExpired(currentStopwatchTicks)) callback.OnTimeout(this.clientMessagingOptions.ResponseTimeout); } } } }
/******************************************************************** 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.Diagnostics; using System.IO; namespace Axiom.SceneManagers.Multiverse { public class TextureMosaic : Mosaic { protected override MosaicTile NewTile(int tileX, int tileZ, MathLib.Vector3 worldLocMM) { return new TextureMosaicTile(this, desc.TileSizeSamples, desc.MetersPerSample, tileX, tileZ, worldLocMM); } public TextureMosaic(string baseName, int preloadRadius) : base(baseName, preloadRadius) { } public TextureMosaic(string baseName, int preloadRadius, MosaicDescription desc) : base(baseName, preloadRadius, desc) { } public string GetTexture(int worldXMeters, int worldZMeters, int sizeXMeters, int sizeZMeters, out float u1, out float v1, out float u2, out float v2) { worldXMeters = worldXMeters + xWorldOffsetMeters; worldZMeters = worldZMeters + zWorldOffsetMeters; int tileX = worldXMeters >> (tileShift + desc.MPSShift); int tileZ = worldZMeters >> (tileShift + desc.MPSShift); int tileSizeWorld = desc.TileSizeSamples << desc.MPSShift; int tileMaskWorld = tileSizeWorld - 1; int xoff = worldXMeters & tileMaskWorld; int zoff = worldZMeters & tileMaskWorld; u1 = (float)xoff / tileSizeWorld; v1 = (float)zoff / tileSizeWorld; u2 = (float)(xoff + sizeXMeters) / tileSizeWorld; v2 = (float)(zoff + sizeZMeters) / tileSizeWorld; if (tileX < 0 || tileX >= sizeXTiles || tileZ < 0 || tileZ >= sizeZTiles) { return "red-zero-alpha.png"; } TextureMosaicTile tile = tiles[tileX, tileZ] as TextureMosaicTile; if (tile == null) { throw new InvalidDataException("Unxpected state!"); } return tile.TextureName; } protected void SampleToTileCoords(int sampleX, int sampleZ, out int tileX, out int tileZ, out int xOff, out int zOff) { int tileSize = desc.TileSizeSamples; tileX = sampleX >> tileShift; tileZ = sampleZ >> tileShift; xOff = sampleX & tileMask; zOff = sampleZ & tileMask; Debug.Assert(xOff < tileSize); Debug.Assert(zOff < tileSize); return; } protected internal void WorldToSampleCoords(int worldXMeters, int worldZMeters, out int sampleX, out int sampleZ, out float sampleXfrac, out float sampleZfrac) { worldXMeters = worldXMeters + xWorldOffsetMeters; worldZMeters = worldZMeters + zWorldOffsetMeters; sampleX = worldXMeters >> desc.MPSShift; sampleZ = worldZMeters >> desc.MPSShift; int sampleXRem = worldXMeters & desc.MPSMask; int sampleZRem = worldZMeters & desc.MPSMask; if ((sampleXRem != 0) || (sampleZRem != 0)) { sampleXfrac = (float)sampleXRem / desc.MetersPerSample; sampleZfrac = (float)sampleZRem / desc.MetersPerSample; } else { sampleXfrac = 0; sampleZfrac = 0; } } /// <summary> /// Get the texture map for a point specified by sample coordinates /// A 4-byte array is returned as the map. The map can have 4 possible /// mappings associated with it with one byte per map. /// </summary> /// <param name="sampleX"></param> /// <param name="sampleZ"></param> /// <returns></returns> public byte[] GetSampleTextureMap(int sampleX, int sampleZ) { int tileX; int tileZ; int xOff; int zOff; SampleToTileCoords(sampleX, sampleZ, out tileX, out tileZ, out xOff, out zOff); if ((tileX < 0) || (tileX >= sizeXTiles) || (tileZ < 0) || (tileZ >= sizeZTiles)) { return new byte[4]; } TextureMosaicTile tile = tiles[tileX, tileZ] as TextureMosaicTile; if (tile == null) { return new byte[4]; } return tile.GetTextureMap(xOff, zOff); } /// <summary> /// Set the texture map for a point specified by sample coordinates. /// The 4-byte array is map. The map can have 4 possible mappings associated /// with it with one byte per map. /// </summary> /// <param name="sampleX"></param> /// <param name="sampleZ"></param> /// <param name="textureMap"></param> /// <returns></returns> public void SetSampleTextureMap(int sampleX, int sampleZ, byte[] textureMap) { int tileX; int tileZ; int xOff; int zOff; SampleToTileCoords(sampleX, sampleZ, out tileX, out tileZ, out xOff, out zOff); if ((tileX < 0) || (tileX >= sizeXTiles) || (tileZ < 0) || (tileZ >= sizeZTiles)) { return; // Ignore out-of-bounds modifications } TextureMosaicTile tile = tiles[tileX, tileZ] as TextureMosaicTile; if (tile == null) { // This shouldn't happen throw new Exception("Tile [" + tileX + "," + tileZ + "] not found for coord [" + sampleX + "," + sampleZ + "] while attempting to set textureMap to: " + textureMap); } tile.SetTextureMap(xOff, zOff, textureMap); } /// <summary> /// Get the texture map for a point specified by world coordinates /// A 4-byte array is returned as the map. The map can have 4 possible /// mappings associated with it with one byte per map. /// </summary> /// <param name="worldXMeters"></param> /// <param name="worldZMeters"></param> /// <returns></returns> public byte[] GetWorldTextureMap(int worldXMeters, int worldZMeters) { int sampleX; int sampleZ; float sampleXfrac; float sampleZfrac; WorldToSampleCoords(worldXMeters, worldZMeters, out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac); if ((sampleXfrac == 0) && (sampleZfrac == 0)) { // pick the closest point to the NW(floor), rather than interpolating return GetSampleTextureMap(sampleX, sampleZ); } // perform a linear interpolation between the 4 surrounding points for each byte within the map byte[] nw = GetSampleTextureMap(sampleX, sampleZ); byte[] ne = GetSampleTextureMap(sampleX + 1, sampleZ); byte[] sw = GetSampleTextureMap(sampleX, sampleZ + 1); byte[] se = GetSampleTextureMap(sampleX + 1, sampleZ + 1); byte[] ret = new byte[4]; for (int i = 0; i < ret.Length; i++) { if (sampleXfrac >= sampleZfrac) { ret[i] = (byte)((nw[i] + (ne[i] - nw[i]) * sampleXfrac + (se[i] - ne[i]) * sampleZfrac)); } else { ret[i] = (byte)((sw[i] + (se[i] - sw[i]) * sampleXfrac + (nw[i] - sw[i]) * (1 - sampleZfrac))); } } return ret; } /// <summary> /// Set the texture map for a point specified by sample coordinates. /// The 4-byte array is map. The map can have 4 possible mappings associated /// with it with one byte per map. /// </summary> /// <param name="worldXMeters"></param> /// <param name="worldZMeters"></param> /// <param name="textureMap"></param> /// <returns></returns> public void SetWorldTextureMap(int worldXMeters, int worldZMeters, byte[] textureMap) { int sampleX; int sampleZ; float sampleXfrac; float sampleZfrac; WorldToSampleCoords(worldXMeters, worldZMeters, out sampleX, out sampleZ, out sampleXfrac, out sampleZfrac); SetSampleTextureMap(sampleX, sampleZ, textureMap); // Ignore the fractional coordinates } public void RefreshTextures() { foreach (TextureMosaicTile tile in tiles) { if (tile != null) { tile.RefreshTexture(); } } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Host; using System.Reflection; using Dbg = System.Management.Automation.Diagnostics; using InternalHostUserInterface = System.Management.Automation.Internal.Host.InternalHostUserInterface; namespace System.Management.Automation.Remoting { /// <summary> /// Executes methods; can be encoded and decoded for transmission over the /// wire. /// </summary> internal class RemoteHostCall { /// <summary> /// Method name. /// </summary> internal string MethodName { get { return _methodInfo.Name; } } /// <summary> /// Method id. /// </summary> internal RemoteHostMethodId MethodId { get; } /// <summary> /// Parameters. /// </summary> internal object[] Parameters { get; } /// <summary> /// Method info. /// </summary> private readonly RemoteHostMethodInfo _methodInfo; /// <summary> /// Call id. /// </summary> private readonly long _callId; /// <summary> /// Call id. /// </summary> internal long CallId { get { return _callId; } } /// <summary> /// Computer name to be used in messages. /// </summary> private string _computerName; /// <summary> /// Constructor for RemoteHostCall. /// </summary> internal RemoteHostCall(long callId, RemoteHostMethodId methodId, object[] parameters) { Dbg.Assert(parameters != null, "Expected parameters != null"); _callId = callId; MethodId = methodId; Parameters = parameters; _methodInfo = RemoteHostMethodInfo.LookUp(methodId); } /// <summary> /// Encode parameters. /// </summary> private static PSObject EncodeParameters(object[] parameters) { // Encode the parameters and wrap the array into an ArrayList and then into a PSObject. ArrayList parameterList = new ArrayList(); for (int i = 0; i < parameters.Length; ++i) { object parameter = parameters[i] == null ? null : RemoteHostEncoder.EncodeObject(parameters[i]); parameterList.Add(parameter); } return new PSObject(parameterList); } /// <summary> /// Decode parameters. /// </summary> private static object[] DecodeParameters(PSObject parametersPSObject, Type[] parameterTypes) { // Extract the ArrayList and decode the parameters. ArrayList parameters = (ArrayList)parametersPSObject.BaseObject; List<object> decodedParameters = new List<object>(); Dbg.Assert(parameters.Count == parameterTypes.Length, "Expected parameters.Count == parameterTypes.Length"); for (int i = 0; i < parameters.Count; ++i) { object parameter = parameters[i] == null ? null : RemoteHostEncoder.DecodeObject(parameters[i], parameterTypes[i]); decodedParameters.Add(parameter); } return decodedParameters.ToArray(); } /// <summary> /// Encode. /// </summary> internal PSObject Encode() { // Add all host information as data. PSObject data = RemotingEncoder.CreateEmptyPSObject(); // Encode the parameters for transport. PSObject parametersPSObject = EncodeParameters(Parameters); // Embed everything into the main PSobject. data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, _callId)); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodId, MethodId)); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodParameters, parametersPSObject)); return data; } /// <summary> /// Decode. /// </summary> internal static RemoteHostCall Decode(PSObject data) { Dbg.Assert(data != null, "Expected data != null"); // Extract all the fields from data. long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId); PSObject parametersPSObject = RemotingDecoder.GetPropertyValue<PSObject>(data, RemoteDataNameStrings.MethodParameters); RemoteHostMethodId methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(data, RemoteDataNameStrings.MethodId); // Look up all the info related to the method. RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); // Decode the parameters. object[] parameters = DecodeParameters(parametersPSObject, methodInfo.ParameterTypes); // Create and return the RemoteHostCall. return new RemoteHostCall(callId, methodId, parameters); } /// <summary> /// Is void method. /// </summary> internal bool IsVoidMethod { get { return _methodInfo.ReturnType == typeof(void); } } /// <summary> /// Execute void method. /// </summary> internal void ExecuteVoidMethod(PSHost clientHost) { // The clientHost can be null if the user creates a runspace object without providing // a host parameter. if (clientHost == null) { return; } RemoteRunspace remoteRunspaceToClose = null; if (this.IsSetShouldExitOrPopRunspace) { remoteRunspaceToClose = GetRemoteRunspaceToClose(clientHost); } try { object targetObject = this.SelectTargetObject(clientHost); MyMethodBase.Invoke(targetObject, Parameters); } finally { if (remoteRunspaceToClose != null) { remoteRunspaceToClose.Close(); } } } /// <summary> /// Get remote runspace to close. /// </summary> private static RemoteRunspace GetRemoteRunspaceToClose(PSHost clientHost) { // Figure out if we need to close the remote runspace. Return null if we don't. // Are we a Start-PSSession enabled host? IHostSupportsInteractiveSession host = clientHost as IHostSupportsInteractiveSession; if (host == null || !host.IsRunspacePushed) { return null; } // Now inspect the runspace. RemoteRunspace remoteRunspace = host.Runspace as RemoteRunspace; if (remoteRunspace == null || !remoteRunspace.ShouldCloseOnPop) { return null; } // At this point it is clear we have to close the remote runspace, so return it. return remoteRunspace; } /// <summary> /// My method base. /// </summary> private MethodBase MyMethodBase { get { return (MethodBase)_methodInfo.InterfaceType.GetMethod(_methodInfo.Name, _methodInfo.ParameterTypes); } } /// <summary> /// Execute non void method. /// </summary> internal RemoteHostResponse ExecuteNonVoidMethod(PSHost clientHost) { // The clientHost can be null if the user creates a runspace object without providing // a host parameter. if (clientHost == null) { throw RemoteHostExceptions.NewNullClientHostException(); } object targetObject = this.SelectTargetObject(clientHost); RemoteHostResponse remoteHostResponse = this.ExecuteNonVoidMethodOnObject(targetObject); return remoteHostResponse; } /// <summary> /// Execute non void method on object. /// </summary> private RemoteHostResponse ExecuteNonVoidMethodOnObject(object instance) { // Create variables to store result of execution. Exception exception = null; object returnValue = null; // Invoke the method and store its return values. try { if (MethodId == RemoteHostMethodId.GetBufferContents) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RemoteHostGetBufferContents, _computerName.ToUpper()); } returnValue = MyMethodBase.Invoke(instance, Parameters); } catch (Exception e) { // Catch-all OK, 3rd party callout. exception = e.InnerException; } // Create a RemoteHostResponse object to store the return value and exceptions. return new RemoteHostResponse(_callId, MethodId, returnValue, exception); } /// <summary> /// Get the object that this method should be invoked on. /// </summary> private object SelectTargetObject(PSHost host) { if (host == null || host.UI == null) { return null; } if (_methodInfo.InterfaceType == typeof(PSHost)) { return host; } if (_methodInfo.InterfaceType == typeof(IHostSupportsInteractiveSession)) { return host; } if (_methodInfo.InterfaceType == typeof(PSHostUserInterface)) { return host.UI; } if (_methodInfo.InterfaceType == typeof(IHostUISupportsMultipleChoiceSelection)) { return host.UI; } if (_methodInfo.InterfaceType == typeof(PSHostRawUserInterface)) { return host.UI.RawUI; } throw RemoteHostExceptions.NewUnknownTargetClassException(_methodInfo.InterfaceType.ToString()); } /// <summary> /// Is set should exit. /// </summary> internal bool IsSetShouldExit { get { return MethodId == RemoteHostMethodId.SetShouldExit; } } /// <summary> /// Is set should exit or pop runspace. /// </summary> internal bool IsSetShouldExitOrPopRunspace { get { return MethodId == RemoteHostMethodId.SetShouldExit || MethodId == RemoteHostMethodId.PopRunspace; } } /// <summary> /// This message performs various security checks on the /// remote host call message. If there is a need to modify /// the message or discard it for security reasons then /// such modifications will be made here. /// </summary> /// <param name="computerName">computer name to use in /// warning messages</param> /// <returns>A collection of remote host calls which will /// have to be executed before this host call can be /// executed.</returns> internal Collection<RemoteHostCall> PerformSecurityChecksOnHostMessage(string computerName) { Dbg.Assert(!string.IsNullOrEmpty(computerName), "Computer Name must be passed for use in warning messages"); _computerName = computerName; Collection<RemoteHostCall> prerequisiteCalls = new Collection<RemoteHostCall>(); // check if the incoming message is a PromptForCredential message // if so, do the following: // (a) prepend "PowerShell Credential Request" in the title // (b) prepend "Message from Server XXXXX" to the text message if (MethodId == RemoteHostMethodId.PromptForCredential1 || MethodId == RemoteHostMethodId.PromptForCredential2) { // modify the caption which is _parameters[0] string modifiedCaption = ModifyCaption((string)Parameters[0]); // modify the message which is _parameters[1] string modifiedMessage = ModifyMessage((string)Parameters[1], computerName); Parameters[0] = modifiedCaption; Parameters[1] = modifiedMessage; } // Check if the incoming message is a Prompt message // if so, then do the following: // (a) check if any of the field descriptions // correspond to PSCredential // (b) if field descriptions correspond to // PSCredential modify the caption and // message as in the previous case above else if (MethodId == RemoteHostMethodId.Prompt) { // check if any of the field descriptions is for type // PSCredential if (Parameters.Length == 3) { Collection<FieldDescription> fieldDescs = (Collection<FieldDescription>)Parameters[2]; bool havePSCredential = false; foreach (FieldDescription fieldDesc in fieldDescs) { fieldDesc.IsFromRemoteHost = true; Type fieldType = InternalHostUserInterface.GetFieldType(fieldDesc); if (fieldType != null) { if (fieldType == typeof(PSCredential)) { havePSCredential = true; fieldDesc.ModifiedByRemotingProtocol = true; } else if (fieldType == typeof(System.Security.SecureString)) { prerequisiteCalls.Add(ConstructWarningMessageForSecureString( computerName, RemotingErrorIdStrings.RemoteHostPromptSecureStringPrompt)); } } } if (havePSCredential) { // modify the caption which is parameter[0] string modifiedCaption = ModifyCaption((string)Parameters[0]); // modify the message which is parameter[1] string modifiedMessage = ModifyMessage((string)Parameters[1], computerName); Parameters[0] = modifiedCaption; Parameters[1] = modifiedMessage; } } } // Check if the incoming message is a readline as secure string // if so do the following: // (a) Specify a warning message that the server is // attempting to read something securely on the client else if (MethodId == RemoteHostMethodId.ReadLineAsSecureString) { prerequisiteCalls.Add(ConstructWarningMessageForSecureString( computerName, RemotingErrorIdStrings.RemoteHostReadLineAsSecureStringPrompt)); } // check if the incoming call is GetBufferContents // if so do the following: // (a) Specify a warning message that the server is // attempting to read the screen buffer contents // on screen and it has been blocked // (b) Modify the message so that call is not executed else if (MethodId == RemoteHostMethodId.GetBufferContents) { prerequisiteCalls.Add(ConstructWarningMessageForGetBufferContents(computerName)); } return prerequisiteCalls; } /// <summary> /// Provides the modified caption for the given caption /// Used in ensuring that remote prompt messages are /// tagged with "PowerShell Credential Request" /// </summary> /// <param name="caption">Caption to modify.</param> /// <returns>New modified caption.</returns> private static string ModifyCaption(string caption) { string pscaption = CredUI.PromptForCredential_DefaultCaption; if (!caption.Equals(pscaption, StringComparison.OrdinalIgnoreCase)) { string modifiedCaption = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedCaption, caption); return modifiedCaption; } return caption; } /// <summary> /// Provides the modified message for the given one /// Used in ensuring that remote prompt messages /// contain a warning that they originate from a /// different computer. /// </summary> /// <param name="message">Original message to modify.</param> /// <param name="computerName">computername to include in the /// message</param> /// <returns>Message which contains a warning as well.</returns> private static string ModifyMessage(string message, string computerName) { string modifiedMessage = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostPromptForCredentialModifiedMessage, computerName.ToUpper(), message); return modifiedMessage; } /// <summary> /// Creates a warning message which displays to the user a /// warning stating that the remote host computer is /// actually attempting to read a line as a secure string. /// </summary> /// <param name="computerName">computer name to include /// in warning</param> /// <param name="resourceString">Resource string to use.</param> /// <returns>A constructed remote host call message /// which will display the warning.</returns> private static RemoteHostCall ConstructWarningMessageForSecureString(string computerName, string resourceString) { string warning = PSRemotingErrorInvariants.FormatResourceString( resourceString, computerName.ToUpper()); return new RemoteHostCall(ServerDispatchTable.VoidCallId, RemoteHostMethodId.WriteWarningLine, new object[] { warning }); } /// <summary> /// Creates a warning message which displays to the user a /// warning stating that the remote host computer is /// attempting to read the host's buffer contents and that /// it was suppressed. /// </summary> /// <param name="computerName">computer name to include /// in warning</param> /// <returns>A constructed remote host call message /// which will display the warning.</returns> private static RemoteHostCall ConstructWarningMessageForGetBufferContents(string computerName) { string warning = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostGetBufferContents, computerName.ToUpper()); return new RemoteHostCall(ServerDispatchTable.VoidCallId, RemoteHostMethodId.WriteWarningLine, new object[] { warning }); } } /// <summary> /// Encapsulates the method response semantics. Method responses are generated when /// RemoteHostCallPacket objects are executed. They can contain both the return values of /// the execution as well as exceptions that were thrown in the RemoteHostCallPacket /// execution. They can be encoded and decoded for transporting over the wire. A /// method response can be used to transport the result of an execution and then to /// simulate the execution on the other end. /// </summary> internal class RemoteHostResponse { /// <summary> /// Call id. /// </summary> private readonly long _callId; /// <summary> /// Call id. /// </summary> internal long CallId { get { return _callId; } } /// <summary> /// Method id. /// </summary> private readonly RemoteHostMethodId _methodId; /// <summary> /// Return value. /// </summary> private readonly object _returnValue; /// <summary> /// Exception. /// </summary> private readonly Exception _exception; /// <summary> /// Constructor for RemoteHostResponse. /// </summary> internal RemoteHostResponse(long callId, RemoteHostMethodId methodId, object returnValue, Exception exception) { _callId = callId; _methodId = methodId; _returnValue = returnValue; _exception = exception; } /// <summary> /// Simulate execution. /// </summary> internal object SimulateExecution() { if (_exception != null) { throw _exception; } return _returnValue; } /// <summary> /// Encode and add return value. /// </summary> private static void EncodeAndAddReturnValue(PSObject psObject, object returnValue) { // Do nothing if the return value is null. if (returnValue == null) { return; } // Otherwise add the property. RemoteHostEncoder.EncodeAndAddAsProperty(psObject, RemoteDataNameStrings.MethodReturnValue, returnValue); } /// <summary> /// Decode return value. /// </summary> private static object DecodeReturnValue(PSObject psObject, Type returnType) { object returnValue = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodReturnValue, returnType); return returnValue; } /// <summary> /// Encode and add exception. /// </summary> private static void EncodeAndAddException(PSObject psObject, Exception exception) { RemoteHostEncoder.EncodeAndAddAsProperty(psObject, RemoteDataNameStrings.MethodException, exception); } /// <summary> /// Decode exception. /// </summary> private static Exception DecodeException(PSObject psObject) { object result = RemoteHostEncoder.DecodePropertyValue(psObject, RemoteDataNameStrings.MethodException, typeof(Exception)); if (result == null) { return null; } if (result is Exception) { return (Exception)result; } throw RemoteHostExceptions.NewDecodingFailedException(); } /// <summary> /// Encode. /// </summary> internal PSObject Encode() { // Create a data object and put everything in that and return it. PSObject data = RemotingEncoder.CreateEmptyPSObject(); EncodeAndAddReturnValue(data, _returnValue); EncodeAndAddException(data, _exception); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.CallId, _callId)); data.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MethodId, _methodId)); return data; } /// <summary> /// Decode. /// </summary> internal static RemoteHostResponse Decode(PSObject data) { Dbg.Assert(data != null, "Expected data != null"); // Extract all the fields from data. long callId = RemotingDecoder.GetPropertyValue<long>(data, RemoteDataNameStrings.CallId); RemoteHostMethodId methodId = RemotingDecoder.GetPropertyValue<RemoteHostMethodId>(data, RemoteDataNameStrings.MethodId); // Decode the return value and the exception. RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); object returnValue = DecodeReturnValue(data, methodInfo.ReturnType); Exception exception = DecodeException(data); // Use these values to create a RemoteHostResponse and return it. return new RemoteHostResponse(callId, methodId, returnValue, exception); } } /// <summary> /// The RemoteHostExceptions class. /// </summary> internal static class RemoteHostExceptions { /// <summary> /// New remote runspace does not support push runspace exception. /// </summary> internal static Exception NewRemoteRunspaceDoesNotSupportPushRunspaceException() { string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteRunspaceDoesNotSupportPushRunspace); return new PSRemotingDataStructureException(resourceString); } /// <summary> /// New decoding failed exception. /// </summary> internal static Exception NewDecodingFailedException() { string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostDecodingFailed); return new PSRemotingDataStructureException(resourceString); } /// <summary> /// New not implemented exception. /// </summary> internal static Exception NewNotImplementedException(RemoteHostMethodId methodId) { RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostMethodNotImplemented, methodInfo.Name); return new PSRemotingDataStructureException(resourceString, new PSNotImplementedException()); } /// <summary> /// New remote host call failed exception. /// </summary> internal static Exception NewRemoteHostCallFailedException(RemoteHostMethodId methodId) { RemoteHostMethodInfo methodInfo = RemoteHostMethodInfo.LookUp(methodId); string resourceString = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.RemoteHostCallFailed, methodInfo.Name); return new PSRemotingDataStructureException(resourceString); } /// <summary> /// New decoding error for error record exception. /// </summary> internal static Exception NewDecodingErrorForErrorRecordException() { return new PSRemotingDataStructureException(RemotingErrorIdStrings.DecodingErrorForErrorRecord); } /// <summary> /// New remote host data encoding not supported exception. /// </summary> internal static Exception NewRemoteHostDataEncodingNotSupportedException(Type type) { Dbg.Assert(type != null, "Expected type != null"); return new PSRemotingDataStructureException( RemotingErrorIdStrings.RemoteHostDataEncodingNotSupported, type.ToString()); } /// <summary> /// New remote host data decoding not supported exception. /// </summary> internal static Exception NewRemoteHostDataDecodingNotSupportedException(Type type) { Dbg.Assert(type != null, "Expected type != null"); return new PSRemotingDataStructureException( RemotingErrorIdStrings.RemoteHostDataDecodingNotSupported, type.ToString()); } /// <summary> /// New unknown target class exception. /// </summary> internal static Exception NewUnknownTargetClassException(string className) { Dbg.Assert(className != null, "Expected className != null"); return new PSRemotingDataStructureException(RemotingErrorIdStrings.UnknownTargetClass, className); } internal static Exception NewNullClientHostException() { return new PSRemotingDataStructureException(RemotingErrorIdStrings.RemoteHostNullClientHost); } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using IdentityServervNextDemo.EntityFrameworkCore; namespace IdentityServervNextDemo.Migrations { [DbContext(typeof(IdentityServervNextDemoDbContext))] [Migration("20170621153937_Added_Description_And_IsActive_To_Role")] partial class Added_Description_And_IsActive_To_Role { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(450)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("ClaimType") .HasColumnType("nvarchar(450)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(255)") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(10)") .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastLoginTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("IdentityServervNextDemo.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId") .HasColumnType("int"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("IdentityServervNextDemo.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Roles.Role", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("IdentityServervNextDemo.Authorization.Users.User", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("IdentityServervNextDemo.MultiTenancy.Tenant", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("IdentityServervNextDemo.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("IdentityServervNextDemo.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("IdentityServervNextDemo.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
using System; using System.Threading; using Content.Shared.Alert; using Content.Shared.GameObjects.Components.Movement; using Content.Shared.GameObjects.EntitySystems; using Content.Shared.Interfaces.GameObjects.Components; using Robust.Shared.GameObjects; using Robust.Shared.GameObjects.Components.Timers; using Robust.Shared.Interfaces.Timing; using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; using Timer = Robust.Shared.Timers.Timer; namespace Content.Shared.GameObjects.Components.Mobs { public abstract class SharedStunnableComponent : Component, IMoveSpeedModifier, IActionBlocker, IInteractHand { [Dependency] private readonly IGameTiming _gameTiming = default!; public sealed override string Name => "Stunnable"; public override uint? NetID => ContentNetIDs.STUNNABLE; protected TimeSpan? LastStun; [ViewVariables] protected TimeSpan? StunStart => LastStun; [ViewVariables] protected TimeSpan? StunEnd => LastStun == null ? (TimeSpan?) null : _gameTiming.CurTime + (TimeSpan.FromSeconds(Math.Max(StunnedTimer, Math.Max(KnockdownTimer, SlowdownTimer)))); private bool _canHelp = true; protected float _stunCap = 20f; protected float _knockdownCap = 20f; protected float _slowdownCap = 20f; private float _helpKnockdownRemove = 1f; private float _helpInterval = 1f; protected float StunnedTimer; protected float KnockdownTimer; protected float SlowdownTimer; private string _stunAlertId; protected CancellationTokenSource StatusRemoveCancellation = new CancellationTokenSource(); [ViewVariables] protected float WalkModifierOverride = 0f; [ViewVariables] protected float RunModifierOverride = 0f; [ViewVariables] public bool Stunned => StunnedTimer > 0f; [ViewVariables] public bool KnockedDown => KnockdownTimer > 0f; [ViewVariables] public bool SlowedDown => SlowdownTimer > 0f; private float StunTimeModifier { get { var modifier = 1.0f; var components = Owner.GetAllComponents<IStunModifier>(); foreach (var component in components) { modifier *= component.StunTimeModifier; } return modifier; } } private float KnockdownTimeModifier { get { var modifier = 1.0f; var components = Owner.GetAllComponents<IStunModifier>(); foreach (var component in components) { modifier *= component.KnockdownTimeModifier; } return modifier; } } private float SlowdownTimeModifier { get { var modifier = 1.0f; var components = Owner.GetAllComponents<IStunModifier>(); foreach (var component in components) { modifier *= component.SlowdownTimeModifier; } return modifier; } } /// <summary> /// Stuns the entity, disallowing it from doing many interactions temporarily. /// </summary> /// <param name="seconds">How many seconds the mob will stay stunned.</param> /// <returns>Whether or not the owner was stunned.</returns> public bool Stun(float seconds) { seconds = MathF.Min(StunnedTimer + (seconds * StunTimeModifier), _stunCap); if (seconds <= 0f) { return false; } StunnedTimer = seconds; LastStun = _gameTiming.CurTime; SetAlert(); OnStun(); Dirty(); return true; } protected virtual void OnStun() { } /// <summary> /// Knocks down the mob, making it fall to the ground. /// </summary> /// <param name="seconds">How many seconds the mob will stay on the ground.</param> /// <returns>Whether or not the owner was knocked down.</returns> public bool Knockdown(float seconds) { seconds = MathF.Min(KnockdownTimer + (seconds * KnockdownTimeModifier), _knockdownCap); if (seconds <= 0f) { return false; } KnockdownTimer = seconds; LastStun = _gameTiming.CurTime; SetAlert(); OnKnockdown(); Dirty(); return true; } protected virtual void OnKnockdown() { } /// <summary> /// Applies knockdown and stun to the mob temporarily. /// </summary> /// <param name="seconds">How many seconds the mob will be paralyzed-</param> /// <returns>Whether or not the owner of this component was paralyzed-</returns> public bool Paralyze(float seconds) { return Stun(seconds) && Knockdown(seconds); } /// <summary> /// Slows down the mob's walking/running speed temporarily /// </summary> /// <param name="seconds">How many seconds the mob will be slowed down</param> /// <param name="walkModifierOverride">Walk speed modifier. Set to 0 or negative for default value. (0.5f)</param> /// <param name="runModifierOverride">Run speed modifier. Set to 0 or negative for default value. (0.5f)</param> public void Slowdown(float seconds, float walkModifierOverride = 0f, float runModifierOverride = 0f) { seconds = MathF.Min(SlowdownTimer + (seconds * SlowdownTimeModifier), _slowdownCap); if (seconds <= 0f) return; WalkModifierOverride = walkModifierOverride; RunModifierOverride = runModifierOverride; SlowdownTimer = seconds; LastStun = _gameTiming.CurTime; if (Owner.TryGetComponent(out MovementSpeedModifierComponent movement)) movement.RefreshMovementSpeedModifiers(); SetAlert(); Dirty(); } private void SetAlert() { if (!Owner.TryGetComponent(out SharedAlertsComponent status)) { return; } status.ShowAlert(AlertType.Stun, cooldown: (StunStart == null || StunEnd == null) ? default : (StunStart.Value, StunEnd.Value)); StatusRemoveCancellation.Cancel(); StatusRemoveCancellation = new CancellationTokenSource(); } public override void ExposeData(ObjectSerializer serializer) { base.ExposeData(serializer); serializer.DataField(ref _stunCap, "stunCap", 20f); serializer.DataField(ref _knockdownCap, "knockdownCap", 20f); serializer.DataField(ref _slowdownCap, "slowdownCap", 20f); serializer.DataField(ref _helpInterval, "helpInterval", 1f); serializer.DataField(ref _helpKnockdownRemove, "helpKnockdownRemove", 1f); serializer.DataField(ref _stunAlertId, "stunAlertId", "stun"); } protected virtual void OnInteractHand() { } bool IInteractHand.InteractHand(InteractHandEventArgs eventArgs) { if (!_canHelp || !KnockedDown) { return false; } _canHelp = false; Owner.SpawnTimer((int) _helpInterval * 1000, () => _canHelp = true); KnockdownTimer -= _helpKnockdownRemove; SetAlert(); Dirty(); return true; } #region ActionBlockers public bool CanMove() => (!Stunned); public bool CanInteract() => (!Stunned); public bool CanUse() => (!Stunned); public bool CanThrow() => (!Stunned); public bool CanSpeak() => true; public bool CanDrop() => (!Stunned); public bool CanPickup() => (!Stunned); public bool CanEmote() => true; public bool CanAttack() => (!Stunned); public bool CanEquip() => (!Stunned); public bool CanUnequip() => (!Stunned); public bool CanChangeDirection() => true; public bool CanShiver() => !Stunned; public bool CanSweat() => true; #endregion [ViewVariables] public float WalkSpeedModifier => (SlowedDown ? (WalkModifierOverride <= 0f ? 0.5f : WalkModifierOverride) : 1f); [ViewVariables] public float SprintSpeedModifier => (SlowedDown ? (RunModifierOverride <= 0f ? 0.5f : RunModifierOverride) : 1f); [Serializable, NetSerializable] protected sealed class StunnableComponentState : ComponentState { public float StunnedTimer { get; } public float KnockdownTimer { get; } public float SlowdownTimer { get; } public float WalkModifierOverride { get; } public float RunModifierOverride { get; } public StunnableComponentState(float stunnedTimer, float knockdownTimer, float slowdownTimer, float walkModifierOverride, float runModifierOverride) : base(ContentNetIDs.STUNNABLE) { StunnedTimer = stunnedTimer; KnockdownTimer = knockdownTimer; SlowdownTimer = slowdownTimer; WalkModifierOverride = walkModifierOverride; RunModifierOverride = runModifierOverride; } } } /// <summary> /// This interface allows components to multiply the time in seconds of various stuns by a number. /// </summary> public interface IStunModifier { float StunTimeModifier => 1.0f; float KnockdownTimeModifier => 1.0f; float SlowdownTimeModifier => 1.0f; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.IO; using Franson.BlueTools; using Franson.Protocols.Obex; using Franson.Protocols.Obex.FTPClient; namespace ObexFTPClientSample { /// <summary> /// Summary description for MainForm. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.StatusBarPanel statusBarPanel; private System.Windows.Forms.StatusBarPanel stackPanel; private System.Windows.Forms.StatusBar statusBar; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog; internal System.Windows.Forms.ImageList toolbarImageList; internal System.Windows.Forms.ToolBar ToolBar; internal System.Windows.Forms.ToolBarButton discoverBtn; internal System.Windows.Forms.ToolBarButton disconnectBtn; internal System.Windows.Forms.ToolBarButton refreshBtn; internal System.Windows.Forms.ToolBarButton createDirBtn; internal System.Windows.Forms.ToolBarButton delBtn; internal System.Windows.Forms.ToolBarButton putBtn; internal System.Windows.Forms.ToolBarButton getBtn; internal System.Windows.Forms.ToolBarButton abortBtn; private System.Windows.Forms.TreeView folderTree; private System.Windows.Forms.Splitter splitter; private System.ComponentModel.IContainer components; public MainForm() { // // Required for Windows Form Designer support // InitializeComponent(); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException); try { m_manager = Manager.GetManager(); // show which stack application is using switch (Manager.StackID) { case StackID.STACK_MICROSOFT: { stackPanel.Text = "Microsoft Bluetooth Stack"; break; } case StackID.STACK_WIDCOMM: { stackPanel.Text = "WidComm Bluetooth Stack"; break; } } // marshal events in this class thread m_manager.Parent = this; // get your trial license from franson.com or buy BlueTools Franson.BlueTools.License license = new Franson.BlueTools.License(); license.LicenseKey = "WoK6IL85CADCPOOQWXYZPixRDRkuKYIYWsLF"; // Get first network (BlueTools 1.0 only supports one network == one dongle) m_network = m_manager.Networks[0]; // Add events for device discovery m_network.DeviceDiscoveryStarted += new BlueToolsEventHandler(network_DeviceDiscoveryStarted); m_network.DeviceDiscoveryCompleted += new BlueToolsEventHandler(network_DeviceDiscoveryCompleted); // load address book m_addressbook = new AddressBook(); m_addressbook.Load(); // create FileBrowser object fb = new FileBrowser(); // marshal events to this class thread. // this is necessary if you for example (like this sample does) want to display the progress // of a copy operation with a progress bar. without this marshalling you will end up calling // the event method from an internal FileBrowser thread. This can cause a lot of problems // with synchronization and deadlocks. By passing this class thread to FileBrowser it will // invoke the events in this thread and thus not cause the problems stated above. // If you want to know more read up on Invoke and BeginInvoke. fb.Parent = this; // set event handlers for PutFile fb.PutFileBegin += new ObexEventHandler(fb_CopyBegin); fb.PutFileEnd += new ObexEventHandler(fb_CopyEnd); fb.PutFileProgress += new ObexEventHandler(fb_CopyProgress); fb.GetPathEnd += new ObexEventHandler(fb_GetPathEnd); fb.SetPathEnd += new ObexEventHandler(fb_SetPathEnd); // set event handlers for GetFile // note that they are set the same as PutFile. // They look pretty much the same and should display pretty much the same // so we re-use them! fb.GetFileBegin += new ObexEventHandler(fb_CopyBegin); fb.GetFileEnd += new ObexEventHandler(fb_CopyEnd); fb.GetFileProgress += new ObexEventHandler(fb_CopyProgress); fb.CreateDirectoryEnd += new ObexEventHandler(fb_CreateDirectoryEnd); // set event handler for possible errors // asynchronous errors can't be trapped with try..catch // they are forwarded to this function instead fb.Error += new ObexEventHandler(fb_Error); // set event handler to be notified when ConnectAsync has finished fb.ConnectEnd += new ObexEventHandler(fb_ConnectEnd); ListDevices(); } catch (Exception exc) { MessageBox.Show(exc.Message); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { // must dispose manager, else application can't exit if (m_manager != null) { m_manager.Dispose(); } if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MainForm)); this.statusBar = new System.Windows.Forms.StatusBar(); this.statusBarPanel = new System.Windows.Forms.StatusBarPanel(); this.stackPanel = new System.Windows.Forms.StatusBarPanel(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.toolbarImageList = new System.Windows.Forms.ImageList(this.components); this.ToolBar = new System.Windows.Forms.ToolBar(); this.discoverBtn = new System.Windows.Forms.ToolBarButton(); this.disconnectBtn = new System.Windows.Forms.ToolBarButton(); this.refreshBtn = new System.Windows.Forms.ToolBarButton(); this.createDirBtn = new System.Windows.Forms.ToolBarButton(); this.delBtn = new System.Windows.Forms.ToolBarButton(); this.putBtn = new System.Windows.Forms.ToolBarButton(); this.getBtn = new System.Windows.Forms.ToolBarButton(); this.abortBtn = new System.Windows.Forms.ToolBarButton(); this.folderTree = new System.Windows.Forms.TreeView(); this.treeImageList = new System.Windows.Forms.ImageList(this.components); this.splitter = new System.Windows.Forms.Splitter(); this.fileListView = new System.Windows.Forms.ListView(); this.NameColumn = new System.Windows.Forms.ColumnHeader(); this.SizeColumn = new System.Windows.Forms.ColumnHeader(); this.ModificationColumn = new System.Windows.Forms.ColumnHeader(); ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.stackPanel)).BeginInit(); this.SuspendLayout(); // // statusBar // this.statusBar.Location = new System.Drawing.Point(0, 367); this.statusBar.Name = "statusBar"; this.statusBar.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] { this.statusBarPanel, this.stackPanel}); this.statusBar.ShowPanels = true; this.statusBar.Size = new System.Drawing.Size(656, 22); this.statusBar.TabIndex = 0; this.statusBar.Text = "statusBar1"; // // statusBarPanel // this.statusBarPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring; this.statusBarPanel.Width = 630; // // stackPanel // this.stackPanel.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents; this.stackPanel.Width = 10; // // progressBar // this.progressBar.Dock = System.Windows.Forms.DockStyle.Bottom; this.progressBar.Location = new System.Drawing.Point(0, 359); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(656, 8); this.progressBar.TabIndex = 1; this.progressBar.Visible = false; // // toolbarImageList // this.toolbarImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; this.toolbarImageList.ImageSize = new System.Drawing.Size(32, 32); this.toolbarImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("toolbarImageList.ImageStream"))); this.toolbarImageList.TransparentColor = System.Drawing.Color.Transparent; // // ToolBar // this.ToolBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.ToolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.discoverBtn, this.disconnectBtn, this.refreshBtn, this.createDirBtn, this.delBtn, this.putBtn, this.getBtn, this.abortBtn}); this.ToolBar.DropDownArrows = true; this.ToolBar.ImageList = this.toolbarImageList; this.ToolBar.Location = new System.Drawing.Point(0, 0); this.ToolBar.Name = "ToolBar"; this.ToolBar.ShowToolTips = true; this.ToolBar.Size = new System.Drawing.Size(656, 44); this.ToolBar.TabIndex = 5; this.ToolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar_ButtonClick); // // discoverBtn // this.discoverBtn.ImageIndex = 0; this.discoverBtn.ToolTipText = "Scan for nearby Bluetooth Devices."; // // disconnectBtn // this.disconnectBtn.Enabled = false; this.disconnectBtn.ImageIndex = 1; this.disconnectBtn.ToolTipText = "Disconnect from Obex server."; // // refreshBtn // this.refreshBtn.Enabled = false; this.refreshBtn.ImageIndex = 5; this.refreshBtn.ToolTipText = "Refresh."; // // createDirBtn // this.createDirBtn.Enabled = false; this.createDirBtn.ImageIndex = 6; this.createDirBtn.ToolTipText = "Create a new directory..."; // // delBtn // this.delBtn.Enabled = false; this.delBtn.ImageIndex = 4; this.delBtn.ToolTipText = "Delete selected folder or file."; // // putBtn // this.putBtn.Enabled = false; this.putBtn.ImageIndex = 7; this.putBtn.ToolTipText = "Upload selected file(s)."; // // getBtn // this.getBtn.Enabled = false; this.getBtn.ImageIndex = 3; this.getBtn.ToolTipText = "Download selected file(s)."; // // abortBtn // this.abortBtn.Enabled = false; this.abortBtn.ImageIndex = 2; this.abortBtn.ToolTipText = "Abort copy."; // // folderTree // this.folderTree.Dock = System.Windows.Forms.DockStyle.Left; this.folderTree.ImageList = this.treeImageList; this.folderTree.Location = new System.Drawing.Point(0, 44); this.folderTree.Name = "folderTree"; this.folderTree.Size = new System.Drawing.Size(152, 315); this.folderTree.TabIndex = 7; this.folderTree.DoubleClick += new System.EventHandler(this.folderTree_DoubleClick); this.folderTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.folderTree_AfterSelect); // // treeImageList // this.treeImageList.ImageSize = new System.Drawing.Size(16, 16); this.treeImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("treeImageList.ImageStream"))); this.treeImageList.TransparentColor = System.Drawing.Color.Transparent; // // splitter // this.splitter.Location = new System.Drawing.Point(152, 44); this.splitter.Name = "splitter"; this.splitter.Size = new System.Drawing.Size(3, 315); this.splitter.TabIndex = 8; this.splitter.TabStop = false; // // fileListView // this.fileListView.Activation = System.Windows.Forms.ItemActivation.OneClick; this.fileListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.NameColumn, this.SizeColumn, this.ModificationColumn}); this.fileListView.Dock = System.Windows.Forms.DockStyle.Fill; this.fileListView.FullRowSelect = true; this.fileListView.Location = new System.Drawing.Point(155, 44); this.fileListView.Name = "fileListView"; this.fileListView.Size = new System.Drawing.Size(501, 315); this.fileListView.SmallImageList = this.treeImageList; this.fileListView.TabIndex = 9; this.fileListView.View = System.Windows.Forms.View.Details; this.fileListView.ItemActivate += new System.EventHandler(this.fileListView_ItemActivate); this.fileListView.DoubleClick += new System.EventHandler(this.fileListView_DoubleClick); this.fileListView.MouseUp += new System.Windows.Forms.MouseEventHandler(this.fileListView_MouseUp); // // NameColumn // this.NameColumn.Text = "Name"; this.NameColumn.Width = 250; // // SizeColumn // this.SizeColumn.Text = "Size"; this.SizeColumn.Width = 80; // // ModificationColumn // this.ModificationColumn.Text = "Date modified"; this.ModificationColumn.Width = 120; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(656, 389); this.Controls.Add(this.fileListView); this.Controls.Add(this.splitter); this.Controls.Add(this.folderTree); this.Controls.Add(this.ToolBar); this.Controls.Add(this.progressBar); this.Controls.Add(this.statusBar); this.Name = "MainForm"; this.Text = "MainForm"; this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing); ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.stackPanel)).EndInit(); this.ResumeLayout(false); } #endregion // - User defined variables - // Application private AddressBook m_addressbook = null; private FileBrowser fb = null; // BlueTools private Manager m_manager = null; private Network m_network = null; private RemoteService m_serviceCurrent = null; private Stream m_streamCurrent = null; private RemoteDevice m_deviceCurrent = null; // stores how many unrecoverable error has occurred private int m_iUnrecoverableError = 0; // stores if the last transfer was denied private bool m_boolDenied = false; private System.Windows.Forms.ImageList treeImageList; private System.Windows.Forms.ColumnHeader NameColumn; private System.Windows.Forms.ColumnHeader SizeColumn; private System.Windows.Forms.ColumnHeader ModificationColumn; private System.Windows.Forms.ListView fileListView; // stores if the last transfer was aborted private bool m_boolAborted = false; [STAThread] static void Main() { Application.Run(new MainForm()); } private void network_DeviceDiscoveryStarted(object sender, BlueToolsEventArgs eventArgs) { // Search for devices on the network started statusBarPanel.Text = "Searching for bluetooth devices..."; // disable folderTree. You can't attempt to connect to anything now folderTree.Enabled = false; } private void network_DeviceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { // add all found devices to addressbook foreach (Device device in m_network.Devices) { // add device to AddressBook m_addressbook.Add(device.Address, device.Name); } discoverBtn.Enabled = true; // list all found and stored devices ListDevices(); // Search for devices on the network ended. statusBarPanel.Text = m_network.Devices.Length + " device(s) in your vicinity."; // re-enable the folder tree folderTree.Enabled = true; } private void device_ServiceDiscoveryCompleted(object sender, BlueToolsEventArgs eventArgs) { try { // reset error status - there has been no errors on this session m_iUnrecoverableError = 0; // if we have no streams or services already connected if (m_streamCurrent == null) { // Get the remote device that raised the event m_deviceCurrent = (RemoteDevice)sender; // You find an array of all found services here - the list is complete since this is ServiceDiscoverCompleted Service[] services = (Service[])((DiscoveryEventArgs)eventArgs).Discovery; // if services.Length is above 0 it means we found an Obex FTP service if (services.Length > 0) { // store current service m_serviceCurrent = (RemoteService)services[0]; // get the stream to the Obex FTP service m_streamCurrent = m_serviceCurrent.Stream; if (m_streamCurrent != null) { // attempt to connect asynchronously to Obex FTP server fb.ConnectAsync(m_streamCurrent); } } else { // enable discover button if we found no appropriate service discoverBtn.Enabled = true; // if this device did not support OBEX FTP display message in status bar statusBarPanel.Text = "No service for Obex FTP available on device."; // Update device list ListDevices(); } } // remove event handlers m_deviceCurrent.ServiceDiscoveryCompleted -= new BlueToolsEventHandler(device_ServiceDiscoveryCompleted); m_deviceCurrent.Error -= new Franson.BlueTools.BlueToolsEventHandler(device_Error); } catch (Exception exc) { m_serviceCurrent = null; m_streamCurrent = null; m_deviceCurrent = null; // display error message in window statusBarPanel.Text = exc.Message; // go back to showing devices ListDevices(); } } private void device_Error(object sender, BlueToolsEventArgs eventArgs) { Franson.BlueTools.ErrorEventArgs errorEventArgs = (Franson.BlueTools.ErrorEventArgs)eventArgs; MessageBox.Show(errorEventArgs.ErrorCode + ": " + errorEventArgs.Message); } private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (fb != null && fb.Connected) { fb.DisconnectEnd -= new ObexEventHandler(fb_DisconnectEnd); fb.DisconnectEnd += new ObexEventHandler(fb_ApplicationExit); fb.DisconnectAsync(); e.Cancel = true; // don't continue to execute this method return; } if (m_addressbook != null) { m_addressbook.Close(); } // cancel any pending device discovery operations if (m_network != null) { m_network.CancelDeviceDiscovery(); } Dispose(); } /// <summary> /// Method called when we were connected and now we isn't /// </summary> /// <param name="source"></param> /// <param name="args"></param> void fb_ApplicationExit(Object source, ObexEventArgs args) { m_addressbook.Close(); // cancel any pending device discovery operations if (m_network != null) { m_network.CancelDeviceDiscovery(); } Dispose(); // won't call MainForm_closing so it's no danger of dead-lock Application.Exit(); } void fb_CopyBegin(Object source, ObexEventArgs args) { // this transfer hasn't been denied (yet!) m_boolDenied = false; // this transfer hasn't been aborted (yet!) m_boolAborted = false; progressBar.Visible = true; ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)args; // must see if Size is -1, that means it is unknown progressBar.Maximum = (copyArgs.Size != -1)?(int)copyArgs.Size:0; abortBtn.Enabled = true; refreshBtn.Enabled = false; createDirBtn.Enabled = false; putBtn.Enabled = false; getBtn.Enabled = false; delBtn.Enabled = false; progressBar.Value = 0; } /// <summary> /// This method is called while a copy operation is commencing. It updates the statusbar to show the byte flow. /// </summary> /// <param name="source"></param> /// <param name="args"></param> private void fb_CopyProgress(Object source, ObexEventArgs args) { ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)args; // if size is unknown, ObexCopyEventArgs.Size will return -1 if (copyArgs.Size != -1) { if (copyArgs.Size != progressBar.Maximum) { progressBar.Maximum = (int)copyArgs.Size; } progressBar.Value = (int)copyArgs.Position; statusBarPanel.Text = Convert.ToString(copyArgs.Position) + "/" + Convert.ToString(copyArgs.Size); } else { // show user that we are copying but we don't know the full size statusBarPanel.Text = Convert.ToString(copyArgs.Position) + "/ ?"; } } /// <summary> /// This method is called when a copy operation is finished. /// </summary> /// <param name="source"></param> /// <param name="args"></param> void fb_CopyEnd(Object source, ObexEventArgs args) { ObexCopyEventArgs copyArgs = (ObexCopyEventArgs)args; // check if Stream is available before closing if (copyArgs.Stream != null) { copyArgs.Stream.Close(); } progressBar.Visible = false; // ...if sending was denied if (m_boolDenied) { statusBarPanel.Text = "File transfer denied by device."; } // ..if sending was aborted else if (m_boolAborted) { statusBarPanel.Text = "Copy was aborted."; } // ...else if there has been no unrecoverable errors else if (m_iUnrecoverableError == 0) { statusBarPanel.Text = "Copy complete."; } // .. or if there has been unrecoverable errors else { statusBarPanel.Text = "There was an error with the copy and the connection was lost."; } // Upload button should always be re-enabled (Download should only be re-enabled when a file is selected) putBtn.Enabled = true; delBtn.Enabled = true; // abort button should only be available while copying abortBtn.Enabled = false; // if this was a putfile operation, there is a new file on the remote device // if there was an unrecoverable error we can't access the device though... if ((args.Event == Franson.Protocols.Obex.EventType.PutFileEnd) && (m_iUnrecoverableError == 0)) { refreshBtn.Enabled = true; createDirBtn.Enabled = true; delBtn.Enabled = false; UpdateUI(); } } /// <summary> /// This methos is called when user is double-clicking the TreeView. /// If connected it changes the current folder on the remote device. /// If not connected, it connects you to the device you clicked on. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void folderTree_DoubleClick(object sender, System.EventArgs e) { TreeNode node = folderTree.SelectedNode; if (fb.Connected && m_iUnrecoverableError == 0) { // this checks if there is a folder selected.. if (node != null) { // check so it is a node that we have ourselves added (with a FileFolder attached) that is being double-clicked if (node.Tag != null) { FileFolder ff = (FileFolder)node.Tag; fb.SetPathAsync(ff.Name); } else { // All nods that do not have a FileFolder attached is treated as step-back fb.SetPathAsync(".."); } } } else { if (node != null) { // disable discover button discoverBtn.Enabled = false; // get stored device StoredDevice deviceStored = (StoredDevice)folderTree.SelectedNode.Tag; // empty treeview folderTree.Nodes.Clear(); // set new device m_deviceCurrent = (RemoteDevice)m_network.ConnectDevice(deviceStored.Address, deviceStored.Name); // try to connec to Obex FTP FindServiceAndConnect(); } } } /// <summary> /// This method updates the user interface. It calls GetPathAsync. /// </summary> private void UpdateUI() { // only call GetPath if there hasn't been an unrecoverable error if (m_iUnrecoverableError == 0) { fb.GetPathAsync(); } } /// <summary> /// This method is called when a user is clicking any of the toolbar buttons. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { // check which button was clicked and act appropriately... // discover button if (e.Button == discoverBtn) { // empty the addressbook so all names and such are updated m_addressbook.Clear(); // disable discover button discoverBtn.Enabled = false; // scan for devices m_network.DiscoverDevicesAsync(); } // delete button else if (e.Button == delBtn) { // if a foldertree is selected if (folderTree.SelectedNode != null && folderTree.SelectedNode.Tag != null) { FileFolder ff = (FileFolder)folderTree.SelectedNode.Tag; fb.DeleteAsync(ff.Name); UpdateUI(); } else if (fileListView.SelectedItems.Count > 0 && fileListView.SelectedItems[0].Tag != null) { FileFolder ff = (FileFolder)fileListView.SelectedItems[0].Tag; fb.DeleteAsync(ff.Name); UpdateUI(); } else { MessageBox.Show("No file or folder selected."); } } else if (e.Button == putBtn) { if (openFileDialog.ShowDialog() == DialogResult.OK) { foreach (string filename in openFileDialog.FileNames) { try { // open a stream to the file so we can read the data from it FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); // store the file! (only the filename, not the path) fb.PutFileAsync(fs, Path.GetFileName(filename)); } catch (Exception exc) { // show some error if we failed to open the FileStream MessageBox.Show(exc.Message); } } } } else if (e.Button == getBtn) { // if user wants to download files // check that there are selected files to download if (fileListView.SelectedItems.Count > 0) { // iterate all files foreach (ListViewItem lvItem in fileListView.SelectedItems) { // check that we have a FileFolder with info if (lvItem.Tag != null) { // get the FileFolder object FileFolder ff = (FileFolder)lvItem.Tag; // propose the same name saveFileDialog.FileName = ff.Name; // ask where to store the file if (saveFileDialog.ShowDialog() == DialogResult.OK) { // open a file stream to where the local store should be kept FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create); // ask Obex to download it! fb.GetFileAsync(fs, ff.Name); } } } } } else if (e.Button == abortBtn) { fb.Abort(); } else if (e.Button == refreshBtn) { UpdateUI(); refreshBtn.Enabled = false; } else if (e.Button == disconnectBtn) { fb.DisconnectAsync(); } else if (e.Button == createDirBtn) { InputForm input = new InputForm(); if (input.ShowDialog(this) == DialogResult.OK) { fb.CreateDirectoryAsync(input.FolderName); } } } /// <summary> /// Takes the current device and attempts to find the Obex FTP Service /// </summary> private void FindServiceAndConnect() { if (m_deviceCurrent != null) { try { // Add a DiscoveryListener so we get service discovery events m_deviceCurrent.ServiceDiscoveryCompleted += new BlueToolsEventHandler(device_ServiceDiscoveryCompleted); m_deviceCurrent.Error += new Franson.BlueTools.BlueToolsEventHandler(device_Error); // Cancel any on-going device discovery (not that there should be any going on) m_network.CancelDeviceDiscovery(); // only find OBEX FTP Services - this is done in UI-thread so let's do it asynchronously m_deviceCurrent.DiscoverServicesAsync(ServiceType.OBEXFileTransfer); statusBarPanel.Text = "Trying to connect..."; } catch (Exception exc) { // enable discover button if something happened discoverBtn.Enabled = true; MessageBox.Show(exc.Message); } } } /// <summary> /// This method is called when GetPathAsync is finished. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void fb_GetPathEnd(object sender, ObexEventArgs e) { if (m_iUnrecoverableError == 0) { // when get path finished - clear controls folderTree.Nodes.Clear(); fileListView.Items.Clear(); // step through entire cache for (int i = 0; i < fb.Items.Count; i++) { // get FileFolder object at current index position FileFolder ff = fb.Items[i]; // declare variables for nodes TreeNode TreeNode = null; ListViewItem ListNode = null; // if FileFolder is a folder if (ff.IsFolder) { // create a TreeView node TreeNode = new TreeNode(ff.Name, 0, 0); // store the FileFolder object if we want to access some of its properties in the UI TreeNode.Tag = ff; // add the object to the treeview folderTree.Nodes.Add(TreeNode); } else { // if FileFolder is not a folder it is by definition a file... // create a ListView item ListNode = new ListViewItem(ff.Name, 1); // add size and modification date to sub-columns (we could add other properties here too - like last access etc.) // if size is unknown it will return -1, and if modification date is unknown it will return DateTime.MinValue ListNode.SubItems.Add((ff.FileSize > 0)?(ff.FileSize > 1024)?Convert.ToString(ff.FileSize / 1024) + " kb":"1 kb":"0 kb"); ListNode.SubItems.Add((ff.FileModified != DateTime.MinValue)?ff.FileModified.ToString():"n/a"); // store the FileFolder object if we want to access some of its properties in the UI ListNode.Tag = ff; // add the item to the listview instead fileListView.Items.Add(ListNode); } } // insert step back (..) folderTree.Nodes.Insert(0, new TreeNode("..", 0, 0)); // disable download & delete button getBtn.Enabled = false; delBtn.Enabled = false; // enable the refresh button refreshBtn.Enabled = true; } } /// <summary> /// This method is called when ConnectAsync is finished. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void fb_ConnectEnd(object sender, ObexEventArgs e) { // when connection is established // update UI to display any files and folders in the current directory // if there was a unrecoverable error there's no point in trying to talk to device though if (m_deviceCurrent != null && m_iUnrecoverableError == 0) { UpdateUI(); statusBarPanel.Text = "Connected to " + ((Device)m_deviceCurrent).Name; // enable buttons needed disconnectBtn.Enabled = true; putBtn.Enabled = true; delBtn.Enabled = true; refreshBtn.Enabled = true; createDirBtn.Enabled = true; fb.DisconnectEnd += new ObexEventHandler(fb_DisconnectEnd); } else { statusBarPanel.Text = "Some error has occured."; ListDevices(); } } private void currentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MessageBox.Show("Unhandled exception. If you think this is due to the Franson.Protocols.Obex component " + "please report it, along with information on how to reproduce it."); } private void fb_Error(object sender, ObexEventArgs eventArgs) { ObexErrorEventArgs errorArgs = (ObexErrorEventArgs)eventArgs; switch (errorArgs.Error) { case Franson.Protocols.Obex.ErrorCode.StreamError: { // count one more unrecoverable error m_iUnrecoverableError++; // if there was an error we should clear this stream, it's not valid anymore if (m_streamCurrent != null) { m_streamCurrent.Close(); } break; } case Franson.Protocols.Obex.ErrorCode.Forbidden: { MessageBox.Show(errorArgs.Message); break; } case Franson.Protocols.Obex.ErrorCode.NoConnection: { m_iUnrecoverableError++; MessageBox.Show("Could not establish a connection or the connection has been lost to the Obex device."); break; } case Franson.Protocols.Obex.ErrorCode.NotFound: { MessageBox.Show("File or folder not found."); break; } case Franson.Protocols.Obex.ErrorCode.SendDenied: { // this transfer was denied! m_boolDenied = true; break; } case Franson.Protocols.Obex.ErrorCode.Aborted: { m_boolAborted = true; break; } // this requires a disconnect, so we disconnect and connect again case Franson.Protocols.Obex.ErrorCode.SecurityAbort: { m_boolAborted = true; // this is done since SecurityAbort expects a disconnect // but this FTP client wants to stay connected, so we disconnect and connect again // if you want to do this really nice, you'll keep track of the path too, and restore it // as well. this solution does put us back to root folder (the inbox) fb.DisconnectEnd -= new ObexEventHandler(fb_DisconnectEnd); fb.DisconnectAsync(); fb.ConnectAsync(m_streamCurrent); break; } default: { MessageBox.Show(errorArgs.Message); break; } } // only need to inform user once if (m_iUnrecoverableError == 1) { MessageBox.Show(errorArgs.Message); // disable UI DisableUI(); // restore devices in the tree ListDevices(); m_serviceCurrent = null; m_streamCurrent = null; } } private void fileListView_DoubleClick(object sender, System.EventArgs e) { if (fileListView.Items.Count > 0) { ListViewItem lvi = fileListView.SelectedItems[0]; FileFolder ff = (FileFolder)lvi.Tag; if (ff != null) { saveFileDialog.FileName = ff.Name; if (saveFileDialog.ShowDialog() == DialogResult.OK) { FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write); fb.GetFileAsync(fs, ff.Name); } } } } private void fileListView_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);; foreach (string filename in filenames) { FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); fb.PutFileAsync(fs, Path.GetFileName(filename)); } } } private void fileListView_DragOver(object sender, System.Windows.Forms.DragEventArgs e) { e.Effect = DragDropEffects.Copy; } private void fb_SetPathEnd(object sender, ObexEventArgs e) { // called when setpath is finished UpdateUI(); } private void fb_CreateDirectoryEnd(object sender, ObexEventArgs e) { UpdateUI(); } /// <summary> /// This method is called when a disconnect has finished as a result of the user clicking on the Disconnect button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void fb_DisconnectEnd(object sender, ObexEventArgs e) { // disable user interface DisableUI(); // update status bar statusBarPanel.Text = "Disconnected."; // close stream if open try { if (m_serviceCurrent != null && m_streamCurrent != null) m_streamCurrent.Close(); } finally { m_serviceCurrent = null; m_streamCurrent = null; m_deviceCurrent = null; } ListDevices(); // enable discover button so we can connect again discoverBtn.Enabled = true; // remove this event handler - we'll re-add it on connect fb.DisconnectEnd -= new ObexEventHandler(fb_DisconnectEnd); } /// <summary> /// This method lists all devices found in addressbook /// </summary> private void ListDevices() { // empty tree folderTree.Nodes.Clear(); // add all found in address book foreach (StoredDevice deviceStored in m_addressbook.Devices) { // add nodes with device icon to treeview TreeNode deviceNode = new TreeNode(deviceStored.Name, 2, 2); deviceNode.Tag = deviceStored; folderTree.Nodes.Add(deviceNode); } } /// <summary> /// This method disables the UI when there is an error or user disconnects. /// </summary> private void DisableUI() { // disable buttons disconnectBtn.Enabled = false; putBtn.Enabled = false; getBtn.Enabled = false; delBtn.Enabled = false; refreshBtn.Enabled = false; createDirBtn.Enabled = false; abortBtn.Enabled = false; // clear controls since we can't access the contents anymore folderTree.Nodes.Clear(); fileListView.Items.Clear(); } private void fileListView_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { // enable download & delete button if any file is selected by keyboard getBtn.Enabled = fileListView.SelectedItems.Count > 0; delBtn.Enabled = fileListView.SelectedItems.Count > 0; } private void fileListView_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { // enable download & delete button if any file is selected by mouse getBtn.Enabled = fileListView.SelectedItems.Count > 0; delBtn.Enabled = fileListView.SelectedItems.Count > 0; } private void folderTree_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { if (fb != null && fb.Connected) { delBtn.Enabled = folderTree.SelectedNode != null && folderTree.SelectedNode.Tag != null; } } private void fileListView_ItemActivate(object sender, System.EventArgs e) { // enable download & delete button if files are selected getBtn.Enabled = fileListView.SelectedItems.Count > 0; delBtn.Enabled = fileListView.SelectedItems.Count > 0; } } }
using System; using System.Collections.Generic; namespace Behemoth.Util { using Point = Tuple2<int, int>; /// <summary> /// Utilities for operating on tile grids. /// </summary> public static class Tile { /// <summary> /// Call a function for each character in an ascii table with the char and /// coordinates of the character. /// </summary> public static void AsciiTableIter(Action<char, int, int> func, string[] lines) { for (int y = 0; y < lines.Length; y++) { for (int x = 0; x < lines[y].Length; x++) { func(lines[y][x], x, y); } } } /// <summary> /// Calculate the maximum dimensions of an ascii table. /// </summary> public static void AsciiTableDims( string[] lines, out int width, out int height) { height = lines.Length; if (lines.Length == 0) { width = 0; } else { width = lines[Alg.MinIndex(lines, str => -str.Length)].Length; } } /// <summary> /// Run a recursive shadowcasting line-of-sight algorithm. It is based on /// three delegates. All delegates use a coordinate system centered on LOS /// center, meaning that position (0, 0) is always where the LOS viewpoint /// is located. /// </summary> /// <param name="isBlockedPredicate"> /// Query whether a tile blocks LOS in a coordinate system centered on LOS center. /// </param> /// <param name="markSeenAction"> /// Called to mark a location as being visible. /// </param> /// <param name="outsideRadiusPredicate"> /// Query whether a point is outside LOS radius. Should work fine when it /// describes any convex shape that touches its axis-aligned bounding box /// at the axes (axis-aligned square, circle, axis-aligned diamond). With /// stranger shapes, the field of view will probably only form a part of /// the shape due to the way the algorithm works. /// </param> public static void LineOfSight( Func<int, int, bool> isBlockedPredicate, Action<int, int> markSeenAction, Func<int, int, bool> outsideRadiusPredicate) { markSeenAction(0, 0); for (int octant = 0; octant < 8; octant++) { ProcessOctant( isBlockedPredicate, markSeenAction, outsideRadiusPredicate, octant, 0.0, 1.0, 1); } } /// <summary> /// Recursive raycasting line-of-sight worker function. Uses three /// delegates to interface with the actual map. The parameters startSlope /// and endSlope specify the sector to iterate. The parameter u is the /// distance from origin along the major axis of the octant. /// </summary> static void ProcessOctant( Func<int, int, bool> isBlockedPredicate, Action<int, int> markSeenAction, Func<int, int, bool> outsideRadiusPredicate, int octant, double startSlope, double endSlope, int u) { if (outsideRadiusPredicate(u, 0)) { return; } if (endSlope <= startSlope) { return; } bool traversingObstacle = true; for (int v = (int)Math.Round(u * startSlope), ev = (int)Math.Ceiling(u * endSlope); v <= ev; ++v) { int mapX, mapY; switch (octant) { case 0: mapX = v; mapY = -u; break; case 1: mapX = u; mapY = -v; break; case 2: mapX = u; mapY = v; break; case 3: mapX = v; mapY = u; break; case 4: mapX = -v; mapY = u; break; case 5: mapX = -u; mapY = v; break; case 6: mapX = -u; mapY = -v; break; case 7: mapX = -v; mapY = -u; break; default: // Shouldn't happen mapX = mapY = 0; break; } if (isBlockedPredicate(mapX, mapY)) { if (!traversingObstacle) { // Hit an obstacle ProcessOctant( isBlockedPredicate, markSeenAction, outsideRadiusPredicate, octant, startSlope, ((double)v - 0.5) / ((double)u + 0.5), u + 1); traversingObstacle = true; } } else { if (traversingObstacle) { traversingObstacle = false; if (v > 0) { // Risen above an obstacle startSlope = Math.Max( startSlope, ((double)v - 0.5) / ((double)u - 0.5)); } } } // Not using u and v because the radius predicate might treat x and y // axes differently. if (startSlope < endSlope && !outsideRadiusPredicate(mapX, mapY)) { markSeenAction(mapX, mapY); } } if (!traversingObstacle) { ProcessOctant( isBlockedPredicate, markSeenAction, outsideRadiusPredicate, octant, startSlope, endSlope, u + 1); } } public static double EuclideanDist(Point p1, Point p2) { var dx = p2.First - p1.First; var dy = p2.Second - p1.Second; return Math.Sqrt(dx * dx + dy * dy); } /// <summary> /// Find a path using A* and allowing 8-directional movement. /// </summary> public static IList<Point> FindPath8( Func<int, int, bool> isPassable, Point startPos, Point targetPos, int maxIterations) { return AStar.Search( startPos, targetPos, EuclideanDist, EuclideanDist, point => Neighbors8(isPassable, point.First, point.Second), maxIterations); } /// <summary> /// Find a path using A* and allowing 4-directional movement. /// </summary> public static IList<Point> FindPath4( Func<int, int, bool> isPassable, Point startPos, Point targetPos, int maxIterations) { return AStar.Search( startPos, targetPos, EuclideanDist, EuclideanDist, point => Neighbors4(isPassable, point.First, point.Second), maxIterations); } public static IEnumerable<Point> Neighbors8( Func<int, int, bool> isPassable, int cx, int cy) { for (int y = cy - 1; y <= cy + 1; y++) { for (int x = cx - 1; x <= cx + 1; x++) { if (x == cx && y == cy) { continue; } if (isPassable(x, y)) { yield return new Point(x, y); } } } } public static IEnumerable<Point> Neighbors4( Func<int, int, bool> isPassable, int cx, int cy) { if (isPassable(cx, cy - 1)) yield return new Point(cx, cy - 1); if (isPassable(cx + 1, cy)) yield return new Point(cx + 1, cy); if (isPassable(cx, cy + 1)) yield return new Point(cx, cy + 1); if (isPassable(cx - 1, cy)) yield return new Point(cx - 1, cy); } } }
//----------------------------------------------------------------------- // <copyright company="Nuclei"> // Copyright 2013 Nuclei. Licensed under the Apache License, Version 2.0. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; namespace Sherlock.Service.Nuclei.ExceptionHandling { /// <summary> /// This class provides some utilities for working with exceptions and exception filters. /// </summary> /// <remarks> /// <para> /// Code inside of exception filters runs before the stack has been logically unwound, and so the throw point /// is still visible in tools like debuggers, and back out code from finally blocks has not yet been run. /// See http://blogs.msdn.com/rmbyers/archive/2008/12/22/getting-good-dumps-when-an-exception-is-thrown.aspx. /// Filters can also be used to provide more fine-grained control over which exceptions are caught. /// </para> /// <para> /// Be aware, however, that filters run at a surprising time - after an exception has occurred but before /// any finally clause has been run to restore broken invariants for things lexically in scope. This can lead to /// confusion if you access or manipulate program state from your filter. See this blog entry for details /// and more specific guidance: http://blogs.msdn.com/clrteam/archive/2009/08/25/the-good-and-the-bad-of-exception-filters.aspx. /// </para> /// <para> /// This class relies on Reflection.Emit to generate code which can use filters. If you are willing to add some /// complexity to your build process, a static technique (like writing in VB and use ILMerge, or rewriting with CCI) /// may be a better choice (e.g. more performant and easier to specialize). Again see /// http://blogs.msdn.com/rmbyers/archive/2008/12/22/getting-good-dumps-when-an-exception-is-thrown.aspx for details. /// </para> /// </remarks> /// <source> /// http://blogs.msdn.com/b/rmbyers/archive/2010/01/30/sample-reflection-emit-code-for-using-exception-filters-from-c.aspx /// </source> internal static class ExceptionFilter { private static Action<Action, Func<Exception, bool>, Action<Exception>> s_Filter = GenerateFilter(); /// <summary> /// Execute the body with the specified filter. /// </summary> /// <param name="body">The code to run inside the "try" block.</param> /// <param name="filter"> /// Called whenever an exception escapes body, passing the exception object. /// For exceptions that aren't derived from System.Exception, they'll show up as an instance of /// RuntimeWrappedException. /// </param> /// <param name="handler"> /// Invoked (with the exception) whenever the filter returns true, causes the exception to be swallowed. /// </param> public static void ExecuteWithFilter(Action body, Func<Exception, bool> filter, Action<Exception> handler) { s_Filter(body, filter, handler); } /// <summary> /// Execute the body with the specified filter with no handler ever being invoked. /// </summary> /// <param name="body">The code to run inside the "try" block.</param> /// <param name="filter"> /// Called whenever an exception escapes body, passing the exception object. /// For exceptions that aren't derived from System.Exception, they'll show up as /// an instance of RuntimeWrappedException. /// </param> /// <remarks> /// Note that this allocates a delegate and closure class, a small amount of overhead but something that may not be appropriate /// for inside of a tight inner loop. If you want to call this on a very hot path, you may want to consider a direct call /// rather than using an anonymous method. /// </remarks> public static void ExecuteWithFilter(Action body, Action<Exception> filter) { ExecuteWithFilter(body, (e) => { filter(e); return false; }, null); } /// <summary> /// Execute the body which is not expected to ever throw any exceptions. /// If an exception does escape body, stop in the debugger if one is attached and then fail-fast. /// </summary> /// <param name="body">The code to run inside the "try" block.</param> public static void ExecuteWithFailfast(Action body) { ExecuteWithFilter( body, (e) => { Debugger.Log(10, "ExceptionFilter", "Saw unexpected exception: " + e.ToString()); // Terminate the process with this fatal error Environment.FailFast("Unexpected Exception", e); return false; // should never be reached }, null); } /// <summary> /// Like a normal C# Try/Catch but allows one catch block to catch multiple different types of exceptions. /// </summary> /// <typeparam name="TExceptionBase">The common base exception type to catch.</typeparam> /// <param name="body">Code to execute inside the try.</param> /// <param name="typesToCatch"> /// All exception types to catch (each of which must be derived from or exactly TExceptionBase). /// </param> /// <param name="handler"> /// The catch block to execute when one of the specified exceptions is caught. /// </param> public static void TryCatchMultiple<TExceptionBase>(Action body, Type[] typesToCatch, Action<TExceptionBase> handler) where TExceptionBase : Exception { // Verify that every type in typesToCatch is a sub-type of TExceptionBase #if DEBUG foreach (var tc in typesToCatch) { Debug.Assert( typeof(TExceptionBase).IsAssignableFrom(tc), string.Format( CultureInfo.InvariantCulture, "Error: {0} is not a sub-class of {1}", tc.FullName, typeof(TExceptionBase).FullName)); } #endif ExecuteWithFilter( body, (e) => { // If the thrown exception is a sub-type (including the same time) of at least one of the provided types then // catch it. foreach (var catchType in typesToCatch) { if (catchType.IsAssignableFrom(e.GetType())) { return true; } } return false; }, (e) => { handler((TExceptionBase)e); }); } /// <summary> /// A convenience method for when only the base type of 'Exception' is needed. /// </summary> /// <param name="body">Code to execute inside the try.</param> /// <param name="typesToCatch"> /// All exception types to catch (each of which must be derived from or exactly TExceptionBase). /// </param> /// <param name="handler"> /// The catch block to execute when one of the specified exceptions is caught. /// </param> public static void TryCatchMultiple(Action body, Type[] typesToCatch, Action<Exception> handler) { TryCatchMultiple<Exception>(body, typesToCatch, handler); } /// <summary> /// Generate a function which has an EH filter. /// </summary> /// <returns>The delegate that holds the EH filter.</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "exLoc", Justification = "If we remove this statement then we're generating illegal IL and the application crashes on startup.")] private static Action<Action, Func<Exception, bool>, Action<Exception>> GenerateFilter() { // Create a dynamic assembly with reflection emit var name = new AssemblyName("DynamicFilter"); #if (DEBUG) AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave); var module = assembly.DefineDynamicModule("DynamicFilter", "DynamicFilter.dll"); #else AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); var module = assembly.DefineDynamicModule("DynamicFilter"); #endif // Add an assembly attribute that tells the CLR to wrap non-CLS-compliant exceptions in a RuntimeWrappedException object // (so the cast to Exception in the code will always succeed). C# and VB always do this, C++/CLI doesn't. assembly.SetCustomAttribute( new CustomAttributeBuilder( typeof(RuntimeCompatibilityAttribute).GetConstructor(new Type[] { }), new object[] { }, new PropertyInfo[] { typeof(RuntimeCompatibilityAttribute).GetProperty("WrapNonExceptionThrows") }, new object[] { true })); // Add an assembly attribute that tells the CLR not to attempt to load PDBs when compiling this assembly assembly.SetCustomAttribute( new CustomAttributeBuilder( typeof(DebuggableAttribute).GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) }), new object[] { DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints })); // Create the type and method which will contain the filter TypeBuilder type = module.DefineType("Filter", TypeAttributes.Class | TypeAttributes.Public); var argTypes = new Type[] { typeof(Action), typeof(Func<Exception, bool>), typeof(Action<Exception>) }; MethodBuilder meth = type.DefineMethod("InvokeWithFilter", MethodAttributes.Public | MethodAttributes.Static, typeof(void), argTypes); var il = meth.GetILGenerator(); // This variable shouldn't be necessary (it's never used) // but for some reason the compiler generates illegal IL if this // variable isn't there ... var exLoc = il.DeclareLocal(typeof(Exception)); // Invoke the body delegate inside the try il.BeginExceptionBlock(); il.Emit(OpCodes.Ldarg_0); il.EmitCall(OpCodes.Callvirt, typeof(Action).GetMethod("Invoke"), null); // Invoke the filter delegate inside the filter block il.BeginExceptFilterBlock(); il.Emit(OpCodes.Castclass, typeof(Exception)); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Ldloc_0); il.EmitCall(OpCodes.Callvirt, typeof(Func<Exception, bool>).GetMethod("Invoke"), null); // Invoke the handler delegate inside the catch block il.BeginCatchBlock(null); il.Emit(OpCodes.Castclass, typeof(Exception)); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldarg_2); il.Emit(OpCodes.Ldloc_0); il.EmitCall(OpCodes.Callvirt, typeof(Action<Exception>).GetMethod("Invoke"), null); il.EndExceptionBlock(); il.Emit(OpCodes.Ret); var bakedType = type.CreateType(); #if (DEBUG) assembly.Save("DynamicFilter.dll"); #endif // Construct a delegate to the filter function and return it var bakedMeth = bakedType.GetMethod("InvokeWithFilter"); var del = Delegate.CreateDelegate(typeof(Action<Action, Func<Exception, bool>, Action<Exception>>), bakedMeth); return (Action<Action, Func<Exception, bool>, Action<Exception>>)del; } } }
using System; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Newtonsoft.Json; using Orleans.Configuration; using Orleans.Providers.Azure; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace Orleans.Storage { /// <summary> /// Simple storage provider for writing grain state data to Azure blob storage in JSON format. /// </summary> public class AzureBlobGrainStorage : IGrainStorage, ILifecycleParticipant<ISiloLifecycle> { private JsonSerializerSettings jsonSettings; private CloudBlobContainer container; private ILogger logger; private readonly string name; private AzureBlobStorageOptions options; private SerializationManager serializationManager; private IGrainFactory grainFactory; private ITypeResolver typeResolver; private ILoggerFactory loggerFactory; /// <summary> Default constructor </summary> public AzureBlobGrainStorage( string name, AzureBlobStorageOptions options, SerializationManager serializationManager, IGrainFactory grainFactory, ITypeResolver typeResolver, ILoggerFactory loggerFactory) { this.name = name; this.options = options; this.serializationManager = serializationManager; this.grainFactory = grainFactory; this.typeResolver = typeResolver; this.loggerFactory = loggerFactory; this.logger = this.loggerFactory.CreateLogger($"{typeof(AzureTableGrainStorageFactory).FullName}.{name}"); } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ReadStateAsync"/> public async Task ReadStateAsync(string grainType, GrainReference grainId, IGrainState grainState) { var blobName = GetBlobName(grainType, grainId); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Reading, "Reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); try { var blob = container.GetBlockBlobReference(blobName); string json; try { json = await blob.DownloadTextAsync().ConfigureAwait(false); } catch (StorageException exception) when (exception.IsBlobNotFound()) { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobNotFound, "BlobNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); return; } catch (StorageException exception) when (exception.IsContainerNotFound()) { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "ContainerNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); return; } if (string.IsNullOrWhiteSpace(json)) { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobEmpty, "BlobEmpty reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); return; } grainState.State = JsonConvert.DeserializeObject(json, grainState.State.GetType(), jsonSettings); grainState.ETag = blob.Properties.ETag; if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Read: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); } catch (Exception ex) { logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ReadError, string.Format("Error reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message), ex); throw; } } private static string GetBlobName(string grainType, GrainReference grainId) { return string.Format("{0}-{1}.json", grainType, grainId.ToKeyString()); } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IGrainStorage.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainId, IGrainState grainState) { var blobName = GetBlobName(grainType, grainId); try { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Writing, "Writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); var json = JsonConvert.SerializeObject(grainState.State, jsonSettings); var blob = container.GetBlockBlobReference(blobName); blob.Properties.ContentType = "application/json"; await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, json, blob); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Written: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); } catch (Exception ex) { logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_WriteError, string.Format("Error writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message), ex); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ClearStateAsync"/> public async Task ClearStateAsync(string grainType, GrainReference grainId, IGrainState grainState) { var blobName = GetBlobName(grainType, grainId); try { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ClearingData, "Clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); var blob = container.GetBlockBlobReference(blobName); await DoOptimisticUpdate(() => blob.DeleteIfExistsAsync(DeleteSnapshotsOption.None, AccessCondition.GenerateIfMatchCondition(grainState.ETag), null, null), blob, grainState.ETag).ConfigureAwait(false); grainState.ETag = null; if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Cleared, "Cleared: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, blob.Properties.ETag, blobName, container.Name); } catch (Exception ex) { logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ClearError, string.Format("Error clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message), ex); throw; } } private async Task WriteStateAndCreateContainerIfNotExists(string grainType, GrainReference grainId, IGrainState grainState, string json, CloudBlockBlob blob) { try { await DoOptimisticUpdate(() => blob.UploadTextAsync(json, Encoding.UTF8, AccessCondition.GenerateIfMatchCondition(grainState.ETag), null, null), blob, grainState.ETag).ConfigureAwait(false); grainState.ETag = blob.Properties.ETag; } catch (StorageException exception) when (exception.IsContainerNotFound()) { // if the container does not exist, create it, and make another attempt if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "Creating container: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blob.Name, container.Name); await container.CreateIfNotExistsAsync().ConfigureAwait(false); await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, json, blob).ConfigureAwait(false); } } private static async Task DoOptimisticUpdate(Func<Task> updateOperation, CloudBlob blob, string currentETag) { try { await updateOperation.Invoke().ConfigureAwait(false); } catch (StorageException ex) when (ex.IsPreconditionFailed() || ex.IsConflict()) { throw new InconsistentStateException($"Blob storage condition not Satisfied. BlobName: {blob.Name}, Container: {blob.Container?.Name}, CurrentETag: {currentETag}", "Unknown", currentETag, ex); } } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<AzureBlobGrainStorage>(this.name), this.options.InitStage, Init); } /// <summary> Initialization function for this storage provider. </summary> private async Task Init(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); try { this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling); this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage initializing: {this.options.ToString()}"); this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableGrainStorage is using DataConnectionString: {0}", ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString)); this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling); var account = CloudStorageAccount.Parse(this.options.ConnectionString); var blobClient = account.CreateCloudBlobClient(); container = blobClient.GetContainerReference(this.options.ContainerName); await container.CreateIfNotExistsAsync().ConfigureAwait(false); stopWatch.Stop(); this.logger.LogInformation((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds."); } catch (Exception ex) { stopWatch.Stop(); this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex); throw; } } } public static class AzureBlobGrainStorageFactory { public static IGrainStorage Create(IServiceProvider services, string name) { IOptionsSnapshot<AzureBlobStorageOptions> optionsSnapshot = services.GetRequiredService<IOptionsSnapshot<AzureBlobStorageOptions>>(); return ActivatorUtilities.CreateInstance<AzureBlobGrainStorage>(services, name, optionsSnapshot.Get(name)); } } }
namespace AngleSharp.Dom { using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Useful methods for parent node objects. /// </summary> public static class ParentNodeExtensions { /// <summary> /// Runs the mutation macro as defined in 5.2.2 Mutation methods /// of http://www.w3.org/TR/domcore/. /// </summary> /// <param name="parent">The parent, which invokes the algorithm.</param> /// <param name="nodes">The nodes array to add.</param> /// <returns>A (single) node.</returns> internal static INode MutationMacro(this INode parent, INode[] nodes) { if (nodes.Length > 1) { var node = parent.Owner!.CreateDocumentFragment(); for (var i = 0; i < nodes.Length; i++) { node.AppendChild(nodes[i]); } return node; } return nodes[0]; } /// <summary> /// Prepends nodes to the parent node. /// </summary> /// <param name="parent">The parent, where to prepend to.</param> /// <param name="nodes">The nodes to prepend.</param> public static void PrependNodes(this INode parent, params INode[] nodes) { if (nodes.Length > 0) { var node = parent.MutationMacro(nodes); parent.PreInsert(node, parent.FirstChild); } } /// <summary> /// Appends nodes to parent node. /// </summary> /// <param name="parent">The parent, where to append to.</param> /// <param name="nodes">The nodes to append.</param> public static void AppendNodes(this INode parent, params INode[] nodes) { if (nodes.Length > 0) { var node = parent.MutationMacro(nodes); parent.PreInsert(node, null); } } /// <summary> /// Inserts nodes before the given child. /// </summary> /// <param name="child">The context object.</param> /// <param name="nodes">The nodes to insert before.</param> /// <returns>The current element.</returns> public static void InsertBefore(this INode child, params INode[] nodes) { var parent = child.Parent; if (parent != null && nodes.Length > 0) { var node = parent.MutationMacro(nodes); parent.PreInsert(node, child); } } /// <summary> /// Inserts nodes after the given child. /// </summary> /// <param name="child">The context object.</param> /// <param name="nodes">The nodes to insert after.</param> /// <returns>The current element.</returns> public static void InsertAfter(this INode child, params INode[] nodes) { var parent = child.Parent; if (parent != null && nodes.Length > 0) { var node = parent.MutationMacro(nodes); parent.PreInsert(node, child.NextSibling); } } /// <summary> /// Replaces the given child with the nodes. /// </summary> /// <param name="child">The context object.</param> /// <param name="nodes">The nodes to replace.</param> public static void ReplaceWith(this INode child, params INode[] nodes) { var parent = child.Parent; if (parent != null) { if (nodes.Length != 0) { var node = parent.MutationMacro(nodes); parent.ReplaceChild(node, child); } else { parent.RemoveChild(child); } } } /// <summary> /// Removes the child from its parent. /// </summary> /// <param name="child">The context object.</param> public static void RemoveFromParent(this INode child) { child.Parent?.PreRemove(child); } /// <summary> /// Inserts a node as the last child node of this element. /// </summary> /// <typeparam name="TElement">The type of element to add.</typeparam> /// <param name="parent">The parent of the node to add.</param> /// <param name="element">The element to be appended.</param> /// <returns>The appended element.</returns> public static TElement AppendElement<TElement>(this INode parent, TElement element) where TElement : class, IElement { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } return (TElement)parent.AppendChild(element); } /// <summary> /// Inserts the newElement immediately before the referenceElement. /// </summary> /// <typeparam name="TElement">The type of element to add.</typeparam> /// <param name="parent">The parent of the node to add.</param> /// <param name="newElement">The node to be inserted.</param> /// <param name="referenceElement"> /// The existing child element that will succeed the new element. /// </param> /// <returns>The inserted element.</returns> public static TElement InsertElement<TElement>(this INode parent, TElement newElement, INode referenceElement) where TElement : class, IElement { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } return (TElement)parent.InsertBefore(newElement, referenceElement); } /// <summary> /// Removes a child node from the current element, which must be a /// child of the current node. /// </summary> /// <typeparam name="TElement">The type of element.</typeparam> /// <param name="parent">The parent of the node to remove.</param> /// <param name="element">The element to be removed.</param> /// <returns>The removed element.</returns> public static TElement RemoveElement<TElement>(this INode parent, TElement element) where TElement : class, IElement { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } return (TElement)parent.RemoveChild(element); } /// <summary> /// Returns the first element matching the selectors with the provided /// type, or null. /// </summary> /// <typeparam name="TElement">The type to look for.</typeparam> /// <param name="parent">The parent of the nodes to gather.</param> /// <param name="selectors">The group of selectors to use.</param> /// <returns>The element, if there is any.</returns> public static TElement? QuerySelector<TElement>(this IParentNode parent, String selectors) where TElement : class, IElement { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } if (selectors is null) { throw new ArgumentNullException(nameof(selectors)); } return parent.QuerySelector(selectors) as TElement; } /// <summary> /// Returns a list of elements matching the selectors with the /// provided type. /// </summary> /// <typeparam name="TElement">The type to look for.</typeparam> /// <param name="parent">The parent of the nodes to gather.</param> /// <param name="selectors">The group of selectors to use.</param> /// <returns>An enumeration with the elements.</returns> public static IEnumerable<TElement> QuerySelectorAll<TElement>(this IParentNode parent, String selectors) where TElement : IElement { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } if (selectors is null) { throw new ArgumentNullException(nameof(selectors)); } return parent.QuerySelectorAll(selectors).OfType<TElement>(); } /// <summary> /// Gets the descendent nodes of the given parent. /// </summary> /// <typeparam name="TNode">The type of nodes to obtain.</typeparam> /// <param name="parent">The parent of the nodes to gather.</param> /// <returns>The descendent nodes.</returns> public static IEnumerable<TNode> Descendents<TNode>(this INode parent) { return parent.Descendents().OfType<TNode>(); } /// <summary> /// Gets the descendent nodes of the given parent. /// </summary> /// <param name="parent">The parent of the nodes to gather.</param> /// <returns>The descendent nodes.</returns> public static IEnumerable<INode> Descendents(this INode parent) { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } return parent.GetDescendants(); } /// <summary> /// Gets the descendent nodes including itself of the given parent. /// </summary> /// <typeparam name="TNode">The type of nodes to obtain.</typeparam> /// <param name="parent">The parent of the nodes to gather.</param> /// <returns>The descendent nodes including itself.</returns> public static IEnumerable<TNode> DescendentsAndSelf<TNode>(this INode parent) { return parent.DescendentsAndSelf().OfType<TNode>(); } /// <summary> /// Gets the descendent nodes including itself of the given parent. /// </summary> /// <param name="parent">The parent of the nodes to gather.</param> /// <returns>The descendent nodes including itself.</returns> public static IEnumerable<INode> DescendentsAndSelf(this INode parent) { if (parent is null) { throw new ArgumentNullException(nameof(parent)); } return parent.GetDescendantsAndSelf(); } /// <summary> /// Gets the ancestor nodes of the given child. /// </summary> /// <typeparam name="TNode">The type of nodes to obtain.</typeparam> /// <param name="child">The child of the nodes to gather.</param> /// <returns>The ancestor nodes.</returns> public static IEnumerable<TNode> Ancestors<TNode>(this INode child) { return child.Ancestors().OfType<TNode>(); } /// <summary> /// Gets the ancestor nodes of the given child. /// </summary> /// <param name="child">The child of the nodes to gather.</param> /// <returns>The ancestor nodes.</returns> public static IEnumerable<INode> Ancestors(this INode child) { if (child is null) { throw new ArgumentNullException(nameof(child)); } return child.GetAncestors(); } } }
// RuntimeInvokeManager.cs // // Author: // Lluis Sanchez Gual <lluis@novell.com> // // Copyright (c) 2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // using System; using System.Collections.Generic; using ST = System.Threading; using Mono.Debugging.Client; namespace Mono.Debugging.Evaluation { public class AsyncOperationManager: IDisposable { readonly List<AsyncOperation> operationsToCancel = new List<AsyncOperation> (); internal bool Disposing; public void Invoke (AsyncOperation methodCall, int timeout) { methodCall.Aborted = false; methodCall.Manager = this; lock (operationsToCancel) { operationsToCancel.Add (methodCall); methodCall.Invoke (); } if (timeout > 0) { if (!methodCall.WaitForCompleted (timeout)) { var wasAborted = methodCall.Aborted; methodCall.InternalAbort (); lock (operationsToCancel) { operationsToCancel.Remove (methodCall); ST.Monitor.PulseAll (operationsToCancel); } if (wasAborted) throw new EvaluatorAbortedException (); throw new TimeOutException (); } } else { methodCall.WaitForCompleted (System.Threading.Timeout.Infinite); } lock (operationsToCancel) { operationsToCancel.Remove (methodCall); ST.Monitor.PulseAll (operationsToCancel); if (methodCall.Aborted) { throw new EvaluatorAbortedException (); } } if (!string.IsNullOrEmpty (methodCall.ExceptionMessage)) { throw new Exception (methodCall.ExceptionMessage); } } public void Dispose () { Disposing = true; lock (operationsToCancel) { foreach (var op in operationsToCancel) { op.InternalShutdown (); } operationsToCancel.Clear (); } } public void AbortAll () { lock (operationsToCancel) { foreach (var op in operationsToCancel) op.InternalAbort (); } } public void EnterBusyState (AsyncOperation oper) { var args = new BusyStateEventArgs { IsBusy = true, Description = oper.Description, EvaluationContext = oper.EvaluationContext }; BusyStateChanged?.Invoke (this, args); } public void LeaveBusyState (AsyncOperation oper) { var args = new BusyStateEventArgs { IsBusy = false, Description = oper.Description, EvaluationContext = oper.EvaluationContext }; BusyStateChanged?.Invoke (this, args); } public event EventHandler<BusyStateEventArgs> BusyStateChanged; } public abstract class AsyncOperation { internal AsyncOperationManager Manager; internal bool Aborted; public bool Aborting { get; internal set; } public EvaluationContext EvaluationContext { get; private set; } protected AsyncOperation (EvaluationContext ctx) { EvaluationContext = ctx; } internal void InternalAbort () { ST.Monitor.Enter (this); if (Aborted) { ST.Monitor.Exit (this); return; } if (Aborting) { // Somebody else is aborting this. Just wait for it to finish. ST.Monitor.Exit (this); WaitForCompleted (ST.Timeout.Infinite); return; } Aborting = true; int abortState = 0; int abortRetryWait = 100; bool abortRequested = false; do { if (abortState > 0) ST.Monitor.Enter (this); try { if (!Aborted && !abortRequested) { // The Abort() call doesn't block. WaitForCompleted is used below to wait for the abort to succeed Abort (); abortRequested = true; } // Short wait for the Abort to finish. If this wait is not enough, it will wait again in the next loop if (WaitForCompleted (100)) { ST.Monitor.Exit (this); break; } } catch { // If abort fails, try again after a short wait } abortState++; if (abortState == 6) { // Several abort calls have failed. Inform the user that the debugger is busy abortRetryWait = 500; try { Manager.EnterBusyState (this); } catch (Exception ex) { Console.WriteLine (ex); } } ST.Monitor.Exit (this); } while (!Aborted && !WaitForCompleted (abortRetryWait) && !Manager.Disposing); if (Manager.Disposing) { InternalShutdown (); } else { lock (this) { Aborted = true; if (abortState >= 6) Manager.LeaveBusyState (this); } } } internal void InternalShutdown () { lock (this) { if (Aborted) return; try { Aborted = true; Shutdown (); } catch { // Ignore } } } /// <summary> /// Message of the exception, if the execution failed. /// </summary> public string ExceptionMessage { get; set; } /// <summary> /// Returns a short description of the operation, to be shown in the Debugger Busy Dialog /// when it blocks the execution of the debugger. /// </summary> public abstract string Description { get; } /// <summary> /// Called to invoke the operation. The execution must be asynchronous (it must return immediatelly). /// </summary> public abstract void Invoke ( ); /// <summary> /// Called to abort the execution of the operation. It has to throw an exception /// if the operation can't be aborted. This operation must not block. The engine /// will wait for the operation to be aborted by calling WaitForCompleted. /// </summary> public abstract void Abort (); /// <summary> /// Waits until the operation has been completed or aborted. /// </summary> public abstract bool WaitForCompleted (int timeout); /// <summary> /// Called when the debugging session has been disposed. /// I must cause any call to WaitForCompleted to exit, even if the operation /// has not been completed or can't be aborted. /// </summary> public abstract void Shutdown (); } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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. ************************************************************************************/ // #define SHOW_DK2_VARIABLES // #define USE_NEW_GUI // You can use the Unity new GUI if you have Unity 4.6 or above. using System; using System.Collections; using UnityEngine; #if USE_NEW_GUI using UnityEngine.UI; # endif //------------------------------------------------------------------------------------- // ***** OVRMainMenu // /// <summary> /// OVRMainMenu is used to control the loading of different scenes. It also renders out /// a menu that allows a user to modify various Rift settings, and allow for storing /// these settings for recall later. /// /// A user of this component can add as many scenes that they would like to be able to /// have access to. /// /// OVRMainMenu is currently attached to the OVRPlayerController prefab for convenience, /// but can safely removed from it and added to another GameObject that is used for general /// Unity logic. /// /// </summary> public class OVRMainMenu : MonoBehaviour { public float FadeInTime = 2.0f; public UnityEngine.Texture FadeInTexture = null; public Font FontReplace = null; public KeyCode MenuKey = KeyCode.Space; public KeyCode QuitKey = KeyCode.Escape; // Scenes to show onscreen public string [] SceneNames; public string [] Scenes; private bool ScenesVisible = false; // Spacing for scenes menu private int StartX = 490; private int StartY = 250; private int WidthX = 300; private int WidthY = 23; // Spacing for variables that users can change private int VRVarsSX = 553; private int VRVarsSY = 250; private int VRVarsWidthX = 175; private int VRVarsWidthY = 23; private int StepY = 25; // Handle to OVRCameraRig private OVRCameraRig CameraController = null; // Handle to OVRPlayerController private OVRPlayerController PlayerController = null; // Controller buttons private bool PrevStartDown; private bool PrevHatDown; private bool PrevHatUp; private bool ShowVRVars; private bool OldSpaceHit; // FPS private float UpdateInterval = 0.5f; private float Accum = 0; private int Frames = 0; private float TimeLeft = 0; private string strFPS = "FPS: 0"; // IPD shift from physical IPD public float IPDIncrement = 0.0025f; private string strIPD = "IPD: 0.000"; // Prediction (in ms) public float PredictionIncrement = 0.001f; // 1 ms private string strPrediction = "Pred: OFF"; // FOV Variables public float FOVIncrement = 0.2f; private string strFOV = "FOV: 0.0f"; // Height adjustment public float HeightIncrement = 0.01f; private string strHeight = "Height: 0.0f"; // Speed and rotation adjustment public float SpeedRotationIncrement = 0.05f; private string strSpeedRotationMultipler = "Spd. X: 0.0f Rot. X: 0.0f"; private bool LoadingLevel = false; private float AlphaFadeValue = 1.0f; private int CurrentLevel = 0; // Rift detection private bool HMDPresent = false; private float RiftPresentTimeout = 0.0f; private string strRiftPresent = ""; // Replace the GUI with our own texture and 3D plane that // is attached to the rendder camera for true 3D placement private OVRGUI GuiHelper = new OVRGUI(); private GameObject GUIRenderObject = null; private RenderTexture GUIRenderTexture = null; // We want to use new Unity GUI built in 4.6 for OVRMainMenu GUI // Enable the UsingNewGUI option in the editor, // if you want to use new GUI and Unity version is higher than 4.6 #if USE_NEW_GUI private GameObject NewGUIObject = null; private GameObject RiftPresentGUIObject = null; #endif // We can set the layer to be anything we want to, this allows // a specific camera to render it public string LayerName = "Default"; // Crosshair system, rendered onto 3D plane public UnityEngine.Texture CrosshairImage = null; private OVRCrosshair Crosshair = new OVRCrosshair(); // Resolution Eye Texture private string strResolutionEyeTexture = "Resolution: 0 x 0"; // Latency values private string strLatencies = "Ren: 0.0f TWrp: 0.0f PostPresent: 0.0f"; // Vision mode on/off private bool VisionMode = true; #if SHOW_DK2_VARIABLES private string strVisionMode = "Vision Enabled: ON"; #endif // We want to hold onto GridCube, for potential sharing // of the menu RenderTarget OVRGridCube GridCube = null; // We want to hold onto the VisionGuide so we can share // the menu RenderTarget OVRVisionGuide VisionGuide = null; #region MonoBehaviour Message Handlers /// <summary> /// Awake this instance. /// </summary> void Awake() { // Find camera controller OVRCameraRig[] CameraControllers; CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRCameraRig attached."); else if (CameraControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRCameraRig attached."); else{ CameraController = CameraControllers[0]; #if USE_NEW_GUI OVRUGUI.CameraController = CameraController; #endif } // Find player controller OVRPlayerController[] PlayerControllers; PlayerControllers = gameObject.GetComponentsInChildren<OVRPlayerController>(); if(PlayerControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRPlayerController attached."); else if (PlayerControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRPlayerController attached."); else{ PlayerController = PlayerControllers[0]; #if USE_NEW_GUI OVRUGUI.PlayerController = PlayerController; #endif } #if USE_NEW_GUI // Create canvas for using new GUI NewGUIObject = new GameObject(); NewGUIObject.name = "OVRGUIMain"; NewGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = NewGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localScale = new Vector3(0.001f, 0.001f, 0.001f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; Canvas c = NewGUIObject.AddComponent<Canvas>(); c.renderMode = RenderMode.World; c.pixelPerfect = false; #endif } /// <summary> /// Start this instance. /// </summary> void Start() { AlphaFadeValue = 1.0f; CurrentLevel = 0; PrevStartDown = false; PrevHatDown = false; PrevHatUp = false; ShowVRVars = false; OldSpaceHit = false; strFPS = "FPS: 0"; LoadingLevel = false; ScenesVisible = false; // Set the GUI target GUIRenderObject = GameObject.Instantiate(Resources.Load("OVRGUIObjectMain")) as GameObject; if(GUIRenderObject != null) { // Chnge the layer GUIRenderObject.layer = LayerMask.NameToLayer(LayerName); if(GUIRenderTexture == null) { int w = Screen.width; int h = Screen.height; // We don't need a depth buffer on this texture GUIRenderTexture = new RenderTexture(w, h, 0); GuiHelper.SetPixelResolution(w, h); // NOTE: All GUI elements are being written with pixel values based // from DK1 (1280x800). These should change to normalized locations so // that we can scale more cleanly with varying resolutions GuiHelper.SetDisplayResolution(1280.0f, 800.0f); } } // Attach GUI texture to GUI object and GUI object to Camera if(GUIRenderTexture != null && GUIRenderObject != null) { GUIRenderObject.GetComponent<Renderer>().material.mainTexture = GUIRenderTexture; if(CameraController != null) { // Grab transform of GUI object Vector3 ls = GUIRenderObject.transform.localScale; Vector3 lp = GUIRenderObject.transform.localPosition; Quaternion lr = GUIRenderObject.transform.localRotation; // Attach the GUI object to the camera GUIRenderObject.transform.parent = CameraController.centerEyeAnchor; // Reset the transform values (we will be maintaining state of the GUI object // in local state) GUIRenderObject.transform.localScale = ls; GUIRenderObject.transform.localPosition = lp; GUIRenderObject.transform.localRotation = lr; // Deactivate object until we have completed the fade-in // Also, we may want to deactive the render object if there is nothing being rendered // into the UI GUIRenderObject.SetActive(false); } } // Make sure to hide cursor if(Application.isEditor == false) { #if UNITY_5_0 Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; #else Screen.showCursor = false; Screen.lockCursor = true; #endif } // CameraController updates if(CameraController != null) { // Add a GridCube component to this object GridCube = gameObject.AddComponent<OVRGridCube>(); GridCube.SetOVRCameraController(ref CameraController); // Add a VisionGuide component to this object VisionGuide = gameObject.AddComponent<OVRVisionGuide>(); VisionGuide.SetOVRCameraController(ref CameraController); VisionGuide.SetFadeTexture(ref FadeInTexture); VisionGuide.SetVisionGuideLayer(ref LayerName); } // Crosshair functionality Crosshair.Init(); Crosshair.SetCrosshairTexture(ref CrosshairImage); Crosshair.SetOVRCameraController (ref CameraController); Crosshair.SetOVRPlayerController(ref PlayerController); // Check for HMD and sensor CheckIfRiftPresent(); #if USE_NEW_GUI if (!string.IsNullOrEmpty(strRiftPresent)){ ShowRiftPresentGUI(); } #endif } /// <summary> /// Update this instance. /// </summary> void Update() { if(LoadingLevel == true) return; // Main update UpdateFPS(); // CameraController updates if(CameraController != null) { UpdateIPD(); UpdateRecenterPose(); UpdateVisionMode(); UpdateFOV(); UpdateEyeHeightOffset(); UpdateResolutionEyeTexture(); UpdateLatencyValues(); } // PlayerController updates if(PlayerController != null) { UpdateSpeedAndRotationScaleMultiplier(); UpdatePlayerControllerMovement(); } // MainMenu updates UpdateSelectCurrentLevel(); // Device updates UpdateDeviceDetection(); // Crosshair functionality Crosshair.UpdateCrosshair(); #if USE_NEW_GUI if (ShowVRVars && RiftPresentTimeout <= 0.0f) { NewGUIObject.SetActive(true); UpdateNewGUIVars(); OVRUGUI.UpdateGUI(); } else { NewGUIObject.SetActive(false); } #endif // Toggle Fullscreen if(Input.GetKeyDown(KeyCode.F11)) Screen.fullScreen = !Screen.fullScreen; if (Input.GetKeyDown(KeyCode.M)) OVRManager.display.mirrorMode = !OVRManager.display.mirrorMode; // Escape Application if (Input.GetKeyDown(QuitKey)) Application.Quit(); } /// <summary> /// Updates Variables for new GUI. /// </summary> #if USE_NEW_GUI void UpdateNewGUIVars() { #if SHOW_DK2_VARIABLES // Print out Vision Mode OVRUGUI.strVisionMode = strVisionMode; #endif // Print out FPS OVRUGUI.strFPS = strFPS; // Don't draw these vars if CameraController is not present if (CameraController != null) { OVRUGUI.strPrediction = strPrediction; OVRUGUI.strIPD = strIPD; OVRUGUI.strFOV = strFOV; OVRUGUI.strResolutionEyeTexture = strResolutionEyeTexture; OVRUGUI.strLatencies = strLatencies; } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { OVRUGUI.strHeight = strHeight; OVRUGUI.strSpeedRotationMultipler = strSpeedRotationMultipler; } OVRUGUI.strRiftPresent = strRiftPresent; } #endif void OnGUI() { // Important to keep from skipping render events if (Event.current.type != EventType.Repaint) return; #if !USE_NEW_GUI // Fade in screen if(AlphaFadeValue > 0.0f) { AlphaFadeValue -= Mathf.Clamp01(Time.deltaTime / FadeInTime); if(AlphaFadeValue < 0.0f) { AlphaFadeValue = 0.0f; } else { GUI.color = new Color(0, 0, 0, AlphaFadeValue); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); return; } } #endif // We can turn on the render object so we can render the on-screen menu if(GUIRenderObject != null) { if (ScenesVisible || ShowVRVars || Crosshair.IsCrosshairVisible() || RiftPresentTimeout > 0.0f || VisionGuide.GetFadeAlphaValue() > 0.0f) { GUIRenderObject.SetActive(true); } else { GUIRenderObject.SetActive(false); } } //*** // Set the GUI matrix to deal with portrait mode Vector3 scale = Vector3.one; Matrix4x4 svMat = GUI.matrix; // save current matrix // substitute matrix - only scale is altered from standard GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale); // Cache current active render texture RenderTexture previousActive = RenderTexture.active; // if set, we will render to this texture if(GUIRenderTexture != null && GUIRenderObject.activeSelf) { RenderTexture.active = GUIRenderTexture; GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f)); } // Update OVRGUI functions (will be deprecated eventually when 2D renderingc // is removed from GUI) GuiHelper.SetFontReplace(FontReplace); // If true, we are displaying information about the Rift not being detected // So do not show anything else if(GUIShowRiftDetected() != true) { GUIShowLevels(); GUIShowVRVariables(); } // The cross-hair may need to go away at some point, unless someone finds it // useful Crosshair.OnGUICrosshair(); // Since we want to draw into the main GUI that is shared within the MainMenu, // we call the OVRVisionGuide GUI function here VisionGuide.OnGUIVisionGuide(); // Restore active render texture if (GUIRenderObject.activeSelf) { RenderTexture.active = previousActive; } // *** // Restore previous GUI matrix GUI.matrix = svMat; } #endregion #region Internal State Management Functions /// <summary> /// Updates the FPS. /// </summary> void UpdateFPS() { TimeLeft -= Time.deltaTime; Accum += Time.timeScale/Time.deltaTime; ++Frames; // Interval ended - update GUI text and start new interval if( TimeLeft <= 0.0 ) { // display two fractional digits (f2 format) float fps = Accum / Frames; if(ShowVRVars == true)// limit gc strFPS = System.String.Format("FPS: {0:F2}",fps); TimeLeft += UpdateInterval; Accum = 0.0f; Frames = 0; } } /// <summary> /// Updates the IPD. /// </summary> void UpdateIPD() { if(ShowVRVars == true) // limit gc { strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f); } } void UpdateRecenterPose() { if(Input.GetKeyDown(KeyCode.R)) { OVRManager.display.RecenterPose(); } } /// <summary> /// Updates the vision mode. /// </summary> void UpdateVisionMode() { if (Input.GetKeyDown(KeyCode.F2)) { VisionMode = !VisionMode; OVRManager.tracker.isEnabled = VisionMode; #if SHOW_DK2_VARIABLES strVisionMode = VisionMode ? "Vision Enabled: ON" : "Vision Enabled: OFF"; #endif } } /// <summary> /// Updates the FOV. /// </summary> void UpdateFOV() { if(ShowVRVars == true)// limit gc { OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); strFOV = System.String.Format ("FOV (deg): {0:F3}", eyeDesc.fov.y); } } /// <summary> /// Updates resolution of eye texture /// </summary> void UpdateResolutionEyeTexture() { if (ShowVRVars == true) // limit gc { OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Right); float scale = OVRManager.instance.nativeTextureScale * OVRManager.instance.virtualTextureScale; float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x)); float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y)); strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h); } } /// <summary> /// Updates latency values /// </summary> void UpdateLatencyValues() { #if !UNITY_ANDROID || UNITY_EDITOR if (ShowVRVars == true) // limit gc { OVRDisplay.LatencyData latency = OVRManager.display.latency; if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f) strLatencies = System.String.Format("Ren : N/A TWrp: N/A PostPresent: N/A"); else strLatencies = System.String.Format("Ren : {0:F3} TWrp: {1:F3} PostPresent: {2:F3}", latency.render, latency.timeWarp, latency.postPresent); } #endif } /// <summary> /// Updates the eye height offset. /// </summary> void UpdateEyeHeightOffset() { if(ShowVRVars == true)// limit gc { float eyeHeight = OVRManager.profile.eyeHeight; strHeight = System.String.Format ("Eye Height (m): {0:F3}", eyeHeight); } } /// <summary> /// Updates the speed and rotation scale multiplier. /// </summary> void UpdateSpeedAndRotationScaleMultiplier() { float moveScaleMultiplier = 0.0f; PlayerController.GetMoveScaleMultiplier(ref moveScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha7)) moveScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha8)) moveScaleMultiplier += SpeedRotationIncrement; PlayerController.SetMoveScaleMultiplier(moveScaleMultiplier); float rotationScaleMultiplier = 0.0f; PlayerController.GetRotationScaleMultiplier(ref rotationScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha9)) rotationScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha0)) rotationScaleMultiplier += SpeedRotationIncrement; PlayerController.SetRotationScaleMultiplier(rotationScaleMultiplier); if(ShowVRVars == true)// limit gc strSpeedRotationMultipler = System.String.Format ("Spd.X: {0:F2} Rot.X: {1:F2}", moveScaleMultiplier, rotationScaleMultiplier); } /// <summary> /// Updates the player controller movement. /// </summary> void UpdatePlayerControllerMovement() { if(PlayerController != null) PlayerController.SetHaltUpdateMovement(ScenesVisible); } /// <summary> /// Updates the select current level. /// </summary> void UpdateSelectCurrentLevel() { ShowLevels(); if (!ScenesVisible) return; CurrentLevel = GetCurrentLevel(); if (Scenes.Length != 0 && (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.A) || Input.GetKeyDown(KeyCode.Return))) { LoadingLevel = true; Application.LoadLevelAsync(Scenes[CurrentLevel]); } } /// <summary> /// Shows the levels. /// </summary> /// <returns><c>true</c>, if levels was shown, <c>false</c> otherwise.</returns> bool ShowLevels() { if (Scenes.Length == 0) { ScenesVisible = false; return ScenesVisible; } bool curStartDown = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Start); bool startPressed = (curStartDown && !PrevStartDown) || Input.GetKeyDown(KeyCode.RightShift); PrevStartDown = curStartDown; if (startPressed) { ScenesVisible = !ScenesVisible; } return ScenesVisible; } /// <summary> /// Gets the current level. /// </summary> /// <returns>The current level.</returns> int GetCurrentLevel() { bool curHatDown = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatDown = true; bool curHatUp = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatUp = true; if((PrevHatDown == false) && (curHatDown == true) || Input.GetKeyDown(KeyCode.DownArrow)) { CurrentLevel = (CurrentLevel + 1) % SceneNames.Length; } else if((PrevHatUp == false) && (curHatUp == true) || Input.GetKeyDown(KeyCode.UpArrow)) { CurrentLevel--; if(CurrentLevel < 0) CurrentLevel = SceneNames.Length - 1; } PrevHatDown = curHatDown; PrevHatUp = curHatUp; return CurrentLevel; } #endregion #region Internal GUI Functions /// <summary> /// Show the GUI levels. /// </summary> void GUIShowLevels() { if(ScenesVisible == true) { // Darken the background by rendering fade texture GUI.color = new Color(0, 0, 0, 0.5f); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); GUI.color = Color.white; if(LoadingLevel == true) { string loading = "LOADING..."; GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref loading, Color.yellow); return; } for (int i = 0; i < SceneNames.Length; i++) { Color c; if(i == CurrentLevel) c = Color.yellow; else c = Color.black; int y = StartY + (i * StepY); GuiHelper.StereoBox (StartX, y, WidthX, WidthY, ref SceneNames[i], c); } } } /// <summary> /// Show the VR variables. /// </summary> void GUIShowVRVariables() { bool SpaceHit = Input.GetKey(MenuKey); if ((OldSpaceHit == false) && (SpaceHit == true)) { if (ShowVRVars == true) { ShowVRVars = false; } else { ShowVRVars = true; #if USE_NEW_GUI OVRUGUI.InitUIComponent = ShowVRVars; #endif } } OldSpaceHit = SpaceHit; // Do not render if we are not showing if (ShowVRVars == false) return; int y = VRVarsSY; #if !USE_NEW_GUI #if SHOW_DK2_VARIABLES // Print out Vision Mode GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strVisionMode, Color.green); #endif // Draw FPS GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFPS, Color.green); // Don't draw these vars if CameraController is not present if (CameraController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strPrediction, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strIPD, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFOV, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strResolutionEyeTexture, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strLatencies, Color.white); } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strHeight, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strSpeedRotationMultipler, Color.white); } #endif } // RIFT DETECTION /// <summary> /// Checks to see if HMD and / or sensor is available, and displays a /// message if it is not. /// </summary> void CheckIfRiftPresent() { HMDPresent = OVRManager.display.isPresent; if (!HMDPresent) { RiftPresentTimeout = 15.0f; if (!HMDPresent) strRiftPresent = "NO HMD DETECTED"; #if USE_NEW_GUI OVRUGUI.strRiftPresent = strRiftPresent; #endif } } /// <summary> /// Show if Rift is detected. /// </summary> /// <returns><c>true</c>, if show rift detected was GUIed, <c>false</c> otherwise.</returns> bool GUIShowRiftDetected() { #if !USE_NEW_GUI if(RiftPresentTimeout > 0.0f) { GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref strRiftPresent, Color.white); return true; } #else if(RiftPresentTimeout < 0.0f) DestroyImmediate(RiftPresentGUIObject); #endif return false; } /// <summary> /// Updates the device detection. /// </summary> void UpdateDeviceDetection() { if(RiftPresentTimeout > 0.0f) RiftPresentTimeout -= Time.deltaTime; } /// <summary> /// Show rift present GUI with new GUI /// </summary> void ShowRiftPresentGUI() { #if USE_NEW_GUI RiftPresentGUIObject = new GameObject(); RiftPresentGUIObject.name = "RiftPresentGUIMain"; RiftPresentGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = RiftPresentGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; r.localScale = new Vector3(0.001f, 0.001f, 0.001f); Canvas c = RiftPresentGUIObject.AddComponent<Canvas>(); c.renderMode = RenderMode.World; c.pixelPerfect = false; OVRUGUI.RiftPresentGUI(RiftPresentGUIObject); #endif } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using IdentityModel; using IdentityServer4; using IdentityServer4.Events; using IdentityServer4.Quickstart.UI; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Test; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Host.Quickstart.Account { [SecurityHeaders] [AllowAnonymous] public class ExternalController : Controller { private readonly TestUserStore _users; private readonly IIdentityServerInteractionService _interaction; private readonly IClientStore _clientStore; private readonly IEventService _events; public ExternalController( IIdentityServerInteractionService interaction, IClientStore clientStore, IEventService events, TestUserStore users = null) { // if the TestUserStore is not in DI, then we'll just use the global users collection // this is where you would plug in your own custom identity management library (e.g. ASP.NET Identity) _users = users ?? new TestUserStore(TestUsers.Users); _interaction = interaction; _clientStore = clientStore; _events = events; } /// <summary> /// initiate roundtrip to external authentication provider /// </summary> [HttpGet] public async Task<IActionResult> Challenge(string provider, string returnUrl) { if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/"; // validate returnUrl - either it is a valid OIDC URL or back to a local page if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false) { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } if (AccountOptions.WindowsAuthenticationSchemeName == provider) { // windows authentication needs special handling return await ProcessWindowsLoginAsync(returnUrl); } else { // start challenge and roundtrip the return URL and scheme var props = new AuthenticationProperties { RedirectUri = Url.Action(nameof(Callback)), Items = { { "returnUrl", returnUrl }, { "scheme", provider }, } }; return Challenge(props, provider); } } /// <summary> /// Post processing of external authentication /// </summary> [HttpGet] public async Task<IActionResult> Callback() { // read external identity from the temporary cookie var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new Exception("External authentication error"); } // lookup our user and external provider info var (user, provider, providerUserId, claims) = FindUserFromExternalProvider(result); if (user == null) { // this might be where you might initiate a custom workflow for user registration // in this sample we don't show how that would be done, as our sample implementation // simply auto-provisions new external user user = AutoProvisionUser(provider, providerUserId, claims); } // this allows us to collect any additonal claims or properties // for the specific prtotocols used and store them in the local auth cookie. // this is typically used to store data needed for signout from those protocols. var additionalLocalClaims = new List<Claim>(); var localSignInProps = new AuthenticationProperties(); ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps); ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps); // issue authentication cookie for user await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username)); await HttpContext.SignInAsync(new IdentityServerUser(user.SubjectId) { DisplayName = user.Username, IdentityProvider = provider, AdditionalClaims = additionalLocalClaims.ToArray() }, localSignInProps); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme); // retrieve return URL var returnUrl = result.Properties.Items["returnUrl"] ?? "~/"; // check if external login is in the context of an OIDC request var context = await _interaction.GetAuthorizationContextAsync(returnUrl); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.Client.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl }); } } return Redirect(returnUrl); } private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl) { // see if windows auth has already been requested and succeeded var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName); if (result?.Principal is WindowsPrincipal wp) { // we will issue the external cookie and then redirect the // user back to the external callback, in essence, tresting windows // auth the same as any other external authentication mechanism var props = new AuthenticationProperties() { RedirectUri = Url.Action("Callback"), Items = { { "returnUrl", returnUrl }, { "scheme", AccountOptions.WindowsAuthenticationSchemeName }, } }; var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName); id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name)); id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name)); // add the groups as claims -- be careful if the number of groups is too large if (AccountOptions.IncludeWindowsGroups) { var wi = wp.Identity as WindowsIdentity; var groups = wi.Groups.Translate(typeof(NTAccount)); var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value)); id.AddClaims(roles); } await HttpContext.SignInAsync( IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme, new ClaimsPrincipal(id), props); return Redirect(props.RedirectUri); } else { // trigger windows auth // since windows auth don't support the redirect uri, // this URL is re-triggered when we call challenge return Challenge(AccountOptions.WindowsAuthenticationSchemeName); } } private (TestUser user, string provider, string providerUserId, IEnumerable<Claim> claims) FindUserFromExternalProvider(AuthenticateResult result) { var externalUser = result.Principal; // try to determine the unique id of the external user (issued by the provider) // the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ?? externalUser.FindFirst(ClaimTypes.NameIdentifier) ?? throw new Exception("Unknown userid"); // remove the user id claim so we don't include it as an extra claim if/when we provision the user var claims = externalUser.Claims.ToList(); claims.Remove(userIdClaim); var provider = result.Properties.Items["scheme"]; var providerUserId = userIdClaim.Value; // find external user var user = _users.FindByExternalProvider(provider, providerUserId); return (user, provider, providerUserId, claims); } private TestUser AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims) { var user = _users.AutoProvisionUser(provider, providerUserId, claims.ToList()); return user; } private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { // if the external system sent a session id claim, copy it over // so we can use it for single sign-out var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId); if (sid != null) { localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value)); } // if the external provider issued an id_token, we'll keep it for signout var id_token = externalResult.Properties.GetTokenValue("id_token"); if (id_token != null) { localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } }); } } private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps) { } } }
// 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.Runtime.InteropServices; namespace System.Threading { [StructLayout(LayoutKind.Sequential)] internal partial struct Win32ThreadPoolNativeOverlapped { // Per-thread cache of the args object, so we don't have to allocate a new one each time. [ThreadStatic] private static ExecutionContextCallbackArgs t_executionContextCallbackArgs; private static ContextCallback s_executionContextCallback; private static OverlappedData[] s_dataArray; private static int s_dataCount; // Current number of valid entries in _dataArray private static IntPtr s_freeList; // Lock-free linked stack of free ThreadPoolNativeOverlapped instances. private NativeOverlapped _overlapped; // must be first, so we can cast to and from NativeOverlapped. private IntPtr _nextFree; // if this instance if free, points to the next free instance. private int _dataIndex; // Index in _dataArray of this instance's OverlappedData. internal OverlappedData Data { get { return s_dataArray[_dataIndex]; } } internal static unsafe Win32ThreadPoolNativeOverlapped* Allocate(IOCompletionCallback callback, object state, object pinData, PreAllocatedOverlapped preAllocated) { Win32ThreadPoolNativeOverlapped* overlapped = AllocateNew(); try { overlapped->SetData(callback, state, pinData, preAllocated); } catch { Free(overlapped); throw; } return overlapped; } private static unsafe Win32ThreadPoolNativeOverlapped* AllocateNew() { IntPtr freePtr; Win32ThreadPoolNativeOverlapped* overlapped; OverlappedData data; // Find a free Overlapped while ((freePtr = Volatile.Read(ref s_freeList)) != IntPtr.Zero) { overlapped = (Win32ThreadPoolNativeOverlapped*)freePtr; if (Interlocked.CompareExchange(ref s_freeList, overlapped->_nextFree, freePtr) != freePtr) continue; overlapped->_nextFree = IntPtr.Zero; return overlapped; } // None are free; allocate a new one. overlapped = (Win32ThreadPoolNativeOverlapped*)Interop.MemAlloc((UIntPtr)sizeof(Win32ThreadPoolNativeOverlapped)); *overlapped = default(Win32ThreadPoolNativeOverlapped); // Allocate a OverlappedData object, and an index at which to store it in _dataArray. data = new OverlappedData(); int dataIndex = Interlocked.Increment(ref s_dataCount) - 1; // Make sure we didn't wrap around. if (dataIndex < 0) Environment.FailFast("Too many outstanding Win32ThreadPoolNativeOverlapped instances"); while (true) { OverlappedData[] dataArray = Volatile.Read(ref s_dataArray); int currentLength = dataArray == null ? 0 : dataArray.Length; // If the current array is too small, create a new, larger one. if (currentLength <= dataIndex) { int newLength = currentLength; if (newLength == 0) newLength = 128; while (newLength <= dataIndex) newLength = (newLength * 3) / 2; OverlappedData[] newDataArray = dataArray; Array.Resize(ref newDataArray, newLength); if (Interlocked.CompareExchange(ref s_dataArray, newDataArray, dataArray) != dataArray) continue; // Someone else got the free one, try again dataArray = newDataArray; } // If we haven't stored this object in the array yet, do so now. Then we need to make another pass through // the loop, in case another thread resized the array before we made this update. if (s_dataArray[dataIndex] == null) { // Full fence so this write can't move past subsequent reads. Interlocked.Exchange(ref dataArray[dataIndex], data); continue; } // We're already in the array, so we're done. Debug.Assert(dataArray[dataIndex] == data); overlapped->_dataIndex = dataIndex; return overlapped; } } private void SetData(IOCompletionCallback callback, object state, object pinData, PreAllocatedOverlapped preAllocated) { Debug.Assert(callback != null); OverlappedData data = Data; data._callback = callback; data._state = state; data._executionContext = ExecutionContext.Capture(); data._preAllocated = preAllocated; // // pinData can be any blittable type to be pinned, *or* an instance of object[] each element of which refers to // an instance of a blittable type to be pinned. // if (pinData != null) { object[] objArray = pinData as object[]; if (objArray != null && objArray.GetType() == typeof(object[])) { if (data._pinnedData == null || data._pinnedData.Length < objArray.Length) Array.Resize(ref data._pinnedData, objArray.Length); for (int i = 0; i < objArray.Length; i++) { if (!data._pinnedData[i].IsAllocated) data._pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned); else data._pinnedData[i].Target = objArray[i]; } } else { if (data._pinnedData == null) data._pinnedData = new GCHandle[1]; if (!data._pinnedData[0].IsAllocated) data._pinnedData[0] = GCHandle.Alloc(pinData, GCHandleType.Pinned); else data._pinnedData[0].Target = pinData; } } } internal static unsafe void Free(Win32ThreadPoolNativeOverlapped* overlapped) { // Reset all data. overlapped->Data.Reset(); overlapped->_overlapped = default(NativeOverlapped); // Add to the free list. while (true) { IntPtr freePtr = Volatile.Read(ref s_freeList); overlapped->_nextFree = freePtr; if (Interlocked.CompareExchange(ref s_freeList, (IntPtr)overlapped, freePtr) == freePtr) break; } } internal static unsafe NativeOverlapped* ToNativeOverlapped(Win32ThreadPoolNativeOverlapped* overlapped) { return (NativeOverlapped*)overlapped; } internal static unsafe Win32ThreadPoolNativeOverlapped* FromNativeOverlapped(NativeOverlapped* overlapped) { return (Win32ThreadPoolNativeOverlapped*)overlapped; } internal static unsafe void CompleteWithCallback(uint errorCode, uint bytesWritten, Win32ThreadPoolNativeOverlapped* overlapped) { OverlappedData data = overlapped->Data; Debug.Assert(!data._completed); data._completed = true; ContextCallback callback = s_executionContextCallback; if (callback == null) s_executionContextCallback = callback = OnExecutionContextCallback; // Get an args object from the per-thread cache. ExecutionContextCallbackArgs args = t_executionContextCallbackArgs; if (args == null) args = new ExecutionContextCallbackArgs(); t_executionContextCallbackArgs = null; args._errorCode = errorCode; args._bytesWritten = bytesWritten; args._overlapped = overlapped; args._data = data; ExecutionContext.Run(data._executionContext, callback, args); } private static unsafe void OnExecutionContextCallback(object state) { ExecutionContextCallbackArgs args = (ExecutionContextCallbackArgs)state; uint errorCode = args._errorCode; uint bytesWritten = args._bytesWritten; Win32ThreadPoolNativeOverlapped* overlapped = args._overlapped; OverlappedData data = args._data; // Put the args object back in the per-thread cache, now that we're done with it. args._data = null; t_executionContextCallbackArgs = args; data._callback(errorCode, bytesWritten, ToNativeOverlapped(overlapped)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ClosedXML.Excel; using System.IO; using MoreLinq; namespace ClosedXML.Examples { public class AddingComments : IXLExample { public void Create(string filePath) { var wb = new XLWorkbook {Author = "Manuel"}; AddMiscComments(wb); AddVisibilityComments(wb); AddPosition(wb); AddSignatures(wb); AddStyleAlignment(wb); AddColorsAndLines(wb); AddMagins(wb); AddProperties(wb); AddProtection(wb); AddSize(wb); AddWeb(wb); wb.SaveAs(filePath); } private void AddWeb(XLWorkbook wb) { var ws = wb.Worksheets.Add("Web"); ws.Cell("A1").GetComment().Style.Web.AlternateText = "The alternate text in case you need it."; } private void AddSize(XLWorkbook wb) { var ws = wb.Worksheets.Add("Size"); // Automatic size is a copy of the property comment.Style.Alignment.AutomaticSize // I created the duplicate because it makes more sense for it to be in Size // but Excel has it under the Alignment tab. ws.Cell("A2").GetComment().AddText("Things are very tight around here."); ws.Cell("A2").GetComment().Style.Size.SetAutomaticSize(); ws.Cell("A4").GetComment().AddText("Different size"); ws.Cell("A4").GetComment().Style .Size.SetHeight(30) // The height is set in the same units as row.Height .Size.SetWidth(30); // The width is set in the same units as row.Width // Set all comments to visible ws.CellsUsed(XLCellsUsedOptions.All, c => c.HasComment).ForEach(c => c.GetComment().SetVisible()); } private void AddProtection(XLWorkbook wb) { var ws = wb.Worksheets.Add("Protection"); ws.Cell("A1").GetComment().Style .Protection.SetLocked(false) .Protection.SetLockText(false); } private void AddProperties(XLWorkbook wb) { var ws = wb.Worksheets.Add("Properties"); ws.Cell("A1").GetComment().Style.Properties.Positioning = XLDrawingAnchor.Absolute; ws.Cell("A2").GetComment().Style.Properties.Positioning = XLDrawingAnchor.MoveAndSizeWithCells; ws.Cell("A3").GetComment().Style.Properties.Positioning = XLDrawingAnchor.MoveWithCells; } private void AddMagins(XLWorkbook wb) { var ws = wb.Worksheets.Add("Margins"); ws.Cell("A2").GetComment() .SetVisible() .AddText("Lorem ipsum dolor sit amet, adipiscing elit. ").AddNewLine() .AddText("Nunc elementum, sapien a ultrices, commodo nisl. ").AddNewLine() .AddText("Consequat erat lectus a nisi. Aliquam facilisis."); ws.Cell("A2").GetComment().Style .Margins.SetAll(0.25) .Size.SetAutomaticSize(); } private void AddColorsAndLines(XLWorkbook wb) { var ws = wb.Worksheets.Add("Colors and Lines"); ws.Cell("A2").GetComment() .AddText("Now ") .AddText("THIS").SetBold().SetFontColor(XLColor.Red) .AddText(" is colorful!"); ws.Cell("A2").GetComment().Style .ColorsAndLines.SetFillColor(XLColor.RichCarmine) .ColorsAndLines.SetFillTransparency(0.25) // 25% opaque .ColorsAndLines.SetLineColor(XLColor.Blue) .ColorsAndLines.SetLineTransparency(0.75) // 75% opaque .ColorsAndLines.SetLineDash(XLDashStyle.LongDash) .ColorsAndLines.SetLineStyle(XLLineStyle.ThickBetweenThin) .ColorsAndLines.SetLineWeight(7.5); // Set all comments to visible ws.CellsUsed(XLCellsUsedOptions.All, c => c.HasComment).ForEach(c => c.GetComment().SetVisible()); } private void AddStyleAlignment(XLWorkbook wb) { var ws = wb.Worksheets.Add("Alignment"); // Automagically adjust the size of the comment to fit the contents ws.Cell("A1").GetComment().Style.Alignment.SetAutomaticSize(); ws.Cell("A1").GetComment().AddText("Things are pretty tight around here"); // Default values ws.Cell("A3").GetComment() .AddText("Default Alignments:").AddNewLine() .AddText("Vertical = Top").AddNewLine() .AddText("Horizontal = Left").AddNewLine() .AddText("Orientation = Left to Right"); // Let's change the alignments ws.Cell("A8").GetComment() .AddText("Vertical = Bottom").AddNewLine() .AddText("Horizontal = Right"); ws.Cell("A8").GetComment().Style .Alignment.SetVertical(XLDrawingVerticalAlignment.Bottom) .Alignment.SetHorizontal(XLDrawingHorizontalAlignment.Right); // And now the orientation... ws.Cell("D3").GetComment().AddText("Orientation = Bottom to Top"); ws.Cell("D3").GetComment().Style .Alignment.SetOrientation(XLDrawingTextOrientation.BottomToTop) .Alignment.SetAutomaticSize(); ws.Cell("E3").GetComment().AddText("Orientation = Top to Bottom"); ws.Cell("E3").GetComment().Style .Alignment.SetOrientation(XLDrawingTextOrientation.TopToBottom) .Alignment.SetAutomaticSize(); ws.Cell("F3").GetComment().AddText("Orientation = Vertical"); ws.Cell("F3").GetComment().Style .Alignment.SetOrientation(XLDrawingTextOrientation.Vertical) .Alignment.SetAutomaticSize(); // Set all comments to visible ws.CellsUsed(XLCellsUsedOptions.All, c => c.HasComment).ForEach(c => c.GetComment().SetVisible()); } private static void AddMiscComments(XLWorkbook wb) { var ws = wb.Worksheets.Add("Comments"); ws.Cell("A1").SetValue("Hidden").GetComment().AddText("Hidden"); ws.Cell("A2").SetValue("Visible").GetComment().AddText("Visible"); ws.Cell("A3").SetValue("On Top").GetComment().AddText("On Top"); ws.Cell("A4").SetValue("Underneath").GetComment().AddText("Underneath"); ws.Cell("A4").GetComment().Style.Alignment.SetVertical(XLDrawingVerticalAlignment.Bottom); ws.Cell("A3").GetComment().SetZOrder(ws.Cell("A4").GetComment().ZOrder + 1); ws.Cell("D9").GetComment().AddText("Vertical"); ws.Cell("D9").GetComment().Style.Alignment.Orientation = XLDrawingTextOrientation.Vertical; ws.Cell("D9").GetComment().Style.Size.SetAutomaticSize(); ws.Cell("E9").GetComment().AddText("Top to Bottom"); ws.Cell("E9").GetComment().Style.Alignment.Orientation = XLDrawingTextOrientation.TopToBottom; ws.Cell("E9").GetComment().Style.Size.SetAutomaticSize(); ws.Cell("F9").GetComment().AddText("Bottom to Top"); ws.Cell("F9").GetComment().Style.Alignment.Orientation = XLDrawingTextOrientation.BottomToTop; ws.Cell("F9").GetComment().Style.Size.SetAutomaticSize(); ws.Cell("E1").GetComment().Position.SetColumn(5); ws.Cell("E1").GetComment().AddText("Start on Col E, on top border"); ws.Cell("E1").GetComment().Style.Size.SetWidth(10); var cE3 = ws.Cell("E3").GetComment(); cE3.AddText("Size and position"); cE3.Position.SetColumn(5).SetRow(4).SetColumnOffset(7).SetRowOffset(10); cE3.Style.Size.SetHeight(25).Size.SetWidth(10); var cE7 = ws.Cell("E7").GetComment(); cE7.Position.SetColumn(6).SetRow(7).SetColumnOffset(0).SetRowOffset(0); cE7.Style.Size.SetHeight(ws.Row(7).Height).Size.SetWidth(ws.Column(6).Width); ws.Cell("G1").GetComment().AddText("Automatic Size"); ws.Cell("G1").GetComment().Style.Alignment.SetAutomaticSize(); var cG3 = ws.Cell("G3").GetComment(); cG3.SetAuthor("MDeLeon"); cG3.AddSignature(); cG3.AddText("This is a test of the emergency broadcast system."); cG3.AddNewLine(); cG3.AddText("Do "); cG3.AddText("NOT").SetFontColor(XLColor.RadicalRed).SetUnderline().SetBold(); cG3.AddText(" forget it."); cG3.Style .Size.SetWidth(25) .Size.SetHeight(100) .Alignment.SetDirection(XLDrawingTextDirection.LeftToRight) .Alignment.SetHorizontal(XLDrawingHorizontalAlignment.Distributed) .Alignment.SetVertical(XLDrawingVerticalAlignment.Center) .Alignment.SetOrientation(XLDrawingTextOrientation.LeftToRight) .ColorsAndLines.SetFillColor(XLColor.Cyan) .ColorsAndLines.SetFillTransparency(0.25) .ColorsAndLines.SetLineColor(XLColor.DarkBlue) .ColorsAndLines.SetLineTransparency(0.75) .ColorsAndLines.SetLineDash(XLDashStyle.DashDot) .ColorsAndLines.SetLineStyle(XLLineStyle.ThinThick) .ColorsAndLines.SetLineWeight(5) .Margins.SetAll(0.25) .Properties.SetPositioning(XLDrawingAnchor.MoveAndSizeWithCells) .Protection.SetLocked(false) .Protection.SetLockText(false) .Web.SetAlternateText("This won't be released to the web"); ws.Cell("A9").GetComment().SetAuthor("MDeLeon").AddSignature().AddText("Something"); ws.Cell("A9").GetComment().SetBold().SetFontColor(XLColor.DarkBlue); ws.CellsUsed(XLCellsUsedOptions.All, c => !c.Address.ToStringRelative().Equals("A1") && c.HasComment).ForEach(c => c.GetComment().SetVisible()); } private static void AddVisibilityComments(XLWorkbook wb) { var ws = wb.Worksheets.Add("Visibility"); // By default comments are hidden ws.Cell("A1").SetValue("I have a hidden comment").GetComment().AddText("Hidden"); // Set the comment as visible ws.Cell("A2").GetComment().SetVisible().AddText("Visible"); // The ZOrder on previous comments were 1 and 2 respectively // here we're explicit about the ZOrder ws.Cell("A3").GetComment().SetZOrder(5).SetVisible().AddText("On Top"); // We want this comment to appear underneath the one for A3 // so we set the ZOrder to something lower ws.Cell("A4").GetComment().SetZOrder(4).SetVisible().AddText("Underneath"); ws.Cell("A4").GetComment().Style.Alignment.SetVertical(XLDrawingVerticalAlignment.Bottom); // Alternatively you could set all comments to visible with the following line: // ws.CellsUsed(true, c => c.HasComment).ForEach(c => c.Comment.SetVisible()); ws.Columns().AdjustToContents(); } private void AddPosition(XLWorkbook wb) { var ws = wb.Worksheets.Add("Position"); ws.Columns().Width = 10; ws.Cell("A1").GetComment().AddText("This is an unusual place for a comment..."); ws.Cell("A1").GetComment().Position .SetColumn(3) // Starting from the third column .SetColumnOffset(5) // The comment will start in the middle of the third column .SetRow(5) // Starting from the fifth row .SetRowOffset(7.5); // The comment will start in the middle of the fifth row // Set all comments to visible ws.CellsUsed(XLCellsUsedOptions.All, c => c.HasComment).ForEach(c => c.GetComment().SetVisible()); } private void AddSignatures(XLWorkbook wb) { var ws = wb.Worksheets.Add("Signatures"); // By default the signature will be with the logged user // ws.Cell("A2").Comment.AddSignature().AddText("Hello World!"); // You can override this by specifying the comment's author: ws.Cell("A2").GetComment() .SetAuthor("MDeLeon") .AddSignature() .AddText("Hello World!"); // Set all comments to visible ws.CellsUsed(XLCellsUsedOptions.All, c => c.HasComment).ForEach(c => c.GetComment().SetVisible()); } } }