context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition.Hosting { // This class guarantees thread-safety under the following conditions: // - Each composition is executed on a single thread // - No recomposition ever takes place // - The class is created with isThreadSafe=true public partial class ImportEngine : ICompositionService, IDisposable { private const int MaximumNumberOfCompositionIterations = 100; private volatile bool _isDisposed; private ExportProvider _sourceProvider; private Stack<PartManager> _recursionStateStack = new Stack<PartManager>(); private ConditionalWeakTable<ComposablePart, PartManager> _partManagers = new ConditionalWeakTable<ComposablePart, PartManager>(); private RecompositionManager _recompositionManager = new RecompositionManager(); private readonly CompositionLock _lock = null; private readonly CompositionOptions _compositionOptions; /// <summary> /// Initializes a new instance of the <see cref="ImportEngine"/> class. /// </summary> /// <param name="sourceProvider"> /// The <see cref="ExportProvider"/> which provides the /// <see cref="ImportEngine"/> access to <see cref="Export"/>s. /// </param> public ImportEngine(ExportProvider sourceProvider) : this(sourceProvider, CompositionOptions.Default) { } public ImportEngine(ExportProvider sourceProvider, bool isThreadSafe) : this(sourceProvider, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default) { } public ImportEngine(ExportProvider sourceProvider, CompositionOptions compositionOptions) { Requires.NotNull(sourceProvider, nameof(sourceProvider)); _compositionOptions = compositionOptions; _sourceProvider = sourceProvider; _sourceProvider.ExportsChanging += OnExportsChanging; _lock = new CompositionLock(compositionOptions.HasFlag(CompositionOptions.IsThreadSafe)); } /// <summary> /// Previews all the required imports for the given <see cref="ComposablePart"/> to /// ensure they can all be satisified. The preview does not actually set the imports /// only ensures that they exist in the source provider. If the preview succeeds then /// the <see cref="ImportEngine"/> also enforces that changes to exports in the source /// provider will not break any of the required imports. If this enforcement needs to be /// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this /// <see cref="ComposablePart"/>. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to preview the required imports. /// </param> /// <param name="atomicComposition"></param> /// <exception cref="CompositionException"> /// An error occurred during previewing and <paramref name="atomicComposition"/> is null. /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred. /// The pre-existing composition is in an unknown state, depending on the errors that occured. /// </exception> /// <exception cref="ChangeRejectedException"> /// An error occurred during the previewing and <paramref name="atomicComposition"/> is not null. /// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred. /// The pre-existing composition remains in valid state. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ImportEngine"/> has been disposed of. /// </exception> public void PreviewImports(ComposablePart part, AtomicComposition atomicComposition) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); // Do not do any previewing if SilentRejection is disabled. if (_compositionOptions.HasFlag(CompositionOptions.DisableSilentRejection)) { return; } // NOTE : this is a very intricate area threading-wise, please use caution when changing, otherwise state corruption or deadlocks will ensue // The gist of what we are doing is as follows: // We need to lock the composition, as we will proceed modifying our internal state. The tricky part is when we release the lock // Due to the fact that some actions will take place AFTER we leave this method, we need to KEEP THAT LOCK HELD until the transation is commiited or rolled back // This is the reason we CAN'T use "using here. // Instead, if the transaction is present we will queue up the release of the lock, otherwise we will release it when we exit this method // We add the "release" lock to BOTH Commit and Revert queues, because they are mutually exclusive, and we need to release the lock regardless. // This will take the lock, if necesary IDisposable compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null; bool compositionLockTaken = (compositionLockHolder != null); try { // revert actions are processed in the reverse order, so we have to add the "release lock" action now if (compositionLockTaken && (atomicComposition != null)) { atomicComposition.AddRevertAction(() => compositionLockHolder.Dispose()); } var partManager = GetPartManager(part, true); var result = TryPreviewImportsStateMachine(partManager, part, atomicComposition); result.ThrowOnErrors(atomicComposition); StartSatisfyingImports(partManager, atomicComposition); // Add the "release lock" to the commit actions if (compositionLockTaken && (atomicComposition != null)) { atomicComposition.AddCompleteAction(() => compositionLockHolder.Dispose()); } } finally { // We haven't updated the queues, so we can release the lock now if (compositionLockTaken && (atomicComposition == null)) { compositionLockHolder.Dispose(); } } } /// <summary> /// Satisfies the imports of the specified composable part. If the satisfy succeeds then /// the <see cref="ImportEngine"/> also enforces that changes to exports in the source /// provider will not break any of the required imports. If this enforcement needs to be /// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this /// <see cref="ComposablePart"/>. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to set the imports. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ImportEngine"/> has been disposed of. /// </exception> public void SatisfyImports(ComposablePart part) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); // NOTE : the following two calls use the state lock PartManager partManager = GetPartManager(part, true); if (partManager.State == ImportState.Composed) { return; } using (_lock.LockComposition()) { var result = TrySatisfyImports(partManager, part, true); result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException } } /// <summary> /// Sets the imports of the specified composable part exactly once and they will not /// ever be recomposed. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to set the imports. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="part"/> is <see langword="null"/>. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ICompositionService"/> has been disposed of. /// </exception> public void SatisfyImportsOnce(ComposablePart part) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); // NOTE : the following two calls use the state lock PartManager partManager = GetPartManager(part, true); if (partManager.State == ImportState.Composed) { return; } using (_lock.LockComposition()) { var result = TrySatisfyImports(partManager, part, false); result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException } } /// <summary> /// Removes any state stored in the <see cref="ImportEngine"/> for the associated /// <see cref="ComposablePart"/> and releases all the <see cref="Export"/>s used to /// satisfy the imports on the <see cref="ComposablePart"/>. /// /// Also removes the enforcement for changes that would break a required import on /// <paramref name="part"/>. /// </summary> /// <param name="part"> /// The <see cref="ComposablePart"/> to release the imports on. /// </param> /// <param name="atomicComposition"> /// The <see cref="AtomicComposition"/> that the release imports is running under. /// </param> public void ReleaseImports(ComposablePart part, AtomicComposition atomicComposition) { ThrowIfDisposed(); Requires.NotNull(part, nameof(part)); using (_lock.LockComposition()) { PartManager partManager = GetPartManager(part, false); if (partManager != null) { StopSatisfyingImports(partManager, atomicComposition); } } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (!_isDisposed) { bool disposeLock = false; ExportProvider sourceProviderToUnsubscribeFrom = null; using (_lock.LockStateForWrite()) { if (!_isDisposed) { sourceProviderToUnsubscribeFrom = _sourceProvider; _sourceProvider = null; _recompositionManager = null; _partManagers = null; _isDisposed = true; disposeLock = true; } } if (sourceProviderToUnsubscribeFrom != null) { sourceProviderToUnsubscribeFrom.ExportsChanging -= OnExportsChanging; } if (disposeLock) { _lock.Dispose(); } } } } private CompositionResult TryPreviewImportsStateMachine(PartManager partManager, ComposablePart part, AtomicComposition atomicComposition) { var result = CompositionResult.SucceededResult; if (partManager.State == ImportState.ImportsPreviewing) { // We shouldn't nomally ever hit this case but if we do // then we should just error with a cycle error. return new CompositionResult(ErrorBuilder.CreatePartCycle(part)); } // Transition from NoImportsStatisified to ImportsPreviewed if (partManager.State == ImportState.NoImportsSatisfied) { partManager.State = ImportState.ImportsPreviewing; var requiredImports = part.ImportDefinitions.Where(IsRequiredImportForPreview); // If this atomicComposition gets rolledback for any reason we need to reset our state atomicComposition.AddRevertActionAllowNull(() => partManager.State = ImportState.NoImportsSatisfied); result = result.MergeResult( TrySatisfyImportSubset(partManager, requiredImports, atomicComposition)); if (!result.Succeeded) { partManager.State = ImportState.NoImportsSatisfied; return result; } partManager.State = ImportState.ImportsPreviewed; } return result; } private CompositionResult TrySatisfyImportsStateMachine(PartManager partManager, ComposablePart part) { var result = CompositionResult.SucceededResult; while (partManager.State < ImportState.Composed) { var previousState = partManager.State; switch (partManager.State) { // "ed" states which represent a some sort of steady state and will // attempt to do a state transition case ImportState.NoImportsSatisfied: case ImportState.ImportsPreviewed: { partManager.State = ImportState.PreExportImportsSatisfying; var prereqImports = part.ImportDefinitions.Where(import => import.IsPrerequisite); result = result.MergeResult( TrySatisfyImportSubset(partManager, prereqImports, null)); partManager.State = ImportState.PreExportImportsSatisfied; break; } case ImportState.PreExportImportsSatisfied: { partManager.State = ImportState.PostExportImportsSatisfying; var requiredImports = part.ImportDefinitions.Where(import => !import.IsPrerequisite); result = result.MergeResult( TrySatisfyImportSubset(partManager, requiredImports, null)); partManager.State = ImportState.PostExportImportsSatisfied; break; } case ImportState.PostExportImportsSatisfied: { partManager.State = ImportState.ComposedNotifying; partManager.ClearSavedImports(); result = result.MergeResult(partManager.TryOnComposed()); partManager.State = ImportState.Composed; break; } // "ing" states which represent some sort of cycle // These state should always return, error or not, instead of breaking case ImportState.ImportsPreviewing: { // We shouldn't nomally ever hit this case but if we do // then we should just error with a cycle error. return new CompositionResult(ErrorBuilder.CreatePartCycle(part)); } case ImportState.PreExportImportsSatisfying: case ImportState.PostExportImportsSatisfying: { if (InPrerequisiteLoop()) { return result.MergeError(ErrorBuilder.CreatePartCycle(part)); } // Cycles in post export imports are allowed so just return in that case return result; } case ImportState.ComposedNotifying: { // We are currently notifying so don't notify again just return return result; } } // if an error occured while doing a state transition if (!result.Succeeded) { // revert to the previous state and return the error partManager.State = previousState; return result; } } return result; } private CompositionResult TrySatisfyImports(PartManager partManager, ComposablePart part, bool shouldTrackImports) { Assumes.NotNull(part); var result = CompositionResult.SucceededResult; // get out if the part is already composed if (partManager.State == ImportState.Composed) { return result; } // Track number of recursive iterations and throw an exception before the stack // fills up and debugging the root cause becomes tricky if (_recursionStateStack.Count >= MaximumNumberOfCompositionIterations) { return result.MergeError( ErrorBuilder.ComposeTookTooManyIterations(MaximumNumberOfCompositionIterations)); } // Maintain the stack to detect whether recursive loops cross prerequisites _recursionStateStack.Push(partManager); try { result = result.MergeResult( TrySatisfyImportsStateMachine(partManager, part)); } finally { _recursionStateStack.Pop(); } if (shouldTrackImports) { StartSatisfyingImports(partManager, null); } return result; } private CompositionResult TrySatisfyImportSubset(PartManager partManager, IEnumerable<ImportDefinition> imports, AtomicComposition atomicComposition) { CompositionResult result = CompositionResult.SucceededResult; var part = partManager.Part; foreach (ImportDefinition import in imports) { var exports = partManager.GetSavedImport(import); if (exports == null) { CompositionResult<IEnumerable<Export>> exportsResult = TryGetExports( _sourceProvider, part, import, atomicComposition); if (!exportsResult.Succeeded) { result = result.MergeResult(exportsResult.ToResult()); continue; } exports = exportsResult.Value.AsArray(); } if (atomicComposition == null) { result = result.MergeResult( partManager.TrySetImport(import, exports)); } else { partManager.SetSavedImport(import, exports, atomicComposition); } } return result; } private void OnExportsChanging(object sender, ExportsChangeEventArgs e) { CompositionResult result = CompositionResult.SucceededResult; // Prepare for the recomposition effort by minimizing the amount of work we'll have to do later AtomicComposition atomicComposition = e.AtomicComposition; IEnumerable<PartManager> affectedParts = _recompositionManager.GetAffectedParts(e.ChangedContractNames); // When in a atomicComposition account for everything that isn't yet reflected in the // index if (atomicComposition != null) { EngineContext engineContext; if (atomicComposition.TryGetValue(this, out engineContext)) { // always added the new part managers to see if they will also be // affected by these changes affectedParts = affectedParts.ConcatAllowingNull(engineContext.GetAddedPartManagers()) .Except(engineContext.GetRemovedPartManagers()); } } var changedExports = e.AddedExports.ConcatAllowingNull(e.RemovedExports); foreach (var partManager in affectedParts) { result = result.MergeResult(TryRecomposeImports(partManager, changedExports, atomicComposition)); } result.ThrowOnErrors(atomicComposition); } private CompositionResult TryRecomposeImports(PartManager partManager, IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition) { var result = CompositionResult.SucceededResult; switch (partManager.State) { case ImportState.ImportsPreviewed: case ImportState.Composed: // Validate states to continue. break; default: { // All other states are invalid and for recomposition. return new CompositionResult(ErrorBuilder.InvalidStateForRecompposition(partManager.Part)); } } var affectedImports = RecompositionManager.GetAffectedImports(partManager.Part, changedExports); bool partComposed = (partManager.State == ImportState.Composed); bool recomposedImport = false; foreach (var import in affectedImports) { result = result.MergeResult( TryRecomposeImport(partManager, partComposed, import, atomicComposition)); recomposedImport = true; } // Knowing that the part has already been composed before and that the only possible // changes are to recomposable imports, we can safely go ahead and do this now or // schedule it for later if (result.Succeeded && recomposedImport && partComposed) { if (atomicComposition == null) { result = result.MergeResult(partManager.TryOnComposed()); } else { atomicComposition.AddCompleteAction(() => partManager.TryOnComposed().ThrowOnErrors()); } } return result; } private CompositionResult TryRecomposeImport(PartManager partManager, bool partComposed, ImportDefinition import, AtomicComposition atomicComposition) { if (partComposed && !import.IsRecomposable) { return new CompositionResult(ErrorBuilder.PreventedByExistingImport(partManager.Part, import)); } // During recomposition you must always requery with the new atomicComposition you cannot use any // cached value in the part manager var exportsResult = TryGetExports(_sourceProvider, partManager.Part, import, atomicComposition); if (!exportsResult.Succeeded) { return exportsResult.ToResult(); } var exports = exportsResult.Value.AsArray(); if (partComposed) { // Knowing that the part has already been composed before and that the only possible // changes are to recomposable imports, we can safely go ahead and do this now or // schedule it for later if (atomicComposition == null) { return partManager.TrySetImport(import, exports); } else { atomicComposition.AddCompleteAction(() => partManager.TrySetImport(import, exports).ThrowOnErrors()); } } else { partManager.SetSavedImport(import, exports, atomicComposition); } return CompositionResult.SucceededResult; } private void StartSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition) { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant addition if (atomicComposition == null) { if (!partManager.TrackingImports) { partManager.TrackingImports = true; _recompositionManager.AddPartToIndex(partManager); } } else { // While in a atomicCompositional state use a less efficient but effective means // of achieving the same results GetEngineContext(atomicComposition).AddPartManager(partManager); } } private void StopSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition) { // When not running in a atomicCompositional state, schedule reindexing after ensuring // that this isn't a redundant removal if (atomicComposition == null) { ConditionalWeakTable<ComposablePart, PartManager> partManagers = null; RecompositionManager recompositionManager = null; using (_lock.LockStateForRead()) { partManagers = _partManagers; recompositionManager = _recompositionManager; } if (partManagers != null) // Disposal race may have been won by dispose { partManagers.Remove(partManager.Part); // Take care of lifetime requirements partManager.DisposeAllDependencies(); if (partManager.TrackingImports) { partManager.TrackingImports = false; recompositionManager.AddPartToUnindex(partManager); } } } else { // While in a atomicCompositional state use a less efficient but effective means // of achieving the same results GetEngineContext(atomicComposition).RemovePartManager(partManager); } } private PartManager GetPartManager(ComposablePart part, bool createIfNotpresent) { PartManager partManager = null; using (_lock.LockStateForRead()) { if (_partManagers.TryGetValue(part, out partManager)) { return partManager; } } if (createIfNotpresent) { using (_lock.LockStateForWrite()) { if (!_partManagers.TryGetValue(part, out partManager)) { partManager = new PartManager(this, part); _partManagers.Add(part, partManager); } } } return partManager; } private EngineContext GetEngineContext(AtomicComposition atomicComposition) { Assumes.NotNull(atomicComposition); EngineContext engineContext; if (!atomicComposition.TryGetValue(this, true, out engineContext)) { EngineContext parentContext; atomicComposition.TryGetValue(this, false, out parentContext); engineContext = new EngineContext(this, parentContext); atomicComposition.SetValue(this, engineContext); atomicComposition.AddCompleteAction(engineContext.Complete); } return engineContext; } private bool InPrerequisiteLoop() { PartManager firstPart = _recursionStateStack.First(); PartManager lastPart = null; foreach (PartManager testPart in _recursionStateStack.Skip(1)) { if (testPart.State == ImportState.PreExportImportsSatisfying) { return true; } if (testPart == firstPart) { lastPart = testPart; break; } } // This should only be called when a loop has been detected - so it should always be on the stack Assumes.IsTrue(lastPart == firstPart); return false; } [DebuggerStepThrough] private void ThrowIfDisposed() { if (_isDisposed) { throw ExceptionBuilder.CreateObjectDisposed(this); } } private static CompositionResult<IEnumerable<Export>> TryGetExports(ExportProvider provider, ComposablePart part, ImportDefinition definition, AtomicComposition atomicComposition) { try { IEnumerable<Export> exports = null; if (provider != null) { exports = provider.GetExports(definition, atomicComposition).AsArray(); } return new CompositionResult<IEnumerable<Export>>(exports); } catch (ImportCardinalityMismatchException ex) { // Either not enough or too many exports that match the definition CompositionException exception = new CompositionException(ErrorBuilder.CreateImportCardinalityMismatch(ex, definition)); return new CompositionResult<IEnumerable<Export>>( ErrorBuilder.CreatePartCannotSetImport(part, definition, exception)); } } internal static bool IsRequiredImportForPreview(ImportDefinition import) { return import.Cardinality == ImportCardinality.ExactlyOne; } // Ordering of this enum is important so be sure to use caution if you // try to reorder them. private enum ImportState { NoImportsSatisfied = 0, ImportsPreviewing = 1, ImportsPreviewed = 2, PreExportImportsSatisfying = 3, PreExportImportsSatisfied = 4, PostExportImportsSatisfying = 5, PostExportImportsSatisfied = 6, ComposedNotifying = 7, Composed = 8, } } }
#region License // // Author: Nate Kohari <nkohari@gmail.com> // Copyright (c) 2007-2008, Enkari, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion #region Using Directives using System; using Ninject.Core; using Ninject.Core.Tracking; using Ninject.Extensions.MessageBroker; using Ninject.Extensions.MessageBroker.Infrastructure; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; #endregion namespace Ninject.Tests.Extensions.MessageBroker { [TestFixture] public class MessageBrokerFixture { /*----------------------------------------------------------------------------------------*/ [Test] public void OnePublisherOneSubscriber() { using (var kernel = new StandardKernel(new MessageBrokerModule())) { PublisherMock pub = kernel.Get<PublisherMock>(); Assert.That(pub, Is.Not.Null); SubscriberMock sub = kernel.Get<SubscriberMock>(); Assert.That(sub, Is.Not.Null); Assert.That(pub.HasListeners); Assert.That(sub.LastMessage, Is.Null); pub.SendMessage("Hello, world!"); Assert.That(sub.LastMessage, Is.EqualTo("Hello, world!")); } } /*----------------------------------------------------------------------------------------*/ [Test] public void ManyPublishersOneSubscriber() { using (var kernel = new StandardKernel(new MessageBrokerModule())) { PublisherMock pub1 = kernel.Get<PublisherMock>(); PublisherMock pub2 = kernel.Get<PublisherMock>(); Assert.That(pub1, Is.Not.Null); Assert.That(pub2, Is.Not.Null); SubscriberMock sub = kernel.Get<SubscriberMock>(); Assert.That(sub, Is.Not.Null); Assert.That(pub1.HasListeners); Assert.That(pub2.HasListeners); Assert.That(sub.LastMessage, Is.Null); pub1.SendMessage("Hello, world!"); Assert.That(sub.LastMessage, Is.EqualTo("Hello, world!")); sub.LastMessage = null; Assert.That(sub.LastMessage, Is.Null); pub2.SendMessage("Hello, world!"); Assert.That(sub.LastMessage, Is.EqualTo("Hello, world!")); } } /*----------------------------------------------------------------------------------------*/ [Test] public void OnePublisherManySubscribers() { using (var kernel = new StandardKernel(new MessageBrokerModule())) { PublisherMock pub = kernel.Get<PublisherMock>(); Assert.That(pub, Is.Not.Null); SubscriberMock sub1 = kernel.Get<SubscriberMock>(); SubscriberMock sub2 = kernel.Get<SubscriberMock>(); Assert.That(sub1, Is.Not.Null); Assert.That(sub2, Is.Not.Null); Assert.That(pub.HasListeners); Assert.That(sub1.LastMessage, Is.Null); Assert.That(sub2.LastMessage, Is.Null); pub.SendMessage("Hello, world!"); Assert.That(sub1.LastMessage, Is.EqualTo("Hello, world!")); Assert.That(sub2.LastMessage, Is.EqualTo("Hello, world!")); } } /*----------------------------------------------------------------------------------------*/ [Test] public void ManyPublishersManySubscribers() { using (var kernel = new StandardKernel(new MessageBrokerModule())) { PublisherMock pub1 = kernel.Get<PublisherMock>(); PublisherMock pub2 = kernel.Get<PublisherMock>(); Assert.That(pub1, Is.Not.Null); Assert.That(pub2, Is.Not.Null); SubscriberMock sub1 = kernel.Get<SubscriberMock>(); SubscriberMock sub2 = kernel.Get<SubscriberMock>(); Assert.That(sub1, Is.Not.Null); Assert.That(sub2, Is.Not.Null); Assert.That(pub1.HasListeners); Assert.That(pub2.HasListeners); Assert.That(sub1.LastMessage, Is.Null); Assert.That(sub2.LastMessage, Is.Null); pub1.SendMessage("Hello, world!"); Assert.That(sub1.LastMessage, Is.EqualTo("Hello, world!")); Assert.That(sub2.LastMessage, Is.EqualTo("Hello, world!")); sub1.LastMessage = null; sub2.LastMessage = null; Assert.That(sub1.LastMessage, Is.Null); Assert.That(sub2.LastMessage, Is.Null); pub2.SendMessage("Hello, world!"); Assert.That(sub1.LastMessage, Is.EqualTo("Hello, world!")); Assert.That(sub2.LastMessage, Is.EqualTo("Hello, world!")); } } /*----------------------------------------------------------------------------------------*/ [Test] public void DisabledChannelsDoNotUnbindButEventsAreNotSent() { using (var kernel = new StandardKernel(new MessageBrokerModule())) { PublisherMock pub = kernel.Get<PublisherMock>(); Assert.That(pub, Is.Not.Null); SubscriberMock sub = kernel.Get<SubscriberMock>(); Assert.That(sub, Is.Not.Null); Assert.That(sub.LastMessage, Is.Null); var messageBroker = kernel.Components.Get<IMessageBroker>(); messageBroker.DisableChannel("message://PublisherMock/MessageReceived"); Assert.That(pub.HasListeners); pub.SendMessage("Hello, world!"); Assert.That(sub.LastMessage, Is.Null); } } /*----------------------------------------------------------------------------------------*/ [Test] public void ClosingChannelUnbindsPublisherEventsFromChannel() { using (var kernel = new StandardKernel(new MessageBrokerModule())) { PublisherMock pub = kernel.Get<PublisherMock>(); Assert.That(pub, Is.Not.Null); SubscriberMock sub = kernel.Get<SubscriberMock>(); Assert.That(sub, Is.Not.Null); Assert.That(sub.LastMessage, Is.Null); var messageBroker = kernel.Components.Get<IMessageBroker>(); messageBroker.CloseChannel("message://PublisherMock/MessageReceived"); Assert.That(pub.HasListeners, Is.False); pub.SendMessage("Hello, world!"); Assert.That(sub.LastMessage, Is.Null); } } /*----------------------------------------------------------------------------------------*/ [Test] public void DisposingObjectRemovesSubscriptionsRequestedByIt() { using (var kernel = new StandardKernel(new MessageBrokerModule())) { var pub = kernel.Get<PublisherMock>(); Assert.That(pub, Is.Not.Null); var sub = kernel.Get<SubscriberMock>(); Assert.That(sub, Is.Not.Null); var messageBroker = kernel.Components.Get<IMessageBroker>(); var channel = messageBroker.GetChannel("message://PublisherMock/MessageReceived"); Assert.That(channel.Subscriptions.Count, Is.EqualTo(1)); kernel.Release(sub); Assert.That(channel.Subscriptions, Is.Empty); } } /*----------------------------------------------------------------------------------------*/ } }
using System; using System.Messaging; using System.Threading; using Castle.MicroKernel.Registration; using Castle.Windsor; using Castle.Windsor.Configuration.Interpreters; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.LoadBalancer; using Rhino.ServiceBus.Messages; using Rhino.ServiceBus.Msmq; using Xunit; using MessageType = Rhino.ServiceBus.Transport.MessageType; using System.Linq; namespace Rhino.ServiceBus.Tests.LoadBalancer { public class With_fail_over : LoadBalancingTestBase { private readonly IWindsorContainer container; public With_fail_over() { var interpreter = new XmlInterpreter(@"LoadBalancer\BusWithLoadBalancer.config"); container = new WindsorContainer(interpreter); container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility()); container.Register( Component.For<MsmqLoadBalancer>() .DependsOn(new { threadCount = 1, endpoint = new Uri(loadBalancerQueue), secondaryLoadBalancer = TestQueueUri2.Uri, transactional = TransactionalOptions.FigureItOut }) ); } [Fact] public void when_start_load_balancer_that_has_secondary_will_start_sending_heartbeats_to_secondary() { using (var loadBalancer = container.Resolve<MsmqLoadBalancer>()) { loadBalancer.Start(); Message peek = testQueue2.Peek(TimeSpan.FromSeconds(30)); object[] msgs = container.Resolve<IMessageSerializer>().Deserialize(peek.BodyStream); Assert.IsType<Heartbeat>(msgs[0]); var beat = (Heartbeat)msgs[0]; Assert.Equal(loadBalancer.Endpoint.Uri, beat.From); } } [Fact] public void when_start_load_balancer_that_has_secondary_will_send_reroute_to_endpoints_to_relieve_secondary() { using (var loadBalancer = container.Resolve<MsmqLoadBalancer>()) { loadBalancer.KnownEndpoints.Add(TestQueueUri.Uri); loadBalancer.Start(); var message = queue.Receive(TimeSpan.FromSeconds(5)); var serializer = container.Resolve<IMessageSerializer>(); var reroute = serializer.Deserialize(message.BodyStream) .OfType<Reroute>().First(); Assert.Equal(loadBalancer.Endpoint.Uri, reroute.NewEndPoint); Assert.Equal(loadBalancer.Endpoint.Uri, reroute.OriginalEndPoint); } } [Fact] public void when_start_load_balancer_that_has_secondary_will_send_reroute_to_workers_to_relieve_secondary() { using (var loadBalancer = container.Resolve<MsmqLoadBalancer>()) { loadBalancer.KnownWorkers.Add(TestQueueUri.Uri); loadBalancer.Start(); var message = queue.Receive(TimeSpan.FromSeconds(5)); var serializer = container.Resolve<IMessageSerializer>(); var reroute = serializer.Deserialize(message.BodyStream) .OfType<Reroute>().First(); Assert.Equal(loadBalancer.Endpoint.Uri, reroute.NewEndPoint); Assert.Equal(loadBalancer.Endpoint.Uri, reroute.OriginalEndPoint); } } [Fact] public void When_Primary_loadBalacer_recieve_workers_it_sends_them_to_secondary_loadBalancer() { using (var loadBalancer = container.Resolve<MsmqLoadBalancer>()) using (var bus = container.Resolve<IStartableServiceBus>()) { var wait = new ManualResetEvent(false); int timesCalled = 0; loadBalancer.SentNewWorkerPersisted += () => { timesCalled += 1; //we get three ReadyToWork mesages, one from the bus itself //the other two from the mesages that we are explicitly sending. if (timesCalled == 3) wait.Set(); }; loadBalancer.Start(); bus.Start(); bus.Send(loadBalancer.Endpoint, new ReadyToWork { Endpoint = new Uri("msmq://app1/work1") }); bus.Send(loadBalancer.Endpoint, new ReadyToWork { Endpoint = new Uri("msmq://app1/work1") }); bus.Send(loadBalancer.Endpoint, new ReadyToWork { Endpoint = new Uri("msmq://app2/work1") }); wait.WaitOne(TimeSpan.FromSeconds(30), false); var messageSerializer = container.Resolve<IMessageSerializer>(); using (var workers = new MessageQueue(testQueuePath2, QueueAccessMode.SendAndReceive)) { int busUri = 0; int app1 = 0; int app2 = 0; foreach (Message msg in workers.GetAllMessages()) { object msgFromQueue = messageSerializer.Deserialize(msg.BodyStream)[0]; var newWorkerPersisted = msgFromQueue as NewWorkerPersisted; if (newWorkerPersisted == null) continue; if (newWorkerPersisted.Endpoint.ToString() == "msmq://app1/work1") app1 += 1; else if (newWorkerPersisted.Endpoint.ToString() == "msmq://app2/work1") app2 += 1; else if (newWorkerPersisted.Endpoint.ToString().ToLower().Replace(Environment.MachineName.ToLower(), "localhost") == bus.Endpoint.Uri.ToString().ToLower()) busUri += 1; } Assert.Equal(app1, 1); Assert.Equal(app2, 1); } } } [Fact] public void When_Primary_loadBalacer_recieve_endPoints_it_sends_them_to_secondary_loadBalancer() { using (var loadBalancer = container.Resolve<MsmqLoadBalancer>()) { var wait = new ManualResetEvent(false); int timesCalled = 0; loadBalancer.SentNewEndpointPersisted += () => { timesCalled += 1; if (timesCalled == 2) wait.Set(); }; loadBalancer.Start(); using (var loadBalancerMsmqQueue = MsmqUtil.GetQueuePath(loadBalancer.Endpoint).Open(QueueAccessMode.SendAndReceive)) { var queuePath = MsmqUtil.GetQueuePath(TestQueueUri2); loadBalancerMsmqQueue.Send(new Message { ResponseQueue = queuePath.Open().ToResponseQueue(), Body = "a" }); loadBalancerMsmqQueue.Send(new Message { ResponseQueue = queuePath.Open().ToResponseQueue(), Body = "a" }); queuePath = MsmqUtil.GetQueuePath(TransactionalTestQueueUri); loadBalancerMsmqQueue.Send(new Message { ResponseQueue = queuePath.Open().ToResponseQueue(), Body = "a" }); } wait.WaitOne(TimeSpan.FromSeconds(30), false); var messageSerializer = container.Resolve<IMessageSerializer>(); using (var workers = new MessageQueue(testQueuePath2, QueueAccessMode.SendAndReceive)) { int work1 = 0; int work2 = 0; foreach (Message msg in workers.GetAllMessages()) { object msgFromQueue = messageSerializer.Deserialize(msg.BodyStream)[0]; var newEndpointPersisted = msgFromQueue as NewEndpointPersisted; if (newEndpointPersisted == null) continue; var endpoint = newEndpointPersisted.PersistedEndpoint; if (endpoint == TestQueueUri2.Uri) work1 += 1; else if (endpoint == TransactionalTestQueueUri.Uri) work2 += 1; } Assert.Equal(work1, 1); Assert.Equal(work2, 1); } } } [Fact] public void When_Primary_loadBalacer_gets_SendAllKnownWorkersAndEndpoints_will_send_them() { using (var loadBalancer = container.Resolve<MsmqLoadBalancer>()) { loadBalancer.KnownWorkers.Add(new Uri("msmq://test1/bar")); loadBalancer.KnownWorkers.Add(new Uri("msmq://test2/bar")); loadBalancer.KnownEndpoints.Add(new Uri("msmq://test3/foo")); loadBalancer.KnownEndpoints.Add(new Uri("msmq://test4/foo")); testQueue2.Purge();// removing existing ones. SendMessageToBalancer(testQueue2, new QueryForAllKnownWorkersAndEndpoints()); var workers = loadBalancer.KnownWorkers.GetValues().ToList(); var endpoints = loadBalancer.KnownEndpoints.GetValues().ToList(); var messageSerializer = container.Resolve<IMessageSerializer>(); while (workers.Count == 0 && endpoints.Count == 0) { var transportMesage = testQueue2.Receive(TimeSpan.FromSeconds(30)); var msgs = messageSerializer.Deserialize(transportMesage.BodyStream); foreach (var msg in msgs) { if (msg is Heartbeat) continue; if(msg is NewEndpointPersisted) { endpoints.Remove(((NewEndpointPersisted) msg).PersistedEndpoint); } if(msg is NewWorkerPersisted) { workers.Remove(((NewWorkerPersisted) msg).Endpoint); } } } } } private void SendMessageToBalancer( MessageQueue reply, LoadBalancerMessage msg) { var messageSerializer = container.Resolve<IMessageSerializer>(); var message = new Message { ResponseQueue = reply, AppSpecific = (int)MessageType.LoadBalancerMessageMarker }; messageSerializer.Serialize(new[] { msg }, message.BodyStream); using (var q = new MessageQueue(loadBalancerQueuePath)) { q.Send(message); } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace Revit.SDK.Samples.CurtainWallGrid.CS { /// <summary> /// maintain the baseline of the curtain wall /// </summary> public class WallDrawing { #region Fields // zoom the baseline to a suitable length public double SCALEFACTOR = 5.0; // the boundary of the canvas for the baseline drawing Rectangle m_boundary; // the origin for the baseline (it's the center of the canvas) Point m_origin; // the referred parent wall geometry WallGeometry m_refGeometry; // store the document of this sample MyDocument m_myDocument; // the font used in drawing the baseline of the curtain wall Font m_coordinateFont; // the baseline of the curtain wall WallBaseline2D m_wallLine2D; #endregion #region Properties /// <summary> /// the boundary of the canvas for the baseline drawing /// </summary> public Rectangle Boundary { get { return m_boundary; } set { m_boundary = value; } } /// <summary> /// the origin for the baseline (it's the center of the canvas) /// </summary> public Point Origin { get { return m_origin; } set { m_origin = value; } } /// <summary> /// the baseline of the curtain wall /// </summary> public WallBaseline2D WallLine2D { get { return m_wallLine2D; } } #endregion #region Constructors /// <summary> /// default constructor /// </summary> /// <param name="wallGeo"> /// the mapped wall geometry information /// </param> public WallDrawing(WallGeometry wallGeo) { m_coordinateFont = new Font("Verdana", 10, FontStyle.Regular); m_wallLine2D = new WallBaseline2D(); m_myDocument = wallGeo.MyDocument; m_refGeometry = wallGeo; } #endregion #region Public methods /// <summary> /// Add point to baseline of the curtain wall /// </summary> /// <param name="mousePosition"> /// the location of the mouse cursor /// </param> public void AddPoint(Point mousePosition) { // both end points of the baseline specified, can't add more points if (Point.Empty != m_wallLine2D.StartPoint && Point.Empty != m_wallLine2D.EndPoint) { return; } // start point isn't specified, specify it if (Point.Empty == m_wallLine2D.StartPoint) { m_wallLine2D.StartPoint = mousePosition; m_refGeometry.StartPointD = ConvertToPointD(mousePosition); } // start point specified, end point isn't, so specify the end point else if (Point.Empty == m_wallLine2D.EndPoint) { // don't let the length of the 2 points too small if (Math.Abs(m_wallLine2D.StartPoint.X - mousePosition.X) >= 2 || Math.Abs(m_wallLine2D.StartPoint.Y - mousePosition.Y) >= 2) { m_wallLine2D.EndPoint = mousePosition; m_refGeometry.EndPointD = ConvertToPointD(mousePosition); m_wallLine2D.AssistantPoint = Point.Empty; } } } /// <summary> /// store mouse position when mouse moves (the location will be the candidate end points of the baseline) /// </summary> /// <param name="mousePosition"> /// the location of the mouse cursor /// </param> public void AddMousePosition(Point mousePosition) { // both endpoints for the baseline have been confirmed, no need to record the mouse location if (Point.Empty != m_wallLine2D.StartPoint && Point.Empty != m_wallLine2D.EndPoint) { return; } // we just start to draw the baseline, no end points are specified // or just the start point was specified, so the mouse position will be the "candidate end point" m_wallLine2D.AssistantPoint = mousePosition; } /// <summary> /// draw the baseline for the curtain wall creation in the picture box /// in the "Create Curtain Wall" tab page, user needs to draw the baseline for wall creation /// </summary> /// <param name="graphics"> /// form graphic /// </param> /// <param name="pen"> /// pen used to draw line in pictureBox /// </param> public void Draw(Graphics graphics, Pen pen) { // draw the coordinate system origin DrawCoordinateOrigin(graphics, pen); // draw the baseline DrawBaseline(graphics, pen); } /// <summary> /// Clear points in baseline /// </summary> public void RemovePoints() { m_wallLine2D.Clear(); } #endregion #region Private methods /// <summary> /// scale the point and store them in PointD format /// </summary> /// <param name="srcPoint"> /// the point to-be-zoomed /// </param> /// <returns> /// the scaled result point /// </returns> private PointD ConvertToPointD(Point srcPoint) { double x = -1; double y = -1; x = srcPoint.X - m_origin.X; y = m_origin.Y - srcPoint.Y; x /= SCALEFACTOR; y /= SCALEFACTOR; return new PointD(x, y); } /// <summary> /// draw the coordinate system origin for the baseline drawing /// </summary> /// <param name="graphics"> /// form graphic /// </param> /// <param name="pen"> /// pen used to draw line in pictureBox /// </param> private void DrawCoordinateOrigin(Graphics graphics, Pen pen) { // draw the coordinate system origin graphics.DrawLine(pen, new Point(m_origin.X - 10, m_origin.Y), new Point(m_origin.X + 10, m_origin.Y)); graphics.DrawLine(pen, new Point(m_origin.X, m_origin.Y - 10), new Point(m_origin.X, m_origin.Y + 10)); graphics.DrawString("(0,0)", m_coordinateFont, Brushes.Blue, new PointF(m_origin.X + 2, m_origin.Y + 2)); } /// <summary> /// draw the baseline / the candidate baseline (start point confirmed, end point didn't) /// </summary> /// <param name="graphics"> /// form graphic /// </param> /// <param name="pen"> /// pen used to draw line in pictureBox /// </param> private void DrawBaseline(Graphics graphics, Pen pen) { if (Point.Empty != m_wallLine2D.AssistantPoint) { if (Point.Empty != m_wallLine2D.StartPoint) { graphics.DrawLine(pen, m_wallLine2D.StartPoint, m_wallLine2D.AssistantPoint); } // show the real-time coordinate of the mouse position WriteCoordinate(graphics, pen); } if (Point.Empty != m_wallLine2D.EndPoint && Point.Empty != m_wallLine2D.EndPoint) { graphics.DrawLine(pen, m_wallLine2D.StartPoint, m_wallLine2D.EndPoint); } } /// <summary> /// write the coordinate for moving mouse /// </summary> /// <param name="graphics"> /// form graphic /// </param> /// <param name="pen"> /// pen used to draw line in pictureBox /// </param> private void WriteCoordinate(Graphics graphics, Pen pen) { PointD assistPointD = ConvertToPointD(m_wallLine2D.AssistantPoint); double x = Unit.CovertFromAPI(m_myDocument.LengthUnitType, assistPointD.X); double y = Unit.CovertFromAPI(m_myDocument.LengthUnitType, assistPointD.Y); string xCoorString = Convert.ToString(Math.Round(x, 1)); string yCoorString = Convert.ToString(Math.Round(y, 1)); string unitType = Properties.Resources.ResourceManager.GetString(m_myDocument.LengthUnitType.ToString()); String coordinate = "(" + xCoorString + unitType + "," + yCoorString + unitType + ")"; graphics.DrawString(coordinate, m_coordinateFont, Brushes.Blue, new PointF(m_wallLine2D.AssistantPoint.X + 2, m_wallLine2D.AssistantPoint.Y + 2)); } #endregion } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Tests { /// <remarks>Check that cipher input/output streams are working correctly</remarks> [TestFixture] public class CipherStreamTest : SimpleTest { private static readonly byte[] RK = Hex.Decode("0123456789ABCDEF"); private static readonly byte[] RIN = Hex.Decode("4e6f772069732074"); private static readonly byte[] ROUT = Hex.Decode("3afbb5c77938280d"); private static byte[] SIN = Hex.Decode( "00000000000000000000000000000000" + "00000000000000000000000000000000" + "00000000000000000000000000000000" + "00000000000000000000000000000000"); private static readonly byte[] SK = Hex.Decode("80000000000000000000000000000000"); private static readonly byte[] SIV = Hex.Decode("0000000000000000"); private static readonly byte[] SOUT = Hex.Decode( "4DFA5E481DA23EA09A31022050859936" + "DA52FCEE218005164F267CB65F5CFD7F" + "2B4F97E0FF16924A52DF269515110A07" + "F9E460BC65EF95DA58F740B7D1DBB0AA"); private static readonly byte[] HCIN = new byte[64]; private static readonly byte[] HCIV = new byte[32]; private static readonly byte[] HCK256A = new byte[32]; private static readonly byte[] HC256A = Hex.Decode( "5B078985D8F6F30D42C5C02FA6B67951" + "53F06534801F89F24E74248B720B4818" + "CD9227ECEBCF4DBF8DBF6977E4AE14FA" + "E8504C7BC8A9F3EA6C0106F5327E6981"); private static readonly byte[] HCK128A = new byte[16]; private static readonly byte[] HC128A = Hex.Decode( "82001573A003FD3B7FD72FFB0EAF63AA" + "C62F12DEB629DCA72785A66268EC758B" + "1EDB36900560898178E0AD009ABF1F49" + "1330DC1C246E3D6CB264F6900271D59C"); private void doRunTest( string name, int ivLength) { string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789"; string baseName = name; if (name.IndexOf('/') >= 0) { baseName = name.Substring(0, name.IndexOf('/')); } CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName); IBufferedCipher inCipher = CipherUtilities.GetCipher(name); IBufferedCipher outCipher = CipherUtilities.GetCipher(name); KeyParameter key = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey()); MemoryStream bIn = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false); MemoryStream bOut = new MemoryStream(); // In the Java build, this IV would be implicitly created and then retrieved with getIV() ICipherParameters cipherParams = key; if (ivLength > 0) { cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]); } inCipher.Init(true, cipherParams); // TODO Should we provide GetIV() method on IBufferedCipher? //if (inCipher.getIV() != null) //{ // outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV())); //} //else //{ // outCipher.Init(false, key); //} outCipher.Init(false, cipherParams); CipherStream cIn = new CipherStream(bIn, inCipher, null); CipherStream cOut = new CipherStream(bOut, null, outCipher); int c; while ((c = cIn.ReadByte()) >= 0) { cOut.WriteByte((byte)c); } cIn.Close(); cOut.Flush(); cOut.Close(); byte[] bs = bOut.ToArray(); string res = Encoding.ASCII.GetString(bs, 0, bs.Length); if (!res.Equals(lCode)) { Fail("Failed - decrypted data doesn't match."); } } private void doTestAlgorithm( string name, byte[] keyBytes, byte[] iv, byte[] plainText, byte[] cipherText) { KeyParameter key = ParameterUtilities.CreateKeyParameter(name, keyBytes); IBufferedCipher inCipher = CipherUtilities.GetCipher(name); IBufferedCipher outCipher = CipherUtilities.GetCipher(name); if (iv != null) { inCipher.Init(true, new ParametersWithIV(key, iv)); outCipher.Init(false, new ParametersWithIV(key, iv)); } else { inCipher.Init(true, key); outCipher.Init(false, key); } byte[] enc = inCipher.DoFinal(plainText); if (!AreEqual(enc, cipherText)) { Fail(name + ": cipher text doesn't match"); } byte[] dec = outCipher.DoFinal(enc); if (!AreEqual(dec, plainText)) { Fail(name + ": plain text doesn't match"); } } private void doTestException( string name, int ivLength) { try { byte[] key128 = { (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143 }; byte[] key256 = { (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143, (byte)128, (byte)131, (byte)133, (byte)134, (byte)137, (byte)138, (byte)140, (byte)143 }; byte[] keyBytes; if (name.Equals("HC256")) { keyBytes = key256; } else { keyBytes = key128; } KeyParameter cipherKey = ParameterUtilities.CreateKeyParameter(name, keyBytes); ICipherParameters cipherParams = cipherKey; if (ivLength > 0) { cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]); } IBufferedCipher ecipher = CipherUtilities.GetCipher(name); ecipher.Init(true, cipherParams); byte[] cipherText = new byte[0]; try { // According specification Method engineUpdate(byte[] input, // int inputOffset, int inputLen, byte[] output, int // outputOffset) // throws ShortBufferException - if the given output buffer is // too // small to hold the result ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0); // Fail("failed exception test - no ShortBufferException thrown"); Fail("failed exception test - no DataLengthException thrown"); } // catch (ShortBufferException e) catch (DataLengthException) { // ignore } // NB: The lightweight engine doesn't take public/private keys // try // { // IBufferedCipher c = CipherUtilities.GetCipher(name); // // // Key k = new PublicKey() // // { // // // // public string getAlgorithm() // // { // // return "STUB"; // // } // // // // public string getFormat() // // { // // return null; // // } // // // // public byte[] getEncoded() // // { // // return null; // // } // // // // }; // AsymmetricKeyParameter k = new AsymmetricKeyParameter(false); // c.Init(true, k); // // Fail("failed exception test - no InvalidKeyException thrown for public key"); // } // catch (InvalidKeyException) // { // // okay // } // // try // { // IBufferedCipher c = CipherUtilities.GetCipher(name); // // // Key k = new PrivateKey() // // { // // // // public string getAlgorithm() // // { // // return "STUB"; // // } // // // // public string getFormat() // // { // // return null; // // } // // // // public byte[] getEncoded() // // { // // return null; // // } // // // // }; // // AsymmetricKeyParameter k = new AsymmetricKeyParameter(true); // c.Init(false, k); // // Fail("failed exception test - no InvalidKeyException thrown for private key"); // } // catch (InvalidKeyException) // { // // okay // } } catch (Exception e) { Fail("unexpected exception.", e); } } [Test] public void TestRC4() { doRunTest("RC4", 0); } [Test] public void TestRC4Exception() { doTestException("RC4", 0); } [Test] public void TestRC4Algorithm() { doTestAlgorithm("RC4", RK, null, RIN, ROUT); } [Test] public void TestSalsa20() { doRunTest("Salsa20", 8); } [Test] public void TestSalsa20Exception() { doTestException("Salsa20", 8); } [Test] public void TestSalsa20Algorithm() { doTestAlgorithm("Salsa20", SK, SIV, SIN, SOUT); } [Test] public void TestHC128() { doRunTest("HC128", 16); } [Test] public void TestHC128Exception() { doTestException("HC128", 16); } [Test] public void TestHC128Algorithm() { doTestAlgorithm("HC128", HCK128A, HCIV, HCIN, HC128A); } [Test] public void TestHC256() { doRunTest("HC256", 32); } [Test] public void TestHC256Exception() { doTestException("HC256", 32); } [Test] public void TestHC256Algorithm() { doTestAlgorithm("HC256", HCK256A, HCIV, HCIN, HC256A); } [Test] public void TestVmpc() { doRunTest("VMPC", 16); } [Test] public void TestVmpcException() { doTestException("VMPC", 16); } // [Test] // public void TestVmpcAlgorithm() // { // doTestAlgorithm("VMPC", a, iv, in, a); // } [Test] public void TestVmpcKsa3() { doRunTest("VMPC-KSA3", 16); } [Test] public void TestVmpcKsa3Exception() { doTestException("VMPC-KSA3", 16); } // [Test] // public void TestVmpcKsa3Algorithm() // { // doTestAlgorithm("VMPC-KSA3", a, iv, in, a); // } [Test] public void TestDesEcbPkcs7() { doRunTest("DES/ECB/PKCS7Padding", 0); } [Test] public void TestDesCfbNoPadding() { doRunTest("DES/CFB8/NoPadding", 0); } public override void PerformTest() { TestRC4(); TestRC4Exception(); TestRC4Algorithm(); TestSalsa20(); TestSalsa20Exception(); TestSalsa20Algorithm(); TestHC128(); TestHC128Exception(); TestHC128Algorithm(); TestHC256(); TestHC256Exception(); TestHC256Algorithm(); TestVmpc(); TestVmpcException(); // TestVmpcAlgorithm(); TestVmpcKsa3(); TestVmpcKsa3Exception(); // TestVmpcKsa3Algorithm(); TestDesEcbPkcs7(); TestDesCfbNoPadding(); } public override string Name { get { return "CipherStreamTest"; } } public static void Main( string[] args) { RunTest(new CipherStreamTest()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; 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.Core; using Orleans.GrainDirectory; using Orleans.Runtime.Configuration; using Orleans.Runtime.Scheduler; using Orleans.Storage; namespace Orleans.Runtime { /// <summary> /// Maintains additional per-activation state that is required for Orleans internal operations. /// MUST lock this object for any concurrent access /// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc. /// </summary> internal class ActivationData : IGrainActivationContext, IActivationData, IInvokable, IDisposable { // This class is used for activations that have extension invokers. It keeps a dictionary of // invoker objects to use with the activation, and extend the default invoker // defined for the grain class. // Note that in all cases we never have more than one copy of an actual invoker; // we may have a ExtensionInvoker per activation, in the worst case. private class ExtensionInvoker : IGrainMethodInvoker, IGrainExtensionMap { // Because calls to ExtensionInvoker are allways made within the activation context, // we rely on the single-threading guarantee of the runtime and do not protect the map with a lock. private Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>> extensionMap; // key is the extension interface ID /// <summary> /// Try to add an extension for the specific interface ID. /// Fail and return false if there is already an extension for that interface ID. /// Note that if an extension invoker handles multiple interface IDs, it can only be associated /// with one of those IDs when added, and so only conflicts on that one ID will be detected and prevented. /// </summary> /// <param name="invoker"></param> /// <param name="handler"></param> /// <returns></returns> internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension handler) { if (extensionMap == null) { extensionMap = new Dictionary<int, Tuple<IGrainExtension, IGrainExtensionMethodInvoker>>(1); } if (extensionMap.ContainsKey(invoker.InterfaceId)) return false; extensionMap.Add(invoker.InterfaceId, new Tuple<IGrainExtension, IGrainExtensionMethodInvoker>(handler, invoker)); return true; } /// <summary> /// Removes all extensions for the specified interface id. /// Returns true if the chained invoker no longer has any extensions and may be safely retired. /// </summary> /// <param name="extension"></param> /// <returns>true if the chained invoker is now empty, false otherwise</returns> public bool Remove(IGrainExtension extension) { int interfaceId = 0; foreach(int iface in extensionMap.Keys) if (extensionMap[iface].Item1 == extension) { interfaceId = iface; break; } if (interfaceId == 0) // not found throw new InvalidOperationException(String.Format("Extension {0} is not installed", extension.GetType().FullName)); extensionMap.Remove(interfaceId); return extensionMap.Count == 0; } public bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result) { result = null; if (extensionMap == null) return false; foreach (var ext in extensionMap.Values) if (extensionType == ext.Item1.GetType()) { result = ext.Item1; return true; } return false; } /// <summary> /// Invokes the appropriate grain or extension method for the request interface ID and method ID. /// First each extension invoker is tried; if no extension handles the request, then the base /// invoker is used to handle the request. /// The base invoker will throw an appropriate exception if the request is not recognized. /// </summary> /// <param name="grain"></param> /// <param name="request"></param> /// <returns></returns> public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request) { if (extensionMap == null || !extensionMap.ContainsKey(request.InterfaceId)) throw new InvalidOperationException( String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", request.InterfaceId)); var invoker = extensionMap[request.InterfaceId].Item2; var extension = extensionMap[request.InterfaceId].Item1; return invoker.Invoke(extension, request); } public bool IsExtensionInstalled(int interfaceId) { return extensionMap != null && extensionMap.ContainsKey(interfaceId); } public int InterfaceId { get { return 0; } // 0 indicates an extension invoker that may have multiple intefaces inplemented by extensions. } public ushort InterfaceVersion { get { return 0; } } /// <summary> /// Gets the extension from this instance if it is available. /// </summary> /// <param name="interfaceId">The interface id.</param> /// <param name="extension">The extension.</param> /// <returns> /// <see langword="true"/> if the extension is found, <see langword="false"/> otherwise. /// </returns> public bool TryGetExtension(int interfaceId, out IGrainExtension extension) { Tuple<IGrainExtension, IGrainExtensionMethodInvoker> value; if (extensionMap != null && extensionMap.TryGetValue(interfaceId, out value)) { extension = value.Item1; } else { extension = null; } return extension != null; } } internal class GrainActivationContextFactory { public IGrainActivationContext Context { get; set; } } // This is the maximum amount of time we expect a request to continue processing private readonly TimeSpan maxRequestProcessingTime; private readonly TimeSpan maxWarningRequestProcessingTime; private readonly SiloMessagingOptions messagingOptions; public readonly TimeSpan CollectionAgeLimit; private readonly ILogger logger; private IGrainMethodInvoker lastInvoker; private IServiceScope serviceScope; private HashSet<IGrainTimer> timers; public ActivationData( ActivationAddress addr, string genericArguments, PlacementStrategy placedUsing, IMultiClusterRegistrationStrategy registrationStrategy, IActivationCollector collector, TimeSpan ageLimit, IOptions<SiloMessagingOptions> messagingOptions, TimeSpan maxWarningRequestProcessingTime, TimeSpan maxRequestProcessingTime, IRuntimeClient runtimeClient, ILoggerFactory loggerFactory) { if (null == addr) throw new ArgumentNullException(nameof(addr)); if (null == placedUsing) throw new ArgumentNullException(nameof(placedUsing)); if (null == collector) throw new ArgumentNullException(nameof(collector)); logger = loggerFactory.CreateLogger<ActivationData>(); this.lifecycle = new GrainLifecycle(loggerFactory.CreateLogger<LifecycleSubject>()); this.maxRequestProcessingTime = maxRequestProcessingTime; this.maxWarningRequestProcessingTime = maxWarningRequestProcessingTime; this.messagingOptions = messagingOptions.Value; ResetKeepAliveRequest(); Address = addr; State = ActivationState.Create; PlacedUsing = placedUsing; RegistrationStrategy = registrationStrategy; if (!Grain.IsSystemTarget && !Constants.IsSystemGrain(Grain)) { this.collector = collector; } CollectionAgeLimit = ageLimit; GrainReference = GrainReference.FromGrainId(addr.Grain, runtimeClient.GrainReferenceRuntime, genericArguments, Grain.IsSystemTarget ? addr.Silo : null); this.SchedulingContext = new SchedulingContext(this); } public Type GrainType => GrainTypeData.Type; public IGrainIdentity GrainIdentity => this.Identity; public IServiceProvider ActivationServices => this.serviceScope.ServiceProvider; #region Method invocation private ExtensionInvoker extensionInvoker; public IGrainMethodInvoker GetInvoker(GrainTypeManager typeManager, int interfaceId, string genericGrainType = null) { // Return previous cached invoker, if applicable if (lastInvoker != null && interfaceId == lastInvoker.InterfaceId) // extension invoker returns InterfaceId==0, so this condition will never be true if an extension is installed return lastInvoker; if (extensionInvoker != null && extensionInvoker.IsExtensionInstalled(interfaceId)) { // Shared invoker for all extensions installed on this grain lastInvoker = extensionInvoker; } else { // Find the specific invoker for this interface / grain type lastInvoker = typeManager.GetInvoker(interfaceId, genericGrainType); } return lastInvoker; } internal bool TryAddExtension(IGrainExtensionMethodInvoker invoker, IGrainExtension extension) { if(extensionInvoker == null) extensionInvoker = new ExtensionInvoker(); return extensionInvoker.TryAddExtension(invoker, extension); } internal void RemoveExtension(IGrainExtension extension) { if (extensionInvoker != null) { if (extensionInvoker.Remove(extension)) extensionInvoker = null; } else throw new InvalidOperationException("Grain extensions not installed."); } internal bool TryGetExtensionHandler(Type extensionType, out IGrainExtension result) { result = null; return extensionInvoker != null && extensionInvoker.TryGetExtensionHandler(extensionType, out result); } #endregion public HashSet<ActivationId> RunningRequestsSenders { get; } = new HashSet<ActivationId>(); public ISchedulingContext SchedulingContext { get; } public string GrainTypeName { get { if (GrainInstanceType == null) { throw new ArgumentNullException("GrainInstanceType", "GrainInstanceType has not been set."); } return GrainInstanceType.FullName; } } internal Type GrainInstanceType => GrainTypeData?.Type; internal void SetGrainInstance(Grain grainInstance) { GrainInstance = grainInstance; } internal void SetupContext(GrainTypeData typeData, IServiceProvider grainServices) { this.GrainTypeData = typeData; this.Items = new Dictionary<object, object>(); this.serviceScope = grainServices.CreateScope(); SetGrainActivationContextInScopedServices(this.ActivationServices, this); if (typeData != null) { var grainType = typeData.Type; // Don't ever collect system grains or reminder table grain or memory store grains. bool doNotCollect = typeof(IReminderTableGrain).IsAssignableFrom(grainType) || typeof(IMemoryStorageGrain).IsAssignableFrom(grainType); if (doNotCollect) { this.collector = null; } } } private static void SetGrainActivationContextInScopedServices(IServiceProvider sp, IGrainActivationContext context) { var contextFactory = sp.GetRequiredService<GrainActivationContextFactory>(); contextFactory.Context = context; } private Streams.StreamDirectory streamDirectory; internal Streams.StreamDirectory GetStreamDirectory() { return streamDirectory ?? (streamDirectory = new Streams.StreamDirectory()); } internal bool IsUsingStreams { get { return streamDirectory != null; } } internal async Task DeactivateStreamResources() { if (streamDirectory == null) return; // No streams - Nothing to do. if (extensionInvoker == null) return; // No installed extensions - Nothing to do. if (StreamResourceTestControl.TestOnlySuppressStreamCleanupOnDeactivate) { logger.Warn(0, "Suppressing cleanup of stream resources during tests for {0}", this); return; } await streamDirectory.Cleanup(true, false); } #region IActivationData GrainReference IActivationData.GrainReference { get { return GrainReference; } } public GrainId Identity { get { return Grain; } } public GrainTypeData GrainTypeData { get; private set; } public Grain GrainInstance { get; private set; } public ActivationId ActivationId { get { return Address.Activation; } } public ActivationAddress Address { get; private set; } public IServiceProvider ServiceProvider => this.serviceScope?.ServiceProvider; public IDictionary<object, object> Items { get; private set; } private readonly GrainLifecycle lifecycle; public IGrainLifecycle ObservableLifecycle => lifecycle; internal ILifecycleObserver Lifecycle => lifecycle; public void OnTimerCreated(IGrainTimer timer) { AddTimer(timer); } #endregion #region Catalog internal readonly GrainReference GrainReference; public SiloAddress Silo { get { return Address.Silo; } } public GrainId Grain { get { return Address.Grain; } } public ActivationState State { get; private set; } public void SetState(ActivationState state) { State = state; } // Don't accept any new messages and stop all timers. public void PrepareForDeactivation() { SetState(ActivationState.Deactivating); deactivationStartTime = DateTime.UtcNow; StopAllTimers(); } /// <summary> /// If State == Invalid, this may contain a forwarding address for incoming messages /// </summary> public ActivationAddress ForwardingAddress { get; set; } private IActivationCollector collector; internal bool IsExemptFromCollection { get { return collector == null; } } public DateTime CollectionTicket { get; private set; } private bool collectionCancelledFlag; public bool TrySetCollectionCancelledFlag() { lock (this) { if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false; collectionCancelledFlag = true; return true; } } public void ResetCollectionCancelledFlag() { lock (this) { collectionCancelledFlag = false; } } public void ResetCollectionTicket() { CollectionTicket = default(DateTime); } public void SetCollectionTicket(DateTime ticket) { if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket"); if (CollectionTicket != default(DateTime)) { throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket."); } CollectionTicket = ticket; } #endregion #region Dispatcher public PlacementStrategy PlacedUsing { get; private set; } public IMultiClusterRegistrationStrategy RegistrationStrategy { get; private set; } // Currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy. internal bool IsStatelessWorker { get { return PlacedUsing is StatelessWorkerPlacement; } } // Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker. internal bool IsUsingGrainDirectory { get { return !IsStatelessWorker; } } public Message Running { get; private set; } // the number of requests that are currently executing on this activation. // includes reentrant and non-reentrant requests. private int numRunning; private DateTime currentRequestStartTime; private DateTime becameIdle; private DateTime deactivationStartTime; public void RecordRunning(Message message) { // Note: This method is always called while holding lock on this activation, so no need for additional locks here numRunning++; if (message.Direction != Message.Directions.OneWay && message.SendingActivation != null && !message.SendingGrain?.IsClient == true) { RunningRequestsSenders.Add(message.SendingActivation); } if (Running != null) return; // This logic only works for non-reentrant activations // Consider: Handle long request detection for reentrant activations. Running = message; currentRequestStartTime = DateTime.UtcNow; } public void ResetRunning(Message message) { // Note: This method is always called while holding lock on this activation, so no need for additional locks here numRunning--; RunningRequestsSenders.Remove(message.SendingActivation); if (numRunning == 0) { becameIdle = DateTime.UtcNow; if (!IsExemptFromCollection) { collector.TryRescheduleCollection(this); } } // The below logic only works for non-reentrant activations. if (Running != null && !message.Equals(Running)) return; Running = null; currentRequestStartTime = DateTime.MinValue; } private long inFlightCount; private long enqueuedOnDispatcherCount; /// <summary> /// Number of messages that are actively being processed [as opposed to being in the Waiting queue]. /// In most cases this will be 0 or 1, but for Reentrant grains can be >1. /// </summary> public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } } /// <summary> /// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed]. /// </summary> public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } } /// <summary>Increment the number of in-flight messages currently being processed.</summary> public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); } /// <summary>Decrement the number of in-flight messages currently being processed.</summary> public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); } /// <summary>Increment the number of messages currently in the prcess of being received.</summary> public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); } /// <summary>Decrement the number of messages currently in the prcess of being received.</summary> public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); } /// <summary> /// grouped by sending activation: responses first, then sorted by id /// </summary> private List<Message> waiting; public int WaitingCount { get { return waiting == null ? 0 : waiting.Count; } } public enum EnqueueMessageResult { Success, ErrorInvalidActivation, ErrorStuckActivation, } /// <summary> /// Insert in a FIFO order /// </summary> /// <param name="message"></param> public EnqueueMessageResult EnqueueMessage(Message message) { lock (this) { if (State == ActivationState.Invalid) { logger.Warn(ErrorCode.Dispatcher_InvalidActivation, "Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message); return EnqueueMessageResult.ErrorInvalidActivation; } if (State == ActivationState.Deactivating) { var deactivatingTime = DateTime.UtcNow - deactivationStartTime; if (deactivatingTime > maxRequestProcessingTime) { logger.Error(ErrorCode.Dispatcher_StuckActivation, $"Current activation {ToDetailedString()} marked as Deactivating for {deactivatingTime}. Trying to enqueue {message}."); return EnqueueMessageResult.ErrorStuckActivation; } } if (Running != null) { var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime; if (currentRequestActiveTime > maxRequestProcessingTime) { logger.Error(ErrorCode.Dispatcher_StuckActivation, $"Current request has been active for {currentRequestActiveTime} for activation {ToDetailedString()}. Currently executing {Running}. Trying to enqueue {message}."); return EnqueueMessageResult.ErrorStuckActivation; } // Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations else if (currentRequestActiveTime > maxWarningRequestProcessingTime) { logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing, "Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.", currentRequestActiveTime, this.ToDetailedString(), Running, message); } } waiting = waiting ?? new List<Message>(); waiting.Add(message); return EnqueueMessageResult.Success; } } /// <summary> /// Check whether this activation is overloaded. /// Returns LimitExceededException if overloaded, otherwise <c>null</c>c> /// </summary> /// <param name="log">Logger to use for reporting any overflow condition</param> /// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns> public LimitExceededException CheckOverloaded(ILogger log) { string limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS; int maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit; int maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit; if (IsStatelessWorker) { limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER; maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit_StatelessWorker; maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit_StatelessWorker; } if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set int count = GetRequestCount(); if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit { log.Warn(ErrorCode.Catalog_Reject_ActivationTooManyRequests, String.Format("Overload - {0} enqueued requests for activation {1}, exceeding hard limit rejection threshold of {2}", count, this, maxRequestsHardLimit)); return new LimitExceededException(limitName, count, maxRequestsHardLimit, this.ToString()); } if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit { log.Warn(ErrorCode.Catalog_Warn_ActivationTooManyRequests, String.Format("Hot - {0} enqueued requests for activation {1}, exceeding soft limit warning threshold of {2}", count, this, maxRequestsSoftLimit)); return null; } return null; } internal int GetRequestCount() { lock (this) { long numInDispatcher = EnqueuedOnDispatcherCount; long numActive = InFlightCount; long numWaiting = WaitingCount; return (int)(numInDispatcher + numActive + numWaiting); } } public Message PeekNextWaitingMessage() { if (waiting != null && waiting.Count > 0) return waiting[0]; return null; } public void DequeueNextWaitingMessage() { if (waiting != null && waiting.Count > 0) waiting.RemoveAt(0); } internal List<Message> DequeueAllWaitingMessages() { lock (this) { if (waiting == null) return null; List<Message> tmp = waiting; waiting = null; return tmp; } } #endregion #region Activation collection public bool IsInactive { get { return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0); } } public bool IsCurrentlyExecuting { get { return numRunning > 0 ; } } /// <summary> /// Returns how long this activation has been idle. /// </summary> public TimeSpan GetIdleness(DateTime now) { if (now == default(DateTime)) throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now"); return now - becameIdle; } /// <summary> /// Returns whether this activation has been idle long enough to be collected. /// </summary> public bool IsStale(DateTime now) { return GetIdleness(now) >= CollectionAgeLimit; } private DateTime keepAliveUntil; public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } } public void DelayDeactivation(TimeSpan timespan) { if (timespan <= TimeSpan.Zero) { // reset any current keepAliveUntill ResetKeepAliveRequest(); } else if (timespan == TimeSpan.MaxValue) { // otherwise creates negative time. keepAliveUntil = DateTime.MaxValue; } else { keepAliveUntil = DateTime.UtcNow + timespan; } } public void ResetKeepAliveRequest() { keepAliveUntil = DateTime.MinValue; } public List<Action> OnInactive { get; set; } // ActivationData public void AddOnInactive(Action action) // ActivationData { lock (this) { if (OnInactive == null) { OnInactive = new List<Action>(); } OnInactive.Add(action); } } public void RunOnInactive() { lock (this) { if (OnInactive == null) return; var actions = OnInactive; OnInactive = null; foreach (var action in actions) { action(); } } } #endregion #region In-grain Timers internal void AddTimer(IGrainTimer timer) { lock(this) { if (timers == null) { timers = new HashSet<IGrainTimer>(); } timers.Add(timer); } } private void StopAllTimers() { lock (this) { if (timers == null) return; foreach (var timer in timers) { timer.Stop(); } } } public void OnTimerDisposed(IGrainTimer orleansTimerInsideGrain) { lock (this) // need to lock since dispose can be called on finalizer thread, outside garin context (not single threaded). { timers.Remove(orleansTimerInsideGrain); } } internal Task WaitForAllTimersToFinish() { lock(this) { if (timers == null) { return Task.CompletedTask; } var tasks = new List<Task>(); var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set. foreach (var timer in timerCopy) { // first call dispose, then wait to finish. Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown"); tasks.Add(timer.GetCurrentlyExecutingTickTask()); } return Task.WhenAll(tasks); } } #endregion #region Printing functions public string DumpStatus() { var sb = new StringBuilder(); lock (this) { sb.AppendFormat(" {0}", ToDetailedString()); if (Running != null) { sb.AppendFormat(" Processing message: {0}", Running); } if (waiting!=null && waiting.Count > 0) { sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue()); } } return sb.ToString(); } public override string ToString() { return String.Format("[Activation: {0}{1}{2}{3} State={4}]", Silo, Grain, ActivationId, GetActivationInfoString(), State); } internal string ToDetailedString(bool includeExtraDetails = false) { return String.Format( "[Activation: {0}{1}{2}{3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]", Silo.ToLongString(), Grain.ToDetailedString(), ActivationId, GetActivationInfoString(), State, // 4 WaitingCount, // 5 NonReentrancyQueueSize EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher InFlightCount, // 7 InFlightCount numRunning, // 8 NumRunning GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan CollectionAgeLimit, // 10 CollectionAgeLimit (includeExtraDetails && Running != null) ? " CurrentlyExecuting=" + Running : ""); // 11: Running } public string Name { get { return String.Format("[Activation: {0}{1}{2}{3}]", Silo, Grain, ActivationId, GetActivationInfoString()); } } /// <summary> /// Return string containing dump of the queue of waiting work items /// </summary> /// <returns></returns> /// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks> internal string PrintWaitingQueue() { return Utils.EnumerableToString(waiting); } private string GetActivationInfoString() { var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty; return GrainInstanceType == null ? placement : String.Format(" #GrainType={0} Placement={1}", GrainInstanceType.FullName, placement); } #endregion public void Dispose() { IDisposable disposable = serviceScope; if (disposable != null) disposable.Dispose(); this.serviceScope = null; } } internal static class StreamResourceTestControl { internal static bool TestOnlySuppressStreamCleanupOnDeactivate; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using Keen.Core; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace Keen.Test { [TestFixture] public class ScopedKeyTest : TestBase { [Test] public void Encrypt_32CharKey_Success() { Assert.DoesNotThrow(() => ScopedKey.Encrypt("0123456789abcdef0123456789abcdef", null)); } [Test] public void Encrypt_64CharKey_Success() { Assert.DoesNotThrow(() => ScopedKey.Encrypt("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", null)); } [Test] public void Encrypt_32CharKeyWithFilter_Success() { var settings = new ProjectSettingsProvider("projId", "0123456789abcdef0123456789abcdef"); IDictionary<string, object> filter = new ExpandoObject(); filter.Add("property_name", "account_id"); filter.Add("operator", "eq"); filter.Add("property_value", 123); dynamic secOpsIn = new ExpandoObject(); secOpsIn.filters = new List<object>() { filter }; secOpsIn.allowed_operations = new List<string>() { "read" }; Assert.DoesNotThrow(() => { var scopedKey = ScopedKey.Encrypt(settings.MasterKey, (object)secOpsIn); var decrypted = ScopedKey.Decrypt(settings.MasterKey, scopedKey); var secOpsOut = JObject.Parse(decrypted); Assert.True(secOpsIn.allowed_operations[0] == (string)(secOpsOut["allowed_operations"].First())); }); } [Test] public void Encrypt_64CharKeyWithFilter_Success() { var settings = new ProjectSettingsProvider("projId", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); IDictionary<string, object> filter = new ExpandoObject(); filter.Add("property_name", "account_id"); filter.Add("operator", "eq"); filter.Add("property_value", 123); dynamic secOpsIn = new ExpandoObject(); secOpsIn.filters = new List<object>() { filter }; secOpsIn.allowed_operations = new List<string>() { "read" }; Assert.DoesNotThrow(() => { var scopedKey = ScopedKey.Encrypt(settings.MasterKey, (object)secOpsIn); var decrypted = ScopedKey.Decrypt(settings.MasterKey, scopedKey); var secOpsOut = JObject.Parse(decrypted); Assert.True(secOpsIn.allowed_operations[0] == (string)(secOpsOut["allowed_operations"].First())); }); } [Test] public void Encrypt_NullObject_Success() { Assert.DoesNotThrow(() => ScopedKey.Encrypt("0123456789ABCDEF0123456789ABCDEF", null)); } [Test] public void Encrypt_NullKey_Throws() { Assert.Throws<KeenException>(() => ScopedKey.Encrypt(null, new { X = "X" })); } public void Encrypt_BlankKey_Throws() { Assert.Throws<KeenException>(() => ScopedKey.Encrypt("", new { X = "X" })); } [Test] public void Encrypt_PopulatedObject_Success() { Assert.DoesNotThrow(() => { var settings = new ProjectSettingsProviderEnv(); dynamic secOps = new ExpandoObject(); IDictionary<string, object> filter = new ExpandoObject(); filter.Add("property_name", "account_id"); filter.Add("operator", "eq"); filter.Add("property_value", 123); secOps.filters = new List<object>() { filter }; secOps.allowed_operations = new List<string>() { "read" }; var scopedKey = ScopedKey.Encrypt(settings.MasterKey, (object)secOps); }); } [Test] public void RoundTrip_PopulatedObject_Success() { var settings = new ProjectSettingsProviderEnv(); IDictionary<string, object> filter = new ExpandoObject(); filter.Add("property_name", "account_id"); filter.Add("operator", "eq"); filter.Add("property_value", 123); dynamic secOpsIn = new ExpandoObject(); secOpsIn.filters = new List<object>() { filter }; secOpsIn.allowed_operations = new List<string>() { "read" }; Assert.DoesNotThrow(() => { var scopedKey = ScopedKey.Encrypt(settings.MasterKey, (object)secOpsIn); var decrypted = ScopedKey.Decrypt(settings.MasterKey, scopedKey); var secOpsOut = JObject.Parse(decrypted); Assert.True(secOpsIn.allowed_operations[0] == (string)(secOpsOut["allowed_operations"].First())); }); } [Test] public void RoundTrip_PopulatedObject_WithIV_Success() { var settings = new ProjectSettingsProviderEnv(); var IV = "C0FFEEC0FFEEC0FFEEC0FFEEC0FFEEC0"; IDictionary<string, object> filter = new ExpandoObject(); filter.Add("property_name", "account_id"); filter.Add("operator", "eq"); filter.Add("property_value", 123); dynamic secOpsIn = new ExpandoObject(); secOpsIn.filters = new List<object>() { filter }; secOpsIn.allowed_operations = new List<string>() { "read" }; Assert.DoesNotThrow(() => { var scopedKey = ScopedKey.Encrypt(settings.MasterKey, (object)secOpsIn, IV); var decrypted = ScopedKey.Decrypt(settings.MasterKey, scopedKey); var secOpsOut = JObject.Parse(decrypted); Assert.True(secOpsIn.allowed_operations[0] == (string)(secOpsOut["allowed_operations"].First())); }); } [Test] public void Decrypt_WriteKey_Success() { const string plainText = "{\"filters\": [{\"property_name\": \"vendor_id\",\"operator\": \"eq\",\"property_value\": \"abc\"}],\"allowed_operations\": [ \"write\" ]}"; var testKey = SettingsEnv.MasterKey; var cryptText = SettingsEnv.ReadKey; if (UseMocks) { cryptText = "BAA51D1D03D49C1159E7298762AAC26493B20F579988E1EDA4613305F08E01CB702886F0FCB5312E5E18C6315A8049700816CA35BD952C75EB694AAA4A95535EE13CD9D5D8C97A215B4790638EA1DA3DB9484A0133D5289E2A22D5C2952E1F708540722EA832B093E147495A70ADF534242E961FDE3F0275E20D58F22B23F4BAE2A61518CB943818ABEF547DD68F68FE"; testKey = "0123456789ABCDEF0123456789ABCDEF"; // ensure the key matches what cryptText was encrypted with } var decrypted = ScopedKey.Decrypt(testKey, cryptText); if (UseMocks) Assert.True(decrypted.Equals(plainText)); else Assert.That(decrypted.IndexOf("timestamp") > 0); } [Test] public void Roundtrip_RndIV_Success() { const string vendorGuid = "abc"; const bool isRead = false; var str = "{\"filters\": [{\"property_name\": \"vendor_id\",\"operator\": \"eq\",\"property_value\": \"VENDOR_GUID\"}],\"allowed_operations\": [ \"READ_OR_WRITE\" ]}"; str = str.Replace("VENDOR_GUID", vendorGuid); str = str.Replace("READ_OR_WRITE", isRead ? "read" : "write"); var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider(); var bytes = new byte[16]; rnd.GetBytes(bytes); var iv = String.Concat(bytes.Select(b => b.ToString("X2"))); Trace.WriteLine("IV: " + iv); Trace.WriteLine("plaintext: " + str); var scopedKey = ScopedKey.EncryptString(SettingsEnv.MasterKey, str, iv); Trace.WriteLine("encrypted: " + scopedKey); var decrypted = ScopedKey.Decrypt(SettingsEnv.MasterKey, scopedKey); Trace.WriteLine("decrypted: " + decrypted); // Make sure the input string exactly matches the decrypted string. This input isn't of // a length that is a multiple of block size or key size, so this would have required // manual padding in the past. The decrypted string shouldn't have any padding now. Assert.AreEqual(str, decrypted); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using ForgottenSchism.world; using ForgottenSchism.screen; using ForgottenSchism.control; namespace ForgottenSchism.engine { class derpAI { private struct PointCounter { public Point p; public int c; public PointCounter(Point fp, int fc) { p = fp; c = fc; } public PointCounter(int x, int y, int fc) { p = new Point(x, y); c = fc; } } private static bool canMove(UnitMap umap, Tilemap tm, Point dest, String org) { if (tm.get(dest.X, dest.Y).Type == Tile.TileType.MOUNTAIN || tm.get(dest.X, dest.Y).Type == Tile.TileType.WATER) return false; return umap.canMove(dest.X, dest.Y, org); } private static bool canMove(Tilemap tm, Point dest, String org) { return !(tm.get(dest.X, dest.Y).Type == Tile.TileType.MOUNTAIN || tm.get(dest.X, dest.Y).Type == Tile.TileType.WATER); } private static bool canMove(CharMap cmap, Tilemap tm, Point dest) { if (tm.get(dest.X, dest.Y).Type == Tile.TileType.MOUNTAIN || tm.get(dest.X, dest.Y).Type == Tile.TileType.WATER) return false; return cmap.canMove(dest.X, dest.Y); } private static bool inMap(Tilemap tm, Point p) { return p.X >= 0 && p.Y >= 0 && p.X < tm.NumX && p.Y < tm.NumY; } private static Point pathFindFallBack(UnitMap umap, Tilemap tm, Point src, Point dest, String org) { Dictionary<Point, int> map = new Dictionary<Point, int>(); Queue<PointCounter> main = new Queue<PointCounter>(); Queue<PointCounter> temp = new Queue<PointCounter>(); PointCounter cur; PointCounter tcur; main.Enqueue(new PointCounter(dest, 0)); map[dest] = 0; int cc; bool f = false; while (main.Count > 0) { cur = main.Dequeue(); temp.Clear(); if (cur.p == src) { f = true; break; } cc = cur.c + 1; temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y - 1, cc)); temp.Enqueue(new PointCounter(cur.p.X + 1, cur.p.Y, cc)); temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y + 1, cc)); temp.Enqueue(new PointCounter(cur.p.X - 1, cur.p.Y, cc)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (tcur.p != src) { if (!inMap(tm, tcur.p) || !canMove(tm, tcur.p, org)) continue; if (map.ContainsKey(tcur.p) && map[tcur.p] <= tcur.c) continue; } map[tcur.p] = tcur.c; main.Enqueue(tcur); } } if (!f) return src; Point ret = src; cc = map[src]; temp.Clear(); temp.Enqueue(new PointCounter(src.X, src.Y - 1, 0)); temp.Enqueue(new PointCounter(src.X + 1, src.Y, 0)); temp.Enqueue(new PointCounter(src.X, src.Y + 1, 0)); temp.Enqueue(new PointCounter(src.X - 1, src.Y, 0)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (map.ContainsKey(tcur.p) && map[tcur.p] < cc) { cc = map[tcur.p]; ret = tcur.p; } } if (!canMove(umap, tm, ret, org)) return src; return ret; } private static Point pathFindFallBack(CharMap cmap, Tilemap tm, Point src, Point dest, String org) { Dictionary<Point, int> map = new Dictionary<Point, int>(); Queue<PointCounter> main = new Queue<PointCounter>(); Queue<PointCounter> temp = new Queue<PointCounter>(); PointCounter cur; PointCounter tcur; main.Enqueue(new PointCounter(dest, 0)); map[dest] = 0; int cc; bool f = false; while (main.Count > 0) { cur = main.Dequeue(); temp.Clear(); if (cur.p == src) { f = true; break; } cc = cur.c + 1; temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y - 1, cc)); temp.Enqueue(new PointCounter(cur.p.X + 1, cur.p.Y, cc)); temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y + 1, cc)); temp.Enqueue(new PointCounter(cur.p.X - 1, cur.p.Y, cc)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (tcur.p != src) { if (!inMap(tm, tcur.p) || !canMove(tm, tcur.p, org)) continue; if (map.ContainsKey(tcur.p) && map[tcur.p] <= tcur.c) continue; } map[tcur.p] = tcur.c; main.Enqueue(tcur); } } if (!f) return src; Point ret = src; cc = map[src]; temp.Clear(); temp.Enqueue(new PointCounter(src.X, src.Y - 1, 0)); temp.Enqueue(new PointCounter(src.X + 1, src.Y, 0)); temp.Enqueue(new PointCounter(src.X, src.Y + 1, 0)); temp.Enqueue(new PointCounter(src.X - 1, src.Y, 0)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (map.ContainsKey(tcur.p) && map[tcur.p] < cc) { cc = map[tcur.p]; ret = tcur.p; } } if (!canMove(cmap, tm, ret)) return src; return ret; } private static Point pathFind(UnitMap umap, Tilemap tm, Point src, Point dest, String org) { Dictionary<Point, int> map = new Dictionary<Point, int>(); Queue<PointCounter> main = new Queue<PointCounter>(); Queue<PointCounter> temp = new Queue<PointCounter>(); PointCounter cur; PointCounter tcur; main.Enqueue(new PointCounter(dest, 0)); map[dest] = 0; int cc; bool f = false; while (main.Count > 0) { cur = main.Dequeue(); temp.Clear(); if (cur.p == src) { f = true; break; } cc = cur.c + 1; temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y - 1, cc)); temp.Enqueue(new PointCounter(cur.p.X + 1, cur.p.Y, cc)); temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y + 1, cc)); temp.Enqueue(new PointCounter(cur.p.X - 1, cur.p.Y, cc)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (tcur.p != src) { if (!inMap(tm, tcur.p) || !canMove(umap, tm, tcur.p, org)) continue; if (map.ContainsKey(tcur.p) && map[tcur.p] <= tcur.c) continue; } map[tcur.p] = tcur.c; main.Enqueue(tcur); } } if (!f) return pathFindFallBack(umap, tm, src, dest, org); Point ret = src; cc = map[src]; temp.Clear(); temp.Enqueue(new PointCounter(src.X, src.Y - 1, 0)); temp.Enqueue(new PointCounter(src.X + 1, src.Y, 0)); temp.Enqueue(new PointCounter(src.X, src.Y + 1, 0)); temp.Enqueue(new PointCounter(src.X - 1, src.Y, 0)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (map.ContainsKey(tcur.p) && map[tcur.p] < cc) { cc = map[tcur.p]; ret = tcur.p; } } return ret; } private static Point pathFind(CharMap cmap, Tilemap tm, Point src, Point dest, String org) { Dictionary<Point, int> map = new Dictionary<Point, int>(); Queue<PointCounter> main = new Queue<PointCounter>(); Queue<PointCounter> temp = new Queue<PointCounter>(); PointCounter cur; PointCounter tcur; main.Enqueue(new PointCounter(dest, 0)); map[dest] = 0; int cc; bool f = false; while (main.Count > 0) { cur = main.Dequeue(); temp.Clear(); if (cur.p == src) { f = true; break; } cc = cur.c + 1; temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y - 1, cc)); temp.Enqueue(new PointCounter(cur.p.X + 1, cur.p.Y, cc)); temp.Enqueue(new PointCounter(cur.p.X, cur.p.Y + 1, cc)); temp.Enqueue(new PointCounter(cur.p.X - 1, cur.p.Y, cc)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (tcur.p != src) { if (!inMap(tm, tcur.p) || !canMove(cmap, tm, tcur.p)) continue; if (map.ContainsKey(tcur.p) && map[tcur.p] <= tcur.c) continue; } map[tcur.p] = tcur.c; main.Enqueue(tcur); } } if (!f) return pathFindFallBack(cmap, tm, src, dest, org); Point ret = src; cc = map[src]; temp.Clear(); temp.Enqueue(new PointCounter(src.X, src.Y - 1, 0)); temp.Enqueue(new PointCounter(src.X + 1, src.Y, 0)); temp.Enqueue(new PointCounter(src.X, src.Y + 1, 0)); temp.Enqueue(new PointCounter(src.X - 1, src.Y, 0)); while (temp.Count > 0) { tcur = temp.Dequeue(); if (map.ContainsKey(tcur.p) && map[tcur.p] < cc) { cc = map[tcur.p]; ret = tcur.p; } } return ret; } //gives the 2 points adjacent to src that are adjacent to dest private static Point[] XYDir(Point src, Point dest) { Point[] ret = new Point[2]; if (dest.X == src.X - 1) ret[0] = new Point(dest.X, src.Y); else if (dest.X == src.X + 1) ret[0] = new Point(dest.X, src.Y); if (dest.Y == src.Y - 1) ret[1] = new Point(src.X, dest.Y); else if (dest.Y == src.Y + 1) ret[1] = new Point(src.X, dest.Y); return ret; } private static bool isTwoRange(Point src, Point dest) { return (isDiag(src, dest) || (dest.X == src.X + 2 && dest.Y == src.Y) || (dest.X == src.X - 2 && dest.Y == src.Y) || (dest.X == src.X && dest.Y == src.Y + 2) || (dest.X == src.X && dest.Y == src.Y - 2)); } private static bool isDiag(Point src, Point dest) { return ((dest.X == src.X - 1 || dest.X == src.X + 1) && (dest.Y == src.Y - 1 || dest.Y == src.Y + 1)); } private static bool isAdj(Point src, Point dest) { if (src == dest || isDiag(src, dest)) return false; return (dest.X >= src.X - 1 && dest.X <= src.X + 1 && dest.Y >= src.Y - 1 && dest.Y <= src.Y + 1); } private static bool isOrgPresent(UnitMap umap, Point p, String org) { if (p.X < 0 || p.Y < 0 || p.X >= umap.NumX || p.Y >= umap.NumY) return false; if (!umap.isUnit(p.X, p.Y)) return false; return umap.get(p.X, p.Y).Organization == org; } private static bool isOrgPresent(CharMap cmap, Point p, String org) { if (p.X < 0 || p.Y < 0 || p.X >= cmap.NumX || p.Y >= cmap.NumY) return false; if (!cmap.isChar(p.X, p.Y)) return false; return cmap.get(p.X, p.Y).Organization == org; } private static Point nearest(UnitMap umap, Point src, String org) { if (isOrgPresent(umap, new Point(src.X, src.Y - 1), org)) return new Point(src.X, src.Y - 1); if (isOrgPresent(umap, new Point(src.X + 1, src.Y), org)) return new Point(src.X + 1, src.Y); if (isOrgPresent(umap, new Point(src.X, src.Y + 1), org)) return new Point(src.X, src.Y + 1); if (isOrgPresent(umap, new Point(src.X - 1, src.Y), org)) return new Point(src.X - 1, src.Y); if (isOrgPresent(umap, new Point(src.X - 1, src.Y - 1), org)) return new Point(src.X - 1, src.Y - 1); if (isOrgPresent(umap, new Point(src.X + 1, src.Y - 1), org)) return new Point(src.X + 1, src.Y - 1); if (isOrgPresent(umap, new Point(src.X - 1, src.Y + 1), org)) return new Point(src.X - 1, src.Y + 1); if (isOrgPresent(umap, new Point(src.X + 1, src.Y + 1), org)) return new Point(src.X + 1, src.Y + 1); //inner cercle checked //very inefficient int mr = Gen.max(umap.NumX, umap.NumY); for (int r = 2; r < mr + 1; r++) for (int i = -r; i < r + 1; i++) for (int e = -r; e < r + 1; e++) { if (i != -r && i != r && e != -r && e != r) continue; if (isOrgPresent(umap, new Point(src.X + i, src.Y + e), org)) return new Point(src.X + i, src.Y + e); } return new Point(-1, -1); } private static Point nearest(CharMap cmap, Point src, String org) { int mr = Gen.max(cmap.NumX, cmap.NumY); for (int r = 1; r <= mr; r++) { for (int i = -r; i <= r; i++) { for (int e = -r; e <= r; e++) { if (Math.Abs(i) + Math.Abs(e) != r) continue; if (isOrgPresent(cmap, new Point(src.X + i, src.Y + e), org)) return new Point(src.X + i, src.Y + e); } } } return new Point(-1, -1); } private static Point derpnearest(CharMap cmap, Point src, String org) { if (isOrgPresent(cmap, new Point(src.X, src.Y - 1), org)) return new Point(src.X, src.Y - 1); if (isOrgPresent(cmap, new Point(src.X + 1, src.Y), org)) return new Point(src.X + 1, src.Y); if (isOrgPresent(cmap, new Point(src.X, src.Y + 1), org)) return new Point(src.X, src.Y + 1); if (isOrgPresent(cmap, new Point(src.X - 1, src.Y), org)) return new Point(src.X - 1, src.Y); if (isOrgPresent(cmap, new Point(src.X - 1, src.Y - 1), org)) return new Point(src.X - 1, src.Y - 1); if (isOrgPresent(cmap, new Point(src.X + 1, src.Y - 1), org)) return new Point(src.X + 1, src.Y - 1); if (isOrgPresent(cmap, new Point(src.X - 1, src.Y + 1), org)) return new Point(src.X - 1, src.Y + 1); if (isOrgPresent(cmap, new Point(src.X + 1, src.Y + 1), org)) return new Point(src.X + 1, src.Y + 1); //inner cercle checked //very inefficient int mr = Gen.max(cmap.NumX, cmap.NumY); for (int r = 2; r < mr + 1; r++) for (int i = -r; i < r + 1; i++) for (int e = -r; e < r + 1; e++) { if (i != -r && i != r && e != -r && e != r) continue; if (isOrgPresent(cmap, new Point(src.X + i, src.Y + e), org)) return new Point(src.X + i, src.Y + e); } return new Point(-1, -1); } private static Point targetCharacter(Character c, Point p, CharMap cmap) { bool targetable = false; bool castable = false; List<Point> targetableChar = new List<Point>(); Point target = new Point(-1, -1); if (c is Fighter || c is Scout) { if (cmap.isChar(p.X - 1, p.Y) && cmap.get(p.X - 1, p.Y).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X - 1, p.Y)); } if (cmap.isChar(p.X, p.Y - 1) && cmap.get(p.X, p.Y - 1).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X, p.Y - 1)); } if (cmap.isChar(p.X + 1, p.Y) && cmap.get(p.X + 1, p.Y).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X + 1, p.Y)); } if (cmap.isChar(p.X, p.Y + 1) && cmap.get(p.X, p.Y + 1).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X, p.Y + 1)); } } else if (c is Archer) { if (cmap.isChar(p.X - 1, p.Y + 1) && cmap.get(p.X - 1, p.Y + 1).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X - 1, p.Y + 1)); } if (cmap.isChar(p.X - 1, p.Y - 1) && cmap.get(p.X - 1, p.Y - 1).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X - 1, p.Y - 1)); } if (cmap.isChar(p.X + 1, p.Y + 1) && cmap.get(p.X + 1, p.Y + 1).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X + 1, p.Y + 1)); } if (cmap.isChar(p.X + 1, p.Y - 1) && cmap.get(p.X + 1, p.Y - 1).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X + 1, p.Y - 1)); } if (cmap.isChar(p.X - 2, p.Y) && cmap.get(p.X - 2, p.Y).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X - 2, p.Y)); } if (cmap.isChar(p.X, p.Y - 2) && cmap.get(p.X, p.Y - 2).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X, p.Y - 2)); } if (cmap.isChar(p.X + 2, p.Y) && cmap.get(p.X + 2, p.Y).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X + 2, p.Y)); } if (cmap.isChar(p.X, p.Y + 2) && cmap.get(p.X, p.Y + 2).Organization == "main") { targetable = true; targetableChar.Add(new Point(p.X, p.Y + 2)); } } else if (c is Healer) { if (cmap.isChar(p.X - 1, p.Y) && cmap.get(p.X - 1, p.Y).Organization == "ennemy") { castable = true; targetableChar.Add(new Point(p.X - 1, p.Y)); } if (cmap.isChar(p.X, p.Y - 1) && cmap.get(p.X, p.Y - 1).Organization == "ennemy") { castable = true; targetableChar.Add(new Point(p.X, p.Y - 1)); } if (cmap.isChar(p.X + 1, p.Y) && cmap.get(p.X + 1, p.Y).Organization == "ennemy") { castable = true; targetableChar.Add(new Point(p.X + 1, p.Y)); } if (cmap.isChar(p.X, p.Y + 1) && cmap.get(p.X, p.Y + 1).Organization == "ennemy") { castable = true; targetableChar.Add(new Point(p.X, p.Y + 1)); } } else if (c is Caster) { if (cmap.isChar(p.X - 1, p.Y) && cmap.get(p.X - 1, p.Y).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X - 1, p.Y)); } if (cmap.isChar(p.X, p.Y - 1) && cmap.get(p.X, p.Y - 1).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X, p.Y - 1)); } if (cmap.isChar(p.X + 1, p.Y) && cmap.get(p.X + 1, p.Y).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X + 1, p.Y)); } if (cmap.isChar(p.X, p.Y + 1) && cmap.get(p.X, p.Y + 1).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X, p.Y + 1)); } if (cmap.isChar(p.X - 1, p.Y + 1) && cmap.get(p.X - 1, p.Y + 1).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X - 1, p.Y + 1)); } if (cmap.isChar(p.X - 1, p.Y - 1) && cmap.get(p.X - 1, p.Y - 1).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X - 1, p.Y - 1)); } if (cmap.isChar(p.X + 1, p.Y + 1) && cmap.get(p.X + 1, p.Y + 1).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X + 1, p.Y + 1)); } if (cmap.isChar(p.X + 1, p.Y - 1) && cmap.get(p.X + 1, p.Y - 1).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X + 1, p.Y - 1)); } if (cmap.isChar(p.X - 2, p.Y) && cmap.get(p.X - 2, p.Y).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X - 2, p.Y)); } if (cmap.isChar(p.X, p.Y - 2) && cmap.get(p.X, p.Y - 2).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X, p.Y - 2)); } if (cmap.isChar(p.X + 2, p.Y) && cmap.get(p.X + 2, p.Y).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X + 2, p.Y)); } if (cmap.isChar(p.X, p.Y + 2) && cmap.get(p.X, p.Y + 2).Organization == "main") { castable = true; targetableChar.Add(new Point(p.X, p.Y + 2)); } } if (targetable) { foreach (Point pt in targetableChar) { if (target == new Point(-1, -1) || cmap.get(pt.X, pt.Y).stats.hp < cmap.get(target.X, target.Y).stats.hp) target = pt; } } if (castable) { foreach (Point pt in targetableChar) { if (target == new Point(-1, -1) || cmap.get(pt.X, pt.Y).stats.hp < cmap.get(target.X, target.Y).stats.hp) target = pt; } } return target; } public static Unit[] region(UnitMap umap, Tilemap tm, String org, Map map, ref Boolean dun) { Unit u; Point ne; Point d; for (int i = 0; i < umap.NumX; i++) for (int e = 0; e < umap.NumY; e++) if (umap.isUnit(i, e) && umap.get(i, e).movement > 0 && umap.get(i, e).Organization == org) { if (map.CursorPosition != new Point(i, e)) { map.changeCursor(new Point(i, e)); return null; } u = umap.get(i, e); if (u.hasLeader()) { ne = nearest(umap, new Point(i, e), "main"); if (isAdj(new Point(i, e), ne)) { u.movement = 0; return new Unit[] { umap.get(ne.X, ne.Y), u }; } //finds path to nearest ennemy d = pathFind(umap, tm, new Point(i, e), nearest(umap, new Point(i, e), "main"), org); umap.move(i, e, d.X, d.Y); map.changeCursor(new Point(d.X, d.Y)); u.movement--; } return null; } dun = true; return null; } public static Boolean battle(CharMap cmap, Tilemap tm, String org, Map map, Unit ally, Unit enemy, Label dmg, Label action, ref Boolean gameOver, ref Boolean defeat, GameTime gameTime) { Character c = cmap.get(map.CursorPosition.X, map.CursorPosition.Y); Character m; Point p; Point ne; if (c != null && c.Organization == org && c.stats.movement != 0) { if(c is Healer) ne = nearest(cmap, map.CursorPosition, "ennemy"); else ne = nearest(cmap, map.CursorPosition, "main"); if (isAdj(map.CursorPosition, ne)) { c.stats.movement = 0; p = map.CursorPosition; } else { //finds path to nearest ennemy p = pathFind(cmap, tm, map.CursorPosition, nearest(cmap, map.CursorPosition, "main"), org); if (c.stats.movement > 0) { cmap.move(map.CursorPosition.X, map.CursorPosition.Y, p.X, p.Y); map.changeCursor(new Point(p.X, p.Y)); } c.stats.movement--; } if (c.stats.movement == 0) { Point tar = targetCharacter(c, p, cmap); if (tar != new Point(-1, -1)) { m = cmap.get(tar.X, tar.Y); map.CurLs.Add(tar, Content.Graphics.Instance.Images.gui.cursorRed); if (c is Fighter) dmg.Text = ((Fighter)c).attack(m); else if (c is Archer) dmg.Text = ((Archer)c).attack(m); else if (c is Scout) dmg.Text = ((Scout)c).attack(m); else if (c is Healer) { dmg.Text = ((Healer)c).heal(m).ToString(); action.Text = "Heal"; } else if (c is Caster) { dmg.Text = ((Caster)c).attack(m, new Spell("DerpCast", 1, 5, 1, 5)); action.Text = "DerpCast"; } else dmg.Text = "Cant"; if (action.Text == "") action.Text = "Attack"; dmg.Position = new Vector2(tar.X * 64 - map.getTlc.X * 64, tar.Y * 64 - map.getTlc.Y * 64 + 20); dmg.visibleTemp(500); action.visibleTemp(500); if (dmg.Text != "miss" || dmg.Text != "Cant") { enemy.set(c.Position.X, c.Position.Y, c); ally.set(m.Position.X, m.Position.Y, m); if (m.stats.hp <= 0) { if (m.isMainChar()) gameOver = true; ally.delete(m.Position.X, m.Position.Y); cmap.set(tar.X, tar.Y, null); cmap.update(map); if (ally.Characters.Count <= 0) defeat = true; } } } } return false; } else { for (int e = cmap.NumY - 1; e >= 0; e--) for (int i = cmap.NumX - 1; i >= 0; i--) if (cmap.isChar(i, e) && cmap.get(i, e).stats.movement != 0 && cmap.get(i, e).Organization == org) { if (map.CursorPosition != new Point(i, e)) { map.CurLs.Clear(); dmg.Visible = false; action.Visible = false; action.Text = ""; map.changeCursor(new Point(i, e)); return false; } } } cmap.resetAllMovement(org); return true; } } }
using System.Collections.Generic; using System.Linq; using GLTF.Extensions; using GLTF.Math; using Newtonsoft.Json; namespace GLTF.Schema { /// <summary> /// A node in the node hierarchy. /// When the node contains `skin`, all `mesh.primitives` must contain `JOINT` /// and `WEIGHT` attributes. A node can have either a `matrix` or any combination /// of `translation`/`rotation`/`scale` (TRS) properties. /// TRS properties are converted to matrices and postmultiplied in /// the `T * R * S` order to compose the transformation matrix; /// first the scale is applied to the vertices, then the rotation, and then /// the translation. If none are provided, the transform is the Identity. /// When a node is targeted for animation /// (referenced by an animation.channel.target), only TRS properties may be present; /// `matrix` will not be present. /// </summary> public class Node : GLTFChildOfRootProperty { /// <summary> /// If true, extracts transform, rotation, scale values from the Matrix4x4. Otherwise uses the Transform, Rotate, Scale directly as specified by by the node. /// </summary> public bool UseTRS; /// <summary> /// The index of the camera referenced by this node. /// </summary> public CameraId Camera; /// <summary> /// The indices of this node's children. /// </summary> public List<NodeId> Children; /// <summary> /// The index of the skin referenced by this node. /// </summary> public SkinId Skin; /// <summary> /// A floating-point 4x4 transformation matrix stored in column-major order. /// </summary> public Matrix4x4 Matrix = Matrix4x4.Identity; /// <summary> /// The index of the mesh in this node. /// </summary> public MeshId Mesh; /// <summary> /// The node's unit quaternion rotation in the order (x, y, z, w), /// where w is the scalar. /// </summary> public Quaternion Rotation = new Quaternion(0, 0, 0, 1); /// <summary> /// The node's non-uniform scale. /// </summary> public Vector3 Scale = Vector3.One; /// <summary> /// The node's translation. /// </summary> public Vector3 Translation = Vector3.Zero; /// <summary> /// The weights of the instantiated Morph Target. /// Number of elements must match number of Morph Targets of used mesh. /// </summary> public List<double> Weights; public Node() { } public Node(Node node, GLTFRoot gltfRoot) : base(node, gltfRoot) { if (node == null) return; UseTRS = node.UseTRS; if (node.Camera != null) { Camera = new CameraId(node.Camera, gltfRoot); } if (node.Children != null) { Children = new List<NodeId>(node.Children.Count); foreach (NodeId child in node.Children) { Children.Add(new NodeId(child, gltfRoot)); } } if (node.Skin != null) { Skin = new SkinId(node.Skin, gltfRoot); } if (node.Matrix != null) { Matrix = new Matrix4x4(node.Matrix); } if (node.Mesh != null) { Mesh = new MeshId(node.Mesh, gltfRoot); } Rotation = node.Rotation; Scale = node.Scale; Translation = node.Translation; if (node.Weights != null) { Weights = node.Weights.ToList(); } } public static Node Deserialize(GLTFRoot root, JsonReader reader) { var node = new Node(); while (reader.Read() && reader.TokenType == JsonToken.PropertyName) { var curProp = reader.Value.ToString(); switch (curProp) { case "camera": node.Camera = CameraId.Deserialize(root, reader); break; case "children": node.Children = NodeId.ReadList(root, reader); break; case "skin": node.Skin = SkinId.Deserialize(root, reader); break; case "matrix": var list = reader.ReadDoubleList(); // gltf has column ordered matricies var mat = new Matrix4x4( (float)list[0], (float)list[1], (float)list[2], (float)list[3], (float)list[4], (float)list[5], (float)list[6], (float)list[7], (float)list[8], (float)list[9], (float)list[10], (float)list[11], (float)list[12], (float)list[13], (float)list[14], (float)list[15] ); node.Matrix = mat; break; case "mesh": node.Mesh = MeshId.Deserialize(root, reader); break; case "rotation": node.UseTRS = true; node.Rotation = reader.ReadAsQuaternion(); break; case "scale": node.UseTRS = true; node.Scale = reader.ReadAsVector3(); break; case "translation": node.UseTRS = true; node.Translation = reader.ReadAsVector3(); break; case "weights": node.Weights = reader.ReadDoubleList(); break; default: node.DefaultPropertyDeserializer(root, reader); break; } } return node; } public override void Serialize(JsonWriter writer) { writer.WriteStartObject(); if (Camera != null) { writer.WritePropertyName("camera"); writer.WriteValue(Camera.Id); } if (Children != null && Children.Count > 0) { writer.WritePropertyName("children"); writer.WriteStartArray(); foreach (var child in Children) { writer.WriteValue(child.Id); } writer.WriteEndArray(); } if (Skin != null) { writer.WritePropertyName("skin"); writer.WriteValue(Skin.Id); } if (Matrix != Matrix4x4.Identity) { writer.WritePropertyName("matrix"); writer.WriteStartArray(); writer.WriteValue(Matrix.M11); writer.WriteValue(Matrix.M21); writer.WriteValue(Matrix.M31); writer.WriteValue(Matrix.M41); writer.WriteValue(Matrix.M12); writer.WriteValue(Matrix.M22); writer.WriteValue(Matrix.M32); writer.WriteValue(Matrix.M42); writer.WriteValue(Matrix.M13); writer.WriteValue(Matrix.M23); writer.WriteValue(Matrix.M33); writer.WriteValue(Matrix.M43); writer.WriteValue(Matrix.M14); writer.WriteValue(Matrix.M24); writer.WriteValue(Matrix.M34); writer.WriteValue(Matrix.M44); writer.WriteEndArray(); } if (Mesh != null) { writer.WritePropertyName("mesh"); writer.WriteValue(Mesh.Id); } if (Rotation != Quaternion.Identity) { writer.WritePropertyName("rotation"); writer.WriteStartArray(); writer.WriteValue(Rotation.X); writer.WriteValue(Rotation.Y); writer.WriteValue(Rotation.Z); writer.WriteValue(Rotation.W); writer.WriteEndArray(); } if (Scale != Vector3.One) { writer.WritePropertyName("scale"); writer.WriteStartArray(); writer.WriteValue(Scale.X); writer.WriteValue(Scale.Y); writer.WriteValue(Scale.Z); writer.WriteEndArray(); } if (Translation != Vector3.Zero) { writer.WritePropertyName("translation"); writer.WriteStartArray(); writer.WriteValue(Translation.X); writer.WriteValue(Translation.Y); writer.WriteValue(Translation.Z); writer.WriteEndArray(); } if (Weights != null && Weights.Count > 0) { writer.WritePropertyName("weights"); writer.WriteStartArray(); foreach (var weight in Weights) { writer.WriteValue(weight); } writer.WriteEndArray(); } base.Serialize(writer); writer.WriteEndObject(); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Studio.Controls.ControlsPublic File: BuySellPanel.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Studio.Controls { using System; using System.Linq; using System.Windows; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Configuration; using Ecng.Serialization; using StockSharp.Algo; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Studio.Core; using StockSharp.Studio.Core.Commands; using StockSharp.Xaml; using StockSharp.Localization; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; public class BuySellSettings : NotifiableObject, IPersistable { private decimal _volume = 1; private bool _showLimitOrderPanel = true; private bool _showMarketOrderPanel = true; private bool _showCancelAll = true; private Portfolio _portfolio; private Security _security; private int _depth = 5; public event Action<Security, Security> SecurityChanged; [DisplayNameLoc(LocalizedStrings.SecurityKey)] [DescriptionLoc(LocalizedStrings.Str3192Key)] [PropertyOrder(10)] public Security Security { get { return _security; } set { if (_security == value) return; var oldValue = _security; _security = value; SecurityChanged.SafeInvoke(oldValue, value); NotifyChanged(nameof(Security)); } } [DisplayNameLoc(LocalizedStrings.PortfolioKey)] [DescriptionLoc(LocalizedStrings.Str1997Key)] [PropertyOrder(15)] public Portfolio Portfolio { get { return _portfolio; } set { if (_portfolio == value) return; _portfolio = value; NotifyChanged(nameof(Portfolio)); } } [DisplayNameLoc(LocalizedStrings.Str3193Key)] [DescriptionLoc(LocalizedStrings.Str3194Key)] [PropertyOrder(20)] public decimal Volume { get { return _volume; } set { _volume = value; NotifyChanged(nameof(Volume)); } } [DisplayNameLoc(LocalizedStrings.Str1660Key)] [DescriptionLoc(LocalizedStrings.Str3195Key)] [PropertyOrder(21)] public int Depth { get { return _depth; } set { _depth = value; NotifyChanged(nameof(Depth)); } } [DisplayNameLoc(LocalizedStrings.CancelAllKey)] [DescriptionLoc(LocalizedStrings.Str3196Key)] [PropertyOrder(30)] public bool ShowCancelAll { get { return _showCancelAll; } set { _showCancelAll = value; NotifyChanged(nameof(ShowCancelAll)); } } [DisplayNameLoc(LocalizedStrings.Str3197Key)] [DescriptionLoc(LocalizedStrings.Str3198Key)] [PropertyOrder(40)] public bool ShowLimitOrderPanel { get { return _showLimitOrderPanel; } set { _showLimitOrderPanel = value; NotifyChanged(nameof(ShowLimitOrderPanel)); } } [DisplayNameLoc(LocalizedStrings.MarketOrdersKey)] [DescriptionLoc(LocalizedStrings.Str3199Key)] [PropertyOrder(50)] public bool ShowMarketOrderPanel { get { return _showMarketOrderPanel; } set { _showMarketOrderPanel = value; NotifyChanged(nameof(ShowMarketOrderPanel)); } } public void Load(SettingsStorage storage) { Volume = storage.GetValue(nameof(Volume), 1); ShowLimitOrderPanel = storage.GetValue(nameof(ShowLimitOrderPanel), true); ShowMarketOrderPanel = storage.GetValue(nameof(ShowMarketOrderPanel), true); ShowCancelAll = storage.GetValue(nameof(ShowCancelAll), true); Depth = storage.GetValue(nameof(Depth), MarketDepthControl.DefaultDepth); var secProvider = ConfigManager.GetService<ISecurityProvider>(); var securityId = storage.GetValue<string>(nameof(Security)); if (!securityId.IsEmpty()) { if (securityId.CompareIgnoreCase("DEPTHSEC@FORTS")) { Security = "RI" .GetFortsJumps(DateTime.Today.AddMonths(3), DateTime.Today.AddMonths(6), code => secProvider.LookupById(code + "@" + ExchangeBoard.Forts.Code)) .LastOrDefault(); } else Security = secProvider.LookupById(securityId); } var pfProvider = ConfigManager.GetService<IPortfolioProvider>(); var portfolioName = storage.GetValue<string>(nameof(Portfolio)); if (!portfolioName.IsEmpty()) Portfolio = pfProvider.Portfolios.FirstOrDefault(s => s.Name == portfolioName); } public void Save(SettingsStorage storage) { storage.SetValue(nameof(Volume), Volume); storage.SetValue(nameof(ShowLimitOrderPanel), ShowLimitOrderPanel); storage.SetValue(nameof(ShowMarketOrderPanel), ShowMarketOrderPanel); storage.SetValue(nameof(ShowCancelAll), ShowCancelAll); storage.SetValue(nameof(Depth), Depth); //storage.SetValue(nameof(CreateOrderAtClick), CreateOrderAtClick); storage.SetValue(nameof(Security), Security?.Id); storage.SetValue(nameof(Portfolio), Portfolio?.Name); } } public partial class BuySellPanel : IStudioControl { private readonly BuySellSettings _settings = new BuySellSettings(); public decimal LimitPrice { get; set; } public BuySellSettings Settings => _settings; public BuySellPanel() { InitializeComponent(); _settings.PropertyChanged += (arg1, arg2) => new ControlChangedCommand(this).Process(this); SettingsPropertyGrid.SelectedObject = _settings; LimitPriceCtrl.Value = 0; } private Order CreateOrder(Sides direction, decimal price = 0, OrderTypes type = OrderTypes.Market) { return new Order { Portfolio = Settings.Portfolio, Security = Settings.Security, Direction = direction, Price = price, Volume = Settings.Volume, Type = type, }; } private void BuyAtLimit_Click(object sender, RoutedEventArgs e) { var price = LimitPriceCtrl.Value; if(price == null || price <= 0) return; new RegisterOrderCommand(CreateOrder(Sides.Buy, price.Value, OrderTypes.Limit)).Process(this); } private void SellAtLimit_Click(object sender, RoutedEventArgs e) { var price = LimitPriceCtrl.Value; if(price == null || price <= 0) return; new RegisterOrderCommand(CreateOrder(Sides.Sell, price.Value, OrderTypes.Limit)).Process(this); } private void BuyAtMarket_Click(object sender, RoutedEventArgs e) { new RegisterOrderCommand(CreateOrder(Sides.Buy)).Process(this); } private void SellAtMarket_Click(object sender, RoutedEventArgs e) { new RegisterOrderCommand(CreateOrder(Sides.Sell)).Process(this); } private void ClosePosition_Click(object sender, RoutedEventArgs e) { new ClosePositionCommand(Settings.Security).Process(this); } private void RevertPosition_Click(object sender, RoutedEventArgs e) { new RevertPositionCommand(Settings.Security).Process(this); } private void CancelAll_Click(object sender, RoutedEventArgs e) { new CancelAllOrdersCommand().Process(this); } public void Save(SettingsStorage storage) { _settings.Save(storage); } public void Load(SettingsStorage storage) { _settings.Load(storage); } void IDisposable.Dispose() { } string IStudioControl.Title => string.Empty; Uri IStudioControl.Icon => null; } }
using System; using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IEDIDocumentTypeApi { #region Synchronous Operations /// <summary> /// Get an eDIDocumentType by id /// </summary> /// <remarks> /// Returns the eDIDocumentType identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>EDIDocumentType</returns> EDIDocumentType GetEDIDocumentTypeById (string eDIDocumentTypeId); /// <summary> /// Get an eDIDocumentType by id /// </summary> /// <remarks> /// Returns the eDIDocumentType identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>ApiResponse of EDIDocumentType</returns> ApiResponse<EDIDocumentType> GetEDIDocumentTypeByIdWithHttpInfo (string eDIDocumentTypeId); /// <summary> /// Search eDIDocumentTypes /// </summary> /// <remarks> /// Returns the list of eDIDocumentTypes that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;EDIDocumentType&gt;</returns> List<EDIDocumentType> GetEDIDocumentTypeBySearchText (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search eDIDocumentTypes /// </summary> /// <remarks> /// Returns the list of eDIDocumentTypes that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;EDIDocumentType&gt;</returns> ApiResponse<List<EDIDocumentType>> GetEDIDocumentTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Get an eDIDocumentType by id /// </summary> /// <remarks> /// Returns the eDIDocumentType identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>Task of EDIDocumentType</returns> System.Threading.Tasks.Task<EDIDocumentType> GetEDIDocumentTypeByIdAsync (string eDIDocumentTypeId); /// <summary> /// Get an eDIDocumentType by id /// </summary> /// <remarks> /// Returns the eDIDocumentType identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>Task of ApiResponse (EDIDocumentType)</returns> System.Threading.Tasks.Task<ApiResponse<EDIDocumentType>> GetEDIDocumentTypeByIdAsyncWithHttpInfo (string eDIDocumentTypeId); /// <summary> /// Search eDIDocumentTypes /// </summary> /// <remarks> /// Returns the list of eDIDocumentTypes that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;EDIDocumentType&gt;</returns> System.Threading.Tasks.Task<List<EDIDocumentType>> GetEDIDocumentTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search eDIDocumentTypes /// </summary> /// <remarks> /// Returns the list of eDIDocumentTypes that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;EDIDocumentType&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<EDIDocumentType>>> GetEDIDocumentTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class EDIDocumentTypeApi : IEDIDocumentTypeApi { /// <summary> /// Initializes a new instance of the <see cref="EDIDocumentTypeApi"/> class. /// </summary> /// <returns></returns> public EDIDocumentTypeApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="EDIDocumentTypeApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public EDIDocumentTypeApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Get an eDIDocumentType by id Returns the eDIDocumentType identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>EDIDocumentType</returns> public EDIDocumentType GetEDIDocumentTypeById (string eDIDocumentTypeId) { ApiResponse<EDIDocumentType> localVarResponse = GetEDIDocumentTypeByIdWithHttpInfo(eDIDocumentTypeId); return localVarResponse.Data; } /// <summary> /// Get an eDIDocumentType by id Returns the eDIDocumentType identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>ApiResponse of EDIDocumentType</returns> public ApiResponse< EDIDocumentType > GetEDIDocumentTypeByIdWithHttpInfo (string eDIDocumentTypeId) { // verify the required parameter 'eDIDocumentTypeId' is set if (eDIDocumentTypeId == null) throw new ApiException(400, "Missing required parameter 'eDIDocumentTypeId' when calling EDIDocumentTypeApi->GetEDIDocumentTypeById"); var localVarPath = "/beta/eDIDocumentType/{eDIDocumentTypeId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (eDIDocumentTypeId != null) localVarPathParams.Add("eDIDocumentTypeId", Configuration.ApiClient.ParameterToString(eDIDocumentTypeId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeById: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<EDIDocumentType>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (EDIDocumentType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(EDIDocumentType))); } /// <summary> /// Get an eDIDocumentType by id Returns the eDIDocumentType identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>Task of EDIDocumentType</returns> public async System.Threading.Tasks.Task<EDIDocumentType> GetEDIDocumentTypeByIdAsync (string eDIDocumentTypeId) { ApiResponse<EDIDocumentType> localVarResponse = await GetEDIDocumentTypeByIdAsyncWithHttpInfo(eDIDocumentTypeId); return localVarResponse.Data; } /// <summary> /// Get an eDIDocumentType by id Returns the eDIDocumentType identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="eDIDocumentTypeId">Id of eDIDocumentType to be returned.</param> /// <returns>Task of ApiResponse (EDIDocumentType)</returns> public async System.Threading.Tasks.Task<ApiResponse<EDIDocumentType>> GetEDIDocumentTypeByIdAsyncWithHttpInfo (string eDIDocumentTypeId) { // verify the required parameter 'eDIDocumentTypeId' is set if (eDIDocumentTypeId == null) throw new ApiException(400, "Missing required parameter 'eDIDocumentTypeId' when calling GetEDIDocumentTypeById"); var localVarPath = "/beta/eDIDocumentType/{eDIDocumentTypeId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (eDIDocumentTypeId != null) localVarPathParams.Add("eDIDocumentTypeId", Configuration.ApiClient.ParameterToString(eDIDocumentTypeId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeById: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeById: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<EDIDocumentType>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (EDIDocumentType) Configuration.ApiClient.Deserialize(localVarResponse, typeof(EDIDocumentType))); } /// <summary> /// Search eDIDocumentTypes Returns the list of eDIDocumentTypes that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;EDIDocumentType&gt;</returns> public List<EDIDocumentType> GetEDIDocumentTypeBySearchText (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<EDIDocumentType>> localVarResponse = GetEDIDocumentTypeBySearchTextWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search eDIDocumentTypes Returns the list of eDIDocumentTypes that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;EDIDocumentType&gt;</returns> public ApiResponse< List<EDIDocumentType> > GetEDIDocumentTypeBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/beta/eDIDocumentType/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeBySearchText: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<List<EDIDocumentType>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<EDIDocumentType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<EDIDocumentType>))); } /// <summary> /// Search eDIDocumentTypes Returns the list of eDIDocumentTypes that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;EDIDocumentType&gt;</returns> public async System.Threading.Tasks.Task<List<EDIDocumentType>> GetEDIDocumentTypeBySearchTextAsync (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<EDIDocumentType>> localVarResponse = await GetEDIDocumentTypeBySearchTextAsyncWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search eDIDocumentTypes Returns the list of eDIDocumentTypes that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;EDIDocumentType&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<EDIDocumentType>>> GetEDIDocumentTypeBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/beta/eDIDocumentType/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (localVarStatusCode >= 400) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeBySearchText: " + localVarResponse.Content, localVarResponse.Content); else if (localVarStatusCode == 0) throw new ApiException (localVarStatusCode, "Error calling GetEDIDocumentTypeBySearchText: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage); return new ApiResponse<List<EDIDocumentType>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<EDIDocumentType>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<EDIDocumentType>))); } } }
// 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.IO; using System.Reflection; using System.Collections; using System.Globalization; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace Microsoft.Build.Shared { /// <summary> /// This class is used to load types from their assemblies. /// </summary> internal class TypeLoader { /// <summary> /// Cache to keep track of the assemblyLoadInfos based on a given typeFilter. /// </summary> private static Concurrent.ConcurrentDictionary<TypeFilter, Concurrent.ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>> s_cacheOfLoadedTypesByFilter = new Concurrent.ConcurrentDictionary<TypeFilter, Concurrent.ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>>(); /// <summary> /// Cache to keep track of the assemblyLoadInfos based on a given type filter for assemblies which are to be loaded for reflectionOnlyLoads. /// </summary> private static Concurrent.ConcurrentDictionary<TypeFilter, Concurrent.ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>> s_cacheOfReflectionOnlyLoadedTypesByFilter = new Concurrent.ConcurrentDictionary<TypeFilter, Concurrent.ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>>(); /// <summary> /// Typefilter for this typeloader /// </summary> private TypeFilter _isDesiredType; /// <summary> /// Constructor. /// </summary> internal TypeLoader(TypeFilter isDesiredType) { ErrorUtilities.VerifyThrow(isDesiredType != null, "need a type filter"); _isDesiredType = isDesiredType; } /// <summary> /// Given two type names, looks for a partial match between them. A partial match is considered valid only if it occurs on /// the right side (tail end) of the name strings, and at the start of a class or namespace name. /// </summary> /// <remarks> /// 1) Matches are case-insensitive. /// 2) .NET conventions regarding namespaces and nested classes are respected, including escaping of reserved characters. /// </remarks> /// <example> /// "Csc" and "csc" ==> exact match /// "Microsoft.Build.Tasks.Csc" and "Microsoft.Build.Tasks.Csc" ==> exact match /// "Microsoft.Build.Tasks.Csc" and "Csc" ==> partial match /// "Microsoft.Build.Tasks.Csc" and "Tasks.Csc" ==> partial match /// "MyTasks.ATask+NestedTask" and "NestedTask" ==> partial match /// "MyTasks.ATask\\+NestedTask" and "NestedTask" ==> partial match /// "MyTasks.CscTask" and "Csc" ==> no match /// "MyTasks.MyCsc" and "Csc" ==> no match /// "MyTasks.ATask\.Csc" and "Csc" ==> no match /// "MyTasks.ATask\\\.Csc" and "Csc" ==> no match /// </example> /// <returns>true, if the type names match exactly or partially; false, if there is no match at all</returns> internal static bool IsPartialTypeNameMatch(string typeName1, string typeName2) { bool isPartialMatch = false; // if the type names are the same length, a partial match is impossible if (typeName1.Length != typeName2.Length) { string longerTypeName; string shorterTypeName; // figure out which type name is longer if (typeName1.Length > typeName2.Length) { longerTypeName = typeName1; shorterTypeName = typeName2; } else { longerTypeName = typeName2; shorterTypeName = typeName1; } // if the shorter type name matches the end of the longer one if (longerTypeName.EndsWith(shorterTypeName, StringComparison.OrdinalIgnoreCase)) { int matchIndex = longerTypeName.Length - shorterTypeName.Length; // if the matched sub-string looks like the start of a namespace or class name if ((longerTypeName[matchIndex - 1] == '.') || (longerTypeName[matchIndex - 1] == '+')) { int precedingBackslashes = 0; // confirm there are zero, or an even number of \'s preceding it... for (int i = matchIndex - 2; i >= 0; i--) { if (longerTypeName[i] == '\\') { precedingBackslashes++; } else { break; } } if ((precedingBackslashes % 2) == 0) { isPartialMatch = true; } } } } else { isPartialMatch = (String.Compare(typeName1, typeName2, StringComparison.OrdinalIgnoreCase) == 0); } return isPartialMatch; } /// <summary> /// Loads the specified type if it exists in the given assembly. If the type name is fully qualified, then a match (if /// any) is unambiguous; otherwise, if there are multiple types with the same name in different namespaces, the first type /// found will be returned. /// </summary> internal LoadedType Load ( string typeName, AssemblyLoadInfo assembly ) { return GetLoadedType(s_cacheOfLoadedTypesByFilter, typeName, assembly); } /// <summary> /// Loads the specified type if it exists in the given assembly. If the type name is fully qualified, then a match (if /// any) is unambiguous; otherwise, if there are multiple types with the same name in different namespaces, the first type /// found will be returned. /// </summary> /// <returns>The loaded type, or null if the type was not found.</returns> internal LoadedType ReflectionOnlyLoad ( string typeName, AssemblyLoadInfo assembly ) { return GetLoadedType(s_cacheOfReflectionOnlyLoadedTypesByFilter, typeName, assembly); } /// <summary> /// Loads the specified type if it exists in the given assembly. If the type name is fully qualified, then a match (if /// any) is unambiguous; otherwise, if there are multiple types with the same name in different namespaces, the first type /// found will be returned. /// </summary> private LoadedType GetLoadedType(Concurrent.ConcurrentDictionary<TypeFilter, Concurrent.ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>> cache, string typeName, AssemblyLoadInfo assembly) { // A given type filter have been used on a number of assemblies, Based on the type filter we will get another dictionary which // will map a specific AssemblyLoadInfo to a AssemblyInfoToLoadedTypes class which knows how to find a typeName in a given assembly. Concurrent.ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes> loadInfoToType = cache.GetOrAdd(_isDesiredType, (_) => new Concurrent.ConcurrentDictionary<AssemblyLoadInfo, AssemblyInfoToLoadedTypes>()); // Get an object which is able to take a typename and determine if it is in the assembly pointed to by the AssemblyInfo. AssemblyInfoToLoadedTypes typeNameToType = loadInfoToType.GetOrAdd(assembly, (_) => new AssemblyInfoToLoadedTypes(_isDesiredType, _)); return typeNameToType.GetLoadedTypeByTypeName(typeName); } /// <summary> /// Given a type filter and an asssemblyInfo object keep track of what types in a given assembly which match the typefilter. /// Also, use this information to determine if a given TypeName is in the assembly which is pointed to by the AssemblyLoadInfo object. /// /// This type represents a combination of a type filter and an assemblyInfo object. /// </summary> private class AssemblyInfoToLoadedTypes { /// <summary> /// Lock to prevent two threads from using this object at the same time. /// Since we fill up internal structures with what is in the assembly /// </summary> private readonly Object _lockObject = new Object(); /// <summary> /// Type filter to pick the correct types out of an assembly /// </summary> private TypeFilter _isDesiredType; /// <summary> /// Assembly load information so we can load an assembly /// </summary> private AssemblyLoadInfo _assemblyLoadInfo; /// <summary> /// What is the type for the given type name, this may be null if the typeName does not map to a type. /// </summary> private Concurrent.ConcurrentDictionary<string, Type> _typeNameToType; /// <summary> /// List of public types in the assembly which match the typefilter and their corresponding types /// </summary> private Dictionary<string, Type> _publicTypeNameToType; /// <summary> /// Have we scanned the public types for this assembly yet. /// </summary> private long _haveScannedPublicTypes; /// <summary> /// If we loaded an assembly for this type. /// We use this information to set the LoadedType.LoadedAssembly so that this object can be used /// to help created AppDomains to resolve those that it could not load successfuly /// </summary> private Assembly _loadedAssembly; /// <summary> /// Given a type filter, and an assembly to load the type information from determine if a given type name is in the assembly or not. /// </summary> internal AssemblyInfoToLoadedTypes(TypeFilter typeFilter, AssemblyLoadInfo loadInfo) { ErrorUtilities.VerifyThrowArgumentNull(typeFilter, "typefilter"); ErrorUtilities.VerifyThrowArgumentNull(loadInfo, "loadInfo"); _isDesiredType = typeFilter; _assemblyLoadInfo = loadInfo; _typeNameToType = new Concurrent.ConcurrentDictionary<string, Type>(StringComparer.OrdinalIgnoreCase); _publicTypeNameToType = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Determine if a given type name is in the assembly or not. Return null if the type is not in the assembly /// </summary> internal LoadedType GetLoadedTypeByTypeName(string typeName) { ErrorUtilities.VerifyThrowArgumentNull(typeName, "typeName"); // Only one thread should be doing operations on this instance of the object at a time. Type type = _typeNameToType.GetOrAdd(typeName, (key) => { if ((_assemblyLoadInfo.AssemblyName != null) && (typeName.Length > 0)) { try { // try to load the type using its assembly qualified name Type t2 = Type.GetType(typeName + "," + _assemblyLoadInfo.AssemblyName, false /* don't throw on error */, true /* case-insensitive */); if (t2 != null) { return !_isDesiredType(t2, null) ? null : t2; } } catch (ArgumentException) { // Type.GetType() will throw this exception if the type name is invalid -- but we have no idea if it's the // type or the assembly name that's the problem -- so just ignore the exception, because we're going to // check the existence/validity of the assembly and type respectively, below anyway } } if (Interlocked.Read(ref _haveScannedPublicTypes) == 0) { lock (_lockObject) { if (Interlocked.Read(ref _haveScannedPublicTypes) == 0) { ScanAssemblyForPublicTypes(); Interlocked.Exchange(ref _haveScannedPublicTypes, ~0); } } } foreach (KeyValuePair<string, Type> desiredTypeInAssembly in _publicTypeNameToType) { // if type matches partially on its name if (typeName.Length == 0 || TypeLoader.IsPartialTypeNameMatch(desiredTypeInAssembly.Key, typeName)) { return desiredTypeInAssembly.Value; } } return null; }); return type != null ? new LoadedType(type, _assemblyLoadInfo, _loadedAssembly) : null; } /// <summary> /// Scan the assembly pointed to by the assemblyLoadInfo for public types. We will use these public types to do partial name matching on /// to find tasks, loggers, and task factories. /// </summary> private void ScanAssemblyForPublicTypes() { // we need to search the assembly for the type... try { if (_assemblyLoadInfo.AssemblyName != null) { _loadedAssembly = Assembly.Load(_assemblyLoadInfo.AssemblyName); } else { _loadedAssembly = Assembly.LoadFrom(_assemblyLoadInfo.AssemblyFile); } } catch (ArgumentException e) { // Assembly.Load() and Assembly.LoadFrom() will throw an ArgumentException if the assembly name is invalid // convert to a FileNotFoundException because it's more meaningful // NOTE: don't use ErrorUtilities.VerifyThrowFileExists() here because that will hit the disk again throw new FileNotFoundException(null, _assemblyLoadInfo.AssemblyLocation, e); } // only look at public types Type[] allPublicTypesInAssembly = _loadedAssembly.GetExportedTypes(); foreach (Type publicType in allPublicTypesInAssembly) { if (_isDesiredType(publicType, null)) { _publicTypeNameToType.Add(publicType.FullName, publicType); } } } } } }
// 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: The CLR wrapper for all Win32 as well as ** ROTOR-style Unix PAL, etc. native operations ** ** ===========================================================*/ /** * Notes to PInvoke users: Getting the syntax exactly correct is crucial, and * more than a little confusing. Here's some guidelines. * * For handles, you should use a SafeHandle subclass specific to your handle * type. For files, we have the following set of interesting definitions: * * [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)] * private static extern SafeFileHandle CreateFile(...); * * [DllImport(KERNEL32, SetLastError=true)] * unsafe internal static extern int ReadFile(SafeFileHandle handle, ...); * * [DllImport(KERNEL32, SetLastError=true)] * internal static extern bool CloseHandle(IntPtr handle); * * P/Invoke will create the SafeFileHandle instance for you and assign the * return value from CreateFile into the handle atomically. When we call * ReadFile, P/Invoke will increment a ref count, make the call, then decrement * it (preventing handle recycling vulnerabilities). Then SafeFileHandle's * ReleaseHandle method will call CloseHandle, passing in the handle field * as an IntPtr. * * If for some reason you cannot use a SafeHandle subclass for your handles, * then use IntPtr as the handle type (or possibly HandleRef - understand when * to use GC.KeepAlive). If your code will run in SQL Server (or any other * long-running process that can't be recycled easily), use a constrained * execution region to prevent thread aborts while allocating your * handle, and consider making your handle wrapper subclass * CriticalFinalizerObject to ensure you can free the handle. As you can * probably guess, SafeHandle will save you a lot of headaches if your code * needs to be robust to thread aborts and OOM. * * * If you have a method that takes a native struct, you have two options for * declaring that struct. You can make it a value type ('struct' in CSharp), * or a reference type ('class'). This choice doesn't seem very interesting, * but your function prototype must use different syntax depending on your * choice. For example, if your native method is prototyped as such: * * bool GetVersionEx(OSVERSIONINFO & lposvi); * * * you must use EITHER THIS OR THE NEXT syntax: * * [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] * internal struct OSVERSIONINFO { ... } * * [DllImport(KERNEL32, CharSet=CharSet.Auto)] * internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi); * * OR: * * [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] * internal class OSVERSIONINFO { ... } * * [DllImport(KERNEL32, CharSet=CharSet.Auto)] * internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi); * * Note that classes require being marked as [In, Out] while value types must * be passed as ref parameters. * * Also note the CharSet.Auto on GetVersionEx - while it does not take a String * as a parameter, the OSVERSIONINFO contains an embedded array of TCHARs, so * the size of the struct varies on different platforms, and there's a * GetVersionExA & a GetVersionExW. Also, the OSVERSIONINFO struct has a sizeof * field so the OS can ensure you've passed in the correctly-sized copy of an * OSVERSIONINFO. You must explicitly set this using Marshal.SizeOf(Object); * * For security reasons, if you're making a P/Invoke method to a Win32 method * that takes an ANSI String and that String is the name of some resource you've * done a security check on (such as a file name), you want to disable best fit * mapping in WideCharToMultiByte. Do this by setting BestFitMapping=false * in your DllImportAttribute. */ namespace Microsoft.Win32 { using System; using System.Security; using System.Text; using System.Configuration.Assemblies; using System.Runtime.Remoting; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using BOOL = System.Int32; using DWORD = System.UInt32; using ULONG = System.UInt32; /** * Win32 encapsulation for MSCORLIB. */ // Remove the default demands for all P/Invoke methods with this // global declaration on the class. [SuppressUnmanagedCodeSecurityAttribute()] internal static class Win32Native { internal const int KEY_QUERY_VALUE = 0x0001; internal const int KEY_SET_VALUE = 0x0002; internal const int KEY_CREATE_SUB_KEY = 0x0004; internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008; internal const int KEY_NOTIFY = 0x0010; internal const int KEY_CREATE_LINK = 0x0020; internal const int KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & (~SYNCHRONIZE)); internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY) & (~SYNCHRONIZE)); internal const int KEY_WOW64_64KEY = 0x0100; // internal const int KEY_WOW64_32KEY = 0x0200; // internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges internal const int REG_NONE = 0; // No value type internal const int REG_SZ = 1; // Unicode nul terminated string internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string // (with environment variable references) internal const int REG_BINARY = 3; // Free form binary internal const int REG_DWORD = 4; // 32-bit number internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD) internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number internal const int REG_LINK = 6; // Symbolic Link (unicode) internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10; internal const int REG_QWORD = 11; // 64-bit number internal const int HWND_BROADCAST = 0xffff; internal const int WM_SETTINGCHANGE = 0x001A; // TimeZone internal const int TIME_ZONE_ID_INVALID = -1; internal const int TIME_ZONE_ID_UNKNOWN = 0; internal const int TIME_ZONE_ID_STANDARD = 1; internal const int TIME_ZONE_ID_DAYLIGHT = 2; internal const int MAX_PATH = 260; internal const int MUI_LANGUAGE_ID = 0x4; internal const int MUI_LANGUAGE_NAME = 0x8; internal const int MUI_PREFERRED_UI_LANGUAGES = 0x10; internal const int MUI_INSTALLED_LANGUAGES = 0x20; internal const int MUI_ALL_LANGUAGES = 0x40; internal const int MUI_LANG_NEUTRAL_PE_FILE = 0x100; internal const int MUI_NON_LANG_NEUTRAL_FILE = 0x200; internal const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002; internal const int LOAD_STRING_MAX_LENGTH = 500; [StructLayout(LayoutKind.Sequential)] internal struct SystemTime { [MarshalAs(UnmanagedType.U2)] public short Year; [MarshalAs(UnmanagedType.U2)] public short Month; [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; [MarshalAs(UnmanagedType.U2)] public short Day; [MarshalAs(UnmanagedType.U2)] public short Hour; [MarshalAs(UnmanagedType.U2)] public short Minute; [MarshalAs(UnmanagedType.U2)] public short Second; [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public Int32 Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; public SystemTime StandardDate; [MarshalAs(UnmanagedType.I4)] public Int32 StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; public SystemTime DaylightDate; [MarshalAs(UnmanagedType.I4)] public Int32 DaylightBias; public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi) { Bias = dtzi.Bias; StandardName = dtzi.StandardName; StandardDate = dtzi.StandardDate; StandardBias = dtzi.StandardBias; DaylightName = dtzi.DaylightName; DaylightDate = dtzi.DaylightDate; DaylightBias = dtzi.DaylightBias; } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct DynamicTimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public Int32 Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; public SystemTime StandardDate; [MarshalAs(UnmanagedType.I4)] public Int32 StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; public SystemTime DaylightDate; [MarshalAs(UnmanagedType.I4)] public Int32 DaylightBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string TimeZoneKeyName; [MarshalAs(UnmanagedType.Bool)] public bool DynamicDaylightTimeDisabled; } [StructLayout(LayoutKind.Sequential)] internal struct RegistryTimeZoneInformation { [MarshalAs(UnmanagedType.I4)] public Int32 Bias; [MarshalAs(UnmanagedType.I4)] public Int32 StandardBias; [MarshalAs(UnmanagedType.I4)] public Int32 DaylightBias; public SystemTime StandardDate; public SystemTime DaylightDate; public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi) { Bias = tzi.Bias; StandardDate = tzi.StandardDate; StandardBias = tzi.StandardBias; DaylightDate = tzi.DaylightDate; DaylightBias = tzi.DaylightBias; } public RegistryTimeZoneInformation(Byte[] bytes) { // // typedef struct _REG_TZI_FORMAT { // [00-03] LONG Bias; // [04-07] LONG StandardBias; // [08-11] LONG DaylightBias; // [12-27] SYSTEMTIME StandardDate; // [12-13] WORD wYear; // [14-15] WORD wMonth; // [16-17] WORD wDayOfWeek; // [18-19] WORD wDay; // [20-21] WORD wHour; // [22-23] WORD wMinute; // [24-25] WORD wSecond; // [26-27] WORD wMilliseconds; // [28-43] SYSTEMTIME DaylightDate; // [28-29] WORD wYear; // [30-31] WORD wMonth; // [32-33] WORD wDayOfWeek; // [34-35] WORD wDay; // [36-37] WORD wHour; // [38-39] WORD wMinute; // [40-41] WORD wSecond; // [42-43] WORD wMilliseconds; // } REG_TZI_FORMAT; // if (bytes == null || bytes.Length != 44) { throw new ArgumentException(SR.Argument_InvalidREG_TZI_FORMAT, nameof(bytes)); } Bias = BitConverter.ToInt32(bytes, 0); StandardBias = BitConverter.ToInt32(bytes, 4); DaylightBias = BitConverter.ToInt32(bytes, 8); StandardDate.Year = BitConverter.ToInt16(bytes, 12); StandardDate.Month = BitConverter.ToInt16(bytes, 14); StandardDate.DayOfWeek = BitConverter.ToInt16(bytes, 16); StandardDate.Day = BitConverter.ToInt16(bytes, 18); StandardDate.Hour = BitConverter.ToInt16(bytes, 20); StandardDate.Minute = BitConverter.ToInt16(bytes, 22); StandardDate.Second = BitConverter.ToInt16(bytes, 24); StandardDate.Milliseconds = BitConverter.ToInt16(bytes, 26); DaylightDate.Year = BitConverter.ToInt16(bytes, 28); DaylightDate.Month = BitConverter.ToInt16(bytes, 30); DaylightDate.DayOfWeek = BitConverter.ToInt16(bytes, 32); DaylightDate.Day = BitConverter.ToInt16(bytes, 34); DaylightDate.Hour = BitConverter.ToInt16(bytes, 36); DaylightDate.Minute = BitConverter.ToInt16(bytes, 38); DaylightDate.Second = BitConverter.ToInt16(bytes, 40); DaylightDate.Milliseconds = BitConverter.ToInt16(bytes, 42); } } // end of TimeZone // Win32 ACL-related constants: internal const int READ_CONTROL = 0x00020000; internal const int SYNCHRONIZE = 0x00100000; internal const int STANDARD_RIGHTS_READ = READ_CONTROL; internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL; // STANDARD_RIGHTS_REQUIRED (0x000F0000L) // SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3) // SEMAPHORE and Event both use 0x0002 // MUTEX uses 0x001 (MUTANT_QUERY_STATE) // Note that you may need to specify the SYNCHRONIZE bit as well // to be able to open a synchronization primitive. internal const int SEMAPHORE_MODIFY_STATE = 0x00000002; internal const int EVENT_MODIFY_STATE = 0x00000002; internal const int MUTEX_MODIFY_STATE = 0x00000001; internal const int MUTEX_ALL_ACCESS = 0x001F0001; internal const int LMEM_FIXED = 0x0000; internal const int LMEM_ZEROINIT = 0x0040; internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal class OSVERSIONINFO { internal OSVERSIONINFO() { OSVersionInfoSize = (int)Marshal.SizeOf(this); } // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) internal int OSVersionInfoSize = 0; internal int MajorVersion = 0; internal int MinorVersion = 0; internal int BuildNumber = 0; internal int PlatformId = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal String CSDVersion = null; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] internal class OSVERSIONINFOEX { public OSVERSIONINFOEX() { OSVersionInfoSize = (int)Marshal.SizeOf(this); } // The OSVersionInfoSize field must be set to Marshal.SizeOf(this) internal int OSVersionInfoSize = 0; internal int MajorVersion = 0; internal int MinorVersion = 0; internal int BuildNumber = 0; internal int PlatformId = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal string CSDVersion = null; internal ushort ServicePackMajor = 0; internal ushort ServicePackMinor = 0; internal short SuiteMask = 0; internal byte ProductType = 0; internal byte Reserved = 0; } [StructLayout(LayoutKind.Sequential)] internal class SECURITY_ATTRIBUTES { internal int nLength = 0; // don't remove null, or this field will disappear in bcl.small internal unsafe byte* pSecurityDescriptor = null; internal int bInheritHandle = 0; } [Serializable] [StructLayout(LayoutKind.Sequential)] internal struct WIN32_FILE_ATTRIBUTE_DATA { internal int fileAttributes; internal uint ftCreationTimeLow; internal uint ftCreationTimeHigh; internal uint ftLastAccessTimeLow; internal uint ftLastAccessTimeHigh; internal uint ftLastWriteTimeLow; internal uint ftLastWriteTimeHigh; internal int fileSizeHigh; internal int fileSizeLow; internal void PopulateFrom(WIN32_FIND_DATA findData) { // Copy the information to data fileAttributes = findData.dwFileAttributes; ftCreationTimeLow = findData.ftCreationTime_dwLowDateTime; ftCreationTimeHigh = findData.ftCreationTime_dwHighDateTime; ftLastAccessTimeLow = findData.ftLastAccessTime_dwLowDateTime; ftLastAccessTimeHigh = findData.ftLastAccessTime_dwHighDateTime; ftLastWriteTimeLow = findData.ftLastWriteTime_dwLowDateTime; ftLastWriteTimeHigh = findData.ftLastWriteTime_dwHighDateTime; fileSizeHigh = findData.nFileSizeHigh; fileSizeLow = findData.nFileSizeLow; } } [StructLayout(LayoutKind.Sequential)] internal struct MEMORYSTATUSEX { // The length field must be set to the size of this data structure. internal int length; internal int memoryLoad; internal ulong totalPhys; internal ulong availPhys; internal ulong totalPageFile; internal ulong availPageFile; internal ulong totalVirtual; internal ulong availVirtual; internal ulong availExtendedVirtual; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct MEMORY_BASIC_INFORMATION { internal void* BaseAddress; internal void* AllocationBase; internal uint AllocationProtect; internal UIntPtr RegionSize; internal uint State; internal uint Protect; internal uint Type; } #if !FEATURE_PAL internal const String KERNEL32 = "kernel32.dll"; internal const String USER32 = "user32.dll"; internal const String OLE32 = "ole32.dll"; internal const String OLEAUT32 = "oleaut32.dll"; #else //FEATURE_PAL internal const String KERNEL32 = "libcoreclr"; internal const String USER32 = "libcoreclr"; internal const String OLE32 = "libcoreclr"; internal const String OLEAUT32 = "libcoreclr"; #endif //FEATURE_PAL internal const String ADVAPI32 = "advapi32.dll"; internal const String SHELL32 = "shell32.dll"; internal const String SHIM = "mscoree.dll"; internal const String CRYPT32 = "crypt32.dll"; internal const String SECUR32 = "secur32.dll"; internal const String MSCORWKS = "coreclr.dll"; // From WinBase.h internal const int SEM_FAILCRITICALERRORS = 1; [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = true)] internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer, int nSize, IntPtr va_list_arguments); // Gets an error message for a Win32 error code. internal static String GetMessage(int errorCode) { StringBuilder sb = StringBuilderCache.Acquire(512); int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, IntPtr.Zero, errorCode, 0, sb, sb.Capacity, IntPtr.Zero); if (result != 0) { // result is the # of characters copied to the StringBuilder. return StringBuilderCache.GetStringAndRelease(sb); } else { StringBuilderCache.Release(sb); return SR.Format(SR.UnknownError_Num, errorCode); } } [DllImport(KERNEL32, EntryPoint = "LocalAlloc")] internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes); [DllImport(KERNEL32, SetLastError = true)] internal static extern IntPtr LocalFree(IntPtr handle); internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer) { buffer.length = Marshal.SizeOf(typeof(MEMORYSTATUSEX)); return GlobalMemoryStatusExNative(ref buffer); } [DllImport(KERNEL32, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")] private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer); [DllImport(KERNEL32, SetLastError = true)] unsafe internal static extern UIntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer); // VirtualAlloc should generally be avoided, but is needed in // the MemoryFailPoint implementation (within a CER) to increase the // size of the page file, ignoring any host memory allocators. [DllImport(KERNEL32, SetLastError = true)] unsafe internal static extern void* VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode); [DllImport(KERNEL32, SetLastError = true)] unsafe internal static extern bool VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode); [DllImport(KERNEL32, CharSet = CharSet.Ansi, ExactSpelling = true, EntryPoint = "lstrlenA")] internal static extern int lstrlenA(IntPtr ptr); [DllImport(KERNEL32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "lstrlenW")] internal static extern int lstrlenW(IntPtr ptr); [DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)] internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR [DllImport(Win32Native.OLEAUT32)] internal static extern uint SysStringLen(IntPtr bstr); [DllImport(Win32Native.OLEAUT32)] internal static extern void SysFreeString(IntPtr bstr); #if FEATURE_COMINTEROP [DllImport(Win32Native.OLEAUT32)] internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); // BSTR [DllImport(Win32Native.OLEAUT32)] internal static extern uint SysStringByteLen(IntPtr bstr); #endif [DllImport(KERNEL32, SetLastError = true)] internal static extern bool SetEvent(SafeWaitHandle handle); [DllImport(KERNEL32, SetLastError = true)] internal static extern bool ResetEvent(SafeWaitHandle handle); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, bool isManualReset, bool initialState, String name); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenEvent(/* DWORD */ int desiredAccess, bool inheritHandle, String name); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, String name); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenMutex(/* DWORD */ int desiredAccess, bool inheritHandle, String name); [DllImport(KERNEL32, SetLastError = true)] internal static extern bool ReleaseMutex(SafeWaitHandle handle); [DllImport(KERNEL32, SetLastError = true)] internal static extern bool CloseHandle(IntPtr handle); [DllImport(KERNEL32, SetLastError = true)] internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle CreateSemaphore(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, String name); [DllImport(KERNEL32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeWaitHandle OpenSemaphore(/* DWORD */ int desiredAccess, bool inheritHandle, String name); // Will be in winnls.h internal const int FIND_STARTSWITH = 0x00100000; // see if value is at the beginning of source internal const int FIND_ENDSWITH = 0x00200000; // see if value is at the end of source internal const int FIND_FROMSTART = 0x00400000; // look for value in source, starting at the beginning internal const int FIND_FROMEND = 0x00800000; // look for value in source, starting at the end [StructLayout(LayoutKind.Sequential)] internal struct NlsVersionInfoEx { internal int dwNLSVersionInfoSize; internal int dwNLSVersion; internal int dwDefinedVersion; internal int dwEffectiveId; internal Guid guidCustomVersion; } [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern int GetSystemDirectory([Out]StringBuilder sb, int length); internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h // Note, these are #defines used to extract handles, and are NOT handles. internal const int STD_INPUT_HANDLE = -10; internal const int STD_OUTPUT_HANDLE = -11; internal const int STD_ERROR_HANDLE = -12; [DllImport(KERNEL32, SetLastError = true)] internal static extern IntPtr GetStdHandle(int nStdHandle); // param is NOT a handle, but it returns one! // From wincon.h internal const int CTRL_C_EVENT = 0; internal const int CTRL_BREAK_EVENT = 1; internal const int CTRL_CLOSE_EVENT = 2; internal const int CTRL_LOGOFF_EVENT = 5; internal const int CTRL_SHUTDOWN_EVENT = 6; internal const short KEY_EVENT = 1; // From WinBase.h internal const int FILE_TYPE_DISK = 0x0001; internal const int FILE_TYPE_CHAR = 0x0002; internal const int FILE_TYPE_PIPE = 0x0003; internal const int REPLACEFILE_WRITE_THROUGH = 0x1; internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2; private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; internal const uint FILE_MAP_WRITE = 0x0002; internal const uint FILE_MAP_READ = 0x0004; // Constants from WinNT.h internal const int FILE_ATTRIBUTE_READONLY = 0x00000001; internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010; internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400; internal const int IO_REPARSE_TAG_MOUNT_POINT = unchecked((int)0xA0000003); internal const int PAGE_READWRITE = 0x04; internal const int MEM_COMMIT = 0x1000; internal const int MEM_RESERVE = 0x2000; internal const int MEM_RELEASE = 0x8000; internal const int MEM_FREE = 0x10000; // Error codes from WinError.h internal const int ERROR_SUCCESS = 0x0; internal const int ERROR_INVALID_FUNCTION = 0x1; internal const int ERROR_FILE_NOT_FOUND = 0x2; internal const int ERROR_PATH_NOT_FOUND = 0x3; internal const int ERROR_ACCESS_DENIED = 0x5; internal const int ERROR_INVALID_HANDLE = 0x6; internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8; internal const int ERROR_INVALID_DATA = 0xd; internal const int ERROR_INVALID_DRIVE = 0xf; internal const int ERROR_NO_MORE_FILES = 0x12; internal const int ERROR_NOT_READY = 0x15; internal const int ERROR_BAD_LENGTH = 0x18; internal const int ERROR_SHARING_VIOLATION = 0x20; internal const int ERROR_NOT_SUPPORTED = 0x32; internal const int ERROR_FILE_EXISTS = 0x50; internal const int ERROR_INVALID_PARAMETER = 0x57; internal const int ERROR_BROKEN_PIPE = 0x6D; internal const int ERROR_CALL_NOT_IMPLEMENTED = 0x78; internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; internal const int ERROR_INVALID_NAME = 0x7B; internal const int ERROR_BAD_PATHNAME = 0xA1; internal const int ERROR_ALREADY_EXISTS = 0xB7; internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB; internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long. internal const int ERROR_NO_DATA = 0xE8; internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; internal const int ERROR_MORE_DATA = 0xEA; internal const int ERROR_DIRECTORY = 0x10B; internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation internal const int ERROR_NOT_FOUND = 0x490; // 1168; For IO Cancellation internal const int ERROR_NO_TOKEN = 0x3f0; internal const int ERROR_DLL_INIT_FAILED = 0x45A; internal const int ERROR_NON_ACCOUNT_SID = 0x4E9; internal const int ERROR_NOT_ALL_ASSIGNED = 0x514; internal const int ERROR_UNKNOWN_REVISION = 0x519; internal const int ERROR_INVALID_OWNER = 0x51B; internal const int ERROR_INVALID_PRIMARY_GROUP = 0x51C; internal const int ERROR_NO_SUCH_PRIVILEGE = 0x521; internal const int ERROR_PRIVILEGE_NOT_HELD = 0x522; internal const int ERROR_NONE_MAPPED = 0x534; internal const int ERROR_INVALID_ACL = 0x538; internal const int ERROR_INVALID_SID = 0x539; internal const int ERROR_INVALID_SECURITY_DESCR = 0x53A; internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542; internal const int ERROR_CANT_OPEN_ANONYMOUS = 0x543; internal const int ERROR_NO_SECURITY_ON_OBJECT = 0x546; internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 0x6FD; // Error codes from ntstatus.h internal const uint STATUS_SUCCESS = 0x00000000; internal const uint STATUS_SOME_NOT_MAPPED = 0x00000107; internal const uint STATUS_NO_MEMORY = 0xC0000017; internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034; internal const uint STATUS_NONE_MAPPED = 0xC0000073; internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A; internal const uint STATUS_ACCESS_DENIED = 0xC0000022; internal const int INVALID_FILE_SIZE = -1; // From WinStatus.h internal const int STATUS_ACCOUNT_RESTRICTION = unchecked((int)0xC000006E); // Use this to translate error codes like the above into HRESULTs like // 0x80070006 for ERROR_INVALID_HANDLE internal static int MakeHRFromErrorCode(int errorCode) { BCLDebug.Assert((0xFFFF0000 & errorCode) == 0, "This is an HRESULT, not an error code!"); return unchecked(((int)0x80070000) | errorCode); } // Win32 Structs in N/Direct style [Serializable] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] [BestFitMapping(false)] internal class WIN32_FIND_DATA { internal int dwFileAttributes = 0; // ftCreationTime was a by-value FILETIME structure internal uint ftCreationTime_dwLowDateTime = 0; internal uint ftCreationTime_dwHighDateTime = 0; // ftLastAccessTime was a by-value FILETIME structure internal uint ftLastAccessTime_dwLowDateTime = 0; internal uint ftLastAccessTime_dwHighDateTime = 0; // ftLastWriteTime was a by-value FILETIME structure internal uint ftLastWriteTime_dwLowDateTime = 0; internal uint ftLastWriteTime_dwHighDateTime = 0; internal int nFileSizeHigh = 0; internal int nFileSizeLow = 0; // If the file attributes' reparse point flag is set, then // dwReserved0 is the file tag (aka reparse tag) for the // reparse point. Use this to figure out whether something is // a volume mount point or a symbolic link. internal int dwReserved0 = 0; internal int dwReserved1 = 0; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] internal String cFileName = null; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] internal String cAlternateFileName = null; } [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern SafeFindHandle FindFirstFile(String fileName, [In, Out] Win32Native.WIN32_FIND_DATA data); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern bool FindNextFile( SafeFindHandle hndFindFile, [In, Out, MarshalAs(UnmanagedType.LPStruct)] WIN32_FIND_DATA lpFindFileData); [DllImport(KERNEL32)] internal static extern bool FindClose(IntPtr handle); [DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)] internal static extern uint GetCurrentDirectoryW(uint nBufferLength, char[] lpBuffer); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern bool SetCurrentDirectory(String path); [DllImport(KERNEL32, SetLastError = false, EntryPoint = "SetErrorMode", ExactSpelling = true)] private static extern int SetErrorMode_VistaAndOlder(int newMode); // RTM versions of Win7 and Windows Server 2008 R2 private static readonly Version ThreadErrorModeMinOsVersion = new Version(6, 1, 7600); // this method uses the thread-safe version of SetErrorMode on Windows 7 / Windows Server 2008 R2 operating systems. internal static int SetErrorMode(int newMode) { return SetErrorMode_VistaAndOlder(newMode); } internal const int LCID_SUPPORTED = 0x00000002; // supported locale ids [DllImport(KERNEL32)] internal static extern unsafe int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern bool SetEnvironmentVariable(string lpName, string lpValue); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern int GetEnvironmentVariable(string lpName, [Out]StringBuilder lpValue, int size); [DllImport(KERNEL32, CharSet = CharSet.Unicode)] internal static unsafe extern char* GetEnvironmentStrings(); [DllImport(KERNEL32, CharSet = CharSet.Unicode)] internal static unsafe extern bool FreeEnvironmentStrings(char* pStrings); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] internal static extern uint GetCurrentProcessId(); [DllImport(OLE32)] internal extern static int CoCreateGuid(out Guid guid); [DllImport(OLE32)] internal static extern IntPtr CoTaskMemAlloc(UIntPtr cb); [DllImport(OLE32)] internal static extern void CoTaskMemFree(IntPtr ptr); [DllImport(OLE32)] internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb); #if FEATURE_WIN32_REGISTRY [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal unsafe static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex, char[] lpName, ref int lpcbName, int[] lpReserved, [Out]StringBuilder lpClass, int[] lpcbClass, long[] lpftLastWriteTime); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal unsafe static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex, char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData, int[] lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass, int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys, int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen, ref int lpcValues, int[] lpcbMaxValueNameLen, int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor, int[] lpftLastWriteTime); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref int lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, ref long lpData, int cbData); [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName, int Reserved, RegistryValueKind dwType, String lpData, int cbData); #endif // FEATURE_WIN32_REGISTRY [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)] internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize); [DllImport(KERNEL32)] internal static extern IntPtr LocalReAlloc(IntPtr handle, IntPtr sizetcbBytes, int uFlags); internal const int SHGFP_TYPE_CURRENT = 0; // the current (user) folder path setting internal const int UOI_FLAGS = 1; internal const int WSF_VISIBLE = 1; // .NET Framework 4.0 and newer - all versions of windows ||| \public\sdk\inc\shlobj.h internal const int CSIDL_FLAG_CREATE = 0x8000; // force folder creation in SHGetFolderPath internal const int CSIDL_FLAG_DONT_VERIFY = 0x4000; // return an unverified folder path internal const int CSIDL_ADMINTOOLS = 0x0030; // <user name>\Start Menu\Programs\Administrative Tools internal const int CSIDL_CDBURN_AREA = 0x003b; // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning internal const int CSIDL_COMMON_ADMINTOOLS = 0x002f; // All Users\Start Menu\Programs\Administrative Tools internal const int CSIDL_COMMON_DOCUMENTS = 0x002e; // All Users\Documents internal const int CSIDL_COMMON_MUSIC = 0x0035; // All Users\My Music internal const int CSIDL_COMMON_OEM_LINKS = 0x003a; // Links to All Users OEM specific apps internal const int CSIDL_COMMON_PICTURES = 0x0036; // All Users\My Pictures internal const int CSIDL_COMMON_STARTMENU = 0x0016; // All Users\Start Menu internal const int CSIDL_COMMON_PROGRAMS = 0X0017; // All Users\Start Menu\Programs internal const int CSIDL_COMMON_STARTUP = 0x0018; // All Users\Startup internal const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019; // All Users\Desktop internal const int CSIDL_COMMON_TEMPLATES = 0x002d; // All Users\Templates internal const int CSIDL_COMMON_VIDEO = 0x0037; // All Users\My Video internal const int CSIDL_FONTS = 0x0014; // windows\fonts internal const int CSIDL_MYVIDEO = 0x000e; // "My Videos" folder internal const int CSIDL_NETHOOD = 0x0013; // %APPDATA%\Microsoft\Windows\Network Shortcuts internal const int CSIDL_PRINTHOOD = 0x001b; // %APPDATA%\Microsoft\Windows\Printer Shortcuts internal const int CSIDL_PROFILE = 0x0028; // %USERPROFILE% (%SystemDrive%\Users\%USERNAME%) internal const int CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c; // x86 Program Files\Common on RISC internal const int CSIDL_PROGRAM_FILESX86 = 0x002a; // x86 C:\Program Files on RISC internal const int CSIDL_RESOURCES = 0x0038; // %windir%\Resources internal const int CSIDL_RESOURCES_LOCALIZED = 0x0039; // %windir%\resources\0409 (code page) internal const int CSIDL_SYSTEMX86 = 0x0029; // %windir%\system32 internal const int CSIDL_WINDOWS = 0x0024; // GetWindowsDirectory() // .NET Framework 3.5 and earlier - all versions of windows internal const int CSIDL_APPDATA = 0x001a; internal const int CSIDL_COMMON_APPDATA = 0x0023; internal const int CSIDL_LOCAL_APPDATA = 0x001c; internal const int CSIDL_COOKIES = 0x0021; internal const int CSIDL_FAVORITES = 0x0006; internal const int CSIDL_HISTORY = 0x0022; internal const int CSIDL_INTERNET_CACHE = 0x0020; internal const int CSIDL_PROGRAMS = 0x0002; internal const int CSIDL_RECENT = 0x0008; internal const int CSIDL_SENDTO = 0x0009; internal const int CSIDL_STARTMENU = 0x000b; internal const int CSIDL_STARTUP = 0x0007; internal const int CSIDL_SYSTEM = 0x0025; internal const int CSIDL_TEMPLATES = 0x0015; internal const int CSIDL_DESKTOPDIRECTORY = 0x0010; internal const int CSIDL_PERSONAL = 0x0005; internal const int CSIDL_PROGRAM_FILES = 0x0026; internal const int CSIDL_PROGRAM_FILES_COMMON = 0x002b; internal const int CSIDL_DESKTOP = 0x0000; internal const int CSIDL_DRIVES = 0x0011; internal const int CSIDL_MYMUSIC = 0x000d; internal const int CSIDL_MYPICTURES = 0x0027; internal const int NameSamCompatible = 2; [DllImport(USER32, SetLastError = true, BestFitMapping = false)] internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, String lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult); [DllImport(KERNEL32, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime); internal const byte VER_GREATER_EQUAL = 0x3; internal const uint VER_MAJORVERSION = 0x0000002; internal const uint VER_MINORVERSION = 0x0000001; internal const uint VER_SERVICEPACKMAJOR = 0x0000020; internal const uint VER_SERVICEPACKMINOR = 0x0000010; [DllImport("kernel32.dll")] internal static extern bool VerifyVersionInfoW([In, Out] OSVERSIONINFOEX lpVersionInfo, uint dwTypeMask, ulong dwlConditionMask); [DllImport("kernel32.dll")] internal static extern ulong VerSetConditionMask(ulong dwlConditionMask, uint dwTypeBitMask, byte dwConditionMask); } }
namespace java.lang { [global::MonoJavaBridge.JavaClass()] public sealed partial class System : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal System(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public static void exit(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m0.native == global::System.IntPtr.Zero) global::java.lang.System._m0 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "exit", "(I)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public static void runFinalizersOnExit(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m1.native == global::System.IntPtr.Zero) global::java.lang.System._m1 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "runFinalizersOnExit", "(Z)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public static global::java.lang.String setProperty(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m2.native == global::System.IntPtr.Zero) global::java.lang.System._m2 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m3; public static global::java.lang.String getProperty(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m3.native == global::System.IntPtr.Zero) global::java.lang.System._m3 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "getProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m4; public static global::java.lang.String getProperty(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m4.native == global::System.IntPtr.Zero) global::java.lang.System._m4 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m5; public static int identityHashCode(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m5.native == global::System.IntPtr.Zero) global::java.lang.System._m5 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "identityHashCode", "(Ljava/lang/Object;)I"); return @__env.CallStaticIntMethod(java.lang.System.staticClass, global::java.lang.System._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public static long currentTimeMillis() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m6.native == global::System.IntPtr.Zero) global::java.lang.System._m6 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "currentTimeMillis", "()J"); return @__env.CallStaticLongMethod(java.lang.System.staticClass, global::java.lang.System._m6); } private static global::MonoJavaBridge.MethodId _m7; public static long nanoTime() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m7.native == global::System.IntPtr.Zero) global::java.lang.System._m7 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "nanoTime", "()J"); return @__env.CallStaticLongMethod(java.lang.System.staticClass, global::java.lang.System._m7); } private static global::MonoJavaBridge.MethodId _m8; public static void arraycopy(java.lang.Object arg0, int arg1, java.lang.Object arg2, int arg3, int arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m8.native == global::System.IntPtr.Zero) global::java.lang.System._m8 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "arraycopy", "(Ljava/lang/Object;ILjava/lang/Object;II)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } public static global::java.lang.SecurityManager SecurityManager { get { return getSecurityManager(); } set { setSecurityManager(value); } } private static global::MonoJavaBridge.MethodId _m9; public static global::java.lang.SecurityManager getSecurityManager() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m9.native == global::System.IntPtr.Zero) global::java.lang.System._m9 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "getSecurityManager", "()Ljava/lang/SecurityManager;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m9)) as java.lang.SecurityManager; } private static global::MonoJavaBridge.MethodId _m10; public static void loadLibrary(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m10.native == global::System.IntPtr.Zero) global::java.lang.System._m10 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "loadLibrary", "(Ljava/lang/String;)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m11; public static global::java.lang.String mapLibraryName(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m11.native == global::System.IntPtr.Zero) global::java.lang.System._m11 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "mapLibraryName", "(Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m12; public static void load(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m12.native == global::System.IntPtr.Zero) global::java.lang.System._m12 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "load", "(Ljava/lang/String;)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static global::java.io.InputStream In { set { setIn(value); } } private static global::MonoJavaBridge.MethodId _m13; public static void setIn(java.io.InputStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m13.native == global::System.IntPtr.Zero) global::java.lang.System._m13 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "setIn", "(Ljava/io/InputStream;)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static global::java.io.PrintStream Out { set { setOut(value); } } private static global::MonoJavaBridge.MethodId _m14; public static void setOut(java.io.PrintStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m14.native == global::System.IntPtr.Zero) global::java.lang.System._m14 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "setOut", "(Ljava/io/PrintStream;)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static global::java.io.PrintStream Err { set { setErr(value); } } private static global::MonoJavaBridge.MethodId _m15; public static void setErr(java.io.PrintStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m15.native == global::System.IntPtr.Zero) global::java.lang.System._m15 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "setErr", "(Ljava/io/PrintStream;)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public static global::java.nio.channels.Channel inheritedChannel() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m16.native == global::System.IntPtr.Zero) global::java.lang.System._m16 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "inheritedChannel", "()Ljava/nio/channels/Channel;"); return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.nio.channels.Channel>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m16)) as java.nio.channels.Channel; } private static global::MonoJavaBridge.MethodId _m17; public static void setSecurityManager(java.lang.SecurityManager arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m17.native == global::System.IntPtr.Zero) global::java.lang.System._m17 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "setSecurityManager", "(Ljava/lang/SecurityManager;)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static global::java.util.Properties Properties { get { return getProperties(); } set { setProperties(value); } } private static global::MonoJavaBridge.MethodId _m18; public static global::java.util.Properties getProperties() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m18.native == global::System.IntPtr.Zero) global::java.lang.System._m18 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "getProperties", "()Ljava/util/Properties;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m18)) as java.util.Properties; } private static global::MonoJavaBridge.MethodId _m19; public static void setProperties(java.util.Properties arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m19.native == global::System.IntPtr.Zero) global::java.lang.System._m19 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "setProperties", "(Ljava/util/Properties;)V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public static global::java.lang.String clearProperty(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m20.native == global::System.IntPtr.Zero) global::java.lang.System._m20 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "clearProperty", "(Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m21; public static global::java.lang.String getenv(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m21.native == global::System.IntPtr.Zero) global::java.lang.System._m21 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "getenv", "(Ljava/lang/String;)Ljava/lang/String;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } public static global::java.util.Map env { get { return getenv(); } } private static global::MonoJavaBridge.MethodId _m22; public static global::java.util.Map getenv() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m22.native == global::System.IntPtr.Zero) global::java.lang.System._m22 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "getenv", "()Ljava/util/Map;"); return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Map>(@__env.CallStaticObjectMethod(java.lang.System.staticClass, global::java.lang.System._m22)) as java.util.Map; } private static global::MonoJavaBridge.MethodId _m23; public static void gc() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m23.native == global::System.IntPtr.Zero) global::java.lang.System._m23 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "gc", "()V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m23); } private static global::MonoJavaBridge.MethodId _m24; public static void runFinalization() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.lang.System._m24.native == global::System.IntPtr.Zero) global::java.lang.System._m24 = @__env.GetStaticMethodIDNoThrow(global::java.lang.System.staticClass, "runFinalization", "()V"); @__env.CallStaticVoidMethod(java.lang.System.staticClass, global::java.lang.System._m24); } internal static global::MonoJavaBridge.FieldId _in6387; public static global::java.io.InputStream @in { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.lang.System.staticClass, _in6387)) as java.io.InputStream; } } internal static global::MonoJavaBridge.FieldId _out6388; public static global::java.io.PrintStream @out { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.lang.System.staticClass, _out6388)) as java.io.PrintStream; } } internal static global::MonoJavaBridge.FieldId _err6389; public static global::java.io.PrintStream err { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::java.lang.System.staticClass, _err6389)) as java.io.PrintStream; } } static System() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.lang.System.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/lang/System")); global::java.lang.System._in6387 = @__env.GetStaticFieldIDNoThrow(global::java.lang.System.staticClass, "@in", "Ljava/io/InputStream;"); global::java.lang.System._out6388 = @__env.GetStaticFieldIDNoThrow(global::java.lang.System.staticClass, "@out", "Ljava/io/PrintStream;"); global::java.lang.System._err6389 = @__env.GetStaticFieldIDNoThrow(global::java.lang.System.staticClass, "err", "Ljava/io/PrintStream;"); } } }
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; namespace Faithlife.Utility { /// <summary> /// Methods for encoding and decoding URL-style strings. /// </summary> public static class UrlEncoding { /// <summary> /// Encodes a string with the default settings. /// </summary> /// <param name="value">The string to encode.</param> /// <returns>The encoded string.</returns> [return: NotNullIfNotNull("value")] public static string? Encode(string? value) => Encode(value, s_settingsDefault); /// <summary> /// Encodes a string with the specified settings. /// </summary> /// <param name="value">The string to encode.</param> /// <param name="settings">The settings to use when encoding.</param> /// <returns>The encoded string.</returns> [return: NotNullIfNotNull("value")] public static string? Encode(string? value, UrlEncodingSettings settings) { // check arguments if (settings is null) throw new ArgumentNullException(nameof(settings)); // null encodes to null if (value is null) return null; // empty string encodes to empty string if (value.Length == 0) return value; // convert string to array of characters var chars = value.ToCharArray(); var length = chars.Length; // count characters that should be encoded and spaces var charsToEncode = 0; for (var index = 0; index < length; index++) { if (ShouldEncodeChar(settings, chars, index)) charsToEncode++; } // we're done if there are no characters to encode if (charsToEncode == 0) return value; // each byte becomes 3 characters var encoding = settings.TextEncoding; var output = new char[length + 3 * settings.TextEncoding.GetMaxByteCount(charsToEncode)]; var outputChar = 0; // walk characters var encodedSpaceChar = settings.EncodedSpaceChar; var encodedBytePrefixChar = settings.EncodedBytePrefixChar; var encodeStart = 0; var encodeLength = 0; for (var index = 0; index < length; index++) { // determine if character needs to be encoded var shouldEncode = ShouldEncodeChar(settings, chars, index); var encodingSpaceChar = shouldEncode && chars[index] == ' ' && encodedSpaceChar.HasValue; // determine if the next character doesn't need text encoding if (!shouldEncode || encodingSpaceChar) { // encode any characters that needed text encoding if (encodeLength != 0) { foreach (var by in encoding.GetBytes(chars, encodeStart, encodeLength)) { output[outputChar++] = encodedBytePrefixChar; output[outputChar++] = HexChar((by >> 4) & 0xf, settings); output[outputChar++] = HexChar(by & 0xf, settings); } encodeLength = 0; } } if (encodingSpaceChar) { // encode space character directly output[outputChar++] = encodedSpaceChar!.Value; } else if (shouldEncode) { // start run of characters that need to be encoded if (encodeLength == 0) encodeStart = index; encodeLength++; } else { // copy character to destination output[outputChar++] = chars[index]; } } // encode any characters that needed text encoding if (encodeLength != 0) { foreach (var by in encoding.GetBytes(chars, encodeStart, encodeLength)) { output[outputChar++] = encodedBytePrefixChar; output[outputChar++] = HexChar((by >> 4) & 0xf, settings); output[outputChar++] = HexChar(by & 0xf, settings); } } // create new string from array of characters return new string(output, 0, outputChar); } /// <summary> /// Decodes a string with the default settings. /// </summary> /// <param name="value">The string to be decoded.</param> /// <returns>The decoded string.</returns> [return: NotNullIfNotNull("value")] public static string? Decode(string? value) => Decode(value, s_settingsDefault); /// <summary> /// Decodes a string with the specified settings. /// </summary> /// <param name="value">The string to be decoded.</param> /// <param name="settings">The settings to use when decoding.</param> /// <returns>The decoded string.</returns> [return: NotNullIfNotNull("value")] public static string? Decode(string? value, UrlEncodingSettings settings) { // check arguments if (settings is null) throw new ArgumentNullException(nameof(settings)); // null decodes to null if (value is null) return null; // empty string decodes to empty string if (value.Length == 0) return value; // replace encoded spaces if necessary if (settings.EncodedSpaceChar.HasValue) value = value.Replace(settings.EncodedSpaceChar.Value, ' '); // decode hex-encoded characters return value.IndexOfOrdinal(settings.EncodedBytePrefixChar) == -1 ? value : DecodeHex(value, settings); } private static string DecodeHex(string str, UrlEncodingSettings settings) { var output = new char[str.Length]; var outputIndex = 0; var singleByteArray = new byte[1]; var decoder = settings.TextEncoding.GetDecoder(); var isUtf8 = ReferenceEquals(settings.TextEncoding, Encoding.UTF8); // walk the string, looking for the prefix character for (var index = 0; index < str.Length; index++) { var ch = str[index]; if (index < str.Length - 2 && ch == settings.EncodedBytePrefixChar && IsCharHex(str[index + 1]) && IsCharHex(str[index + 2])) { // found two hex characters; add their byte value to the buffer var value = unchecked((byte) ((CharHex(str[index + 1]) << 4) + CharHex(str[index + 2]))); index += 2; if (isUtf8 && value <= 0x7F) { // this byte converts straight to the equivalent char output[outputIndex++] = (char) value; } else { // use the decoder to decode this byte singleByteArray[0] = value; outputIndex += decoder.GetChars(singleByteArray, 0, 1, output, outputIndex); } } else { // decode the buffer first if it contains data if (singleByteArray[0] != 0) { outputIndex += decoder.GetChars(singleByteArray, 0, 0, output, outputIndex, flush: true); singleByteArray[0] = 0; } // copy this character as-is output[outputIndex++] = ch; } } // decode any remaining bytes in the buffer if (singleByteArray[0] != 0) outputIndex += decoder.GetChars(singleByteArray, 0, 0, output, outputIndex, flush: true); return new string(output, 0, outputIndex); } private static bool IsCharHex(char ch) { return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'); } private static int CharHex(char ch) { Debug.Assert(IsCharHex(ch), "IsCharHex(ch)"); // convert hex nybble to integer ('1' == 1, A == '10', etc.) if (ch >= '0' && ch <= '9') return ch - '0'; else if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10; else return ch - 'A' + 10; } private static char HexChar(int n, UrlEncodingSettings settings) { // convert integer to hex nybble return (char) (n < 10 ? n + '0' : n - 10 + (settings.UppercaseHexDigits ? 'A' : 'a')); } private static bool ShouldEncodeChar(UrlEncodingSettings settings, char[] chars, int index) { var ch = chars[index]; // the char should be encoded if the user-supplied function indicates it should if (settings.ShouldEncodeChar(ch)) return true; // the char should be encoded if it's the char used to encode spaces if (settings.EncodedSpaceChar.HasValue && ch == settings.EncodedSpaceChar.Value) return true; // the char should be encoded if it's a space (and spaces have custom encodings) if (settings.EncodedSpaceChar.HasValue && ch == ' ') return true; // the char should be encoded if it's the char used to encode other characters return ch == settings.EncodedBytePrefixChar && !(settings.PreventDoubleEncoding && index + 2 < chars.Length && IsCharHex(chars[index + 1]) && IsCharHex(chars[index + 2])); } private static readonly UrlEncodingSettings s_settingsDefault = new UrlEncodingSettings(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace Vexe.Runtime.Extensions { public delegate void MemberSetter<TTarget, TValue>(ref TTarget target, TValue value); public delegate TReturn MemberGetter<TTarget, TReturn>(TTarget target); public delegate TReturn MethodCaller<TTarget, TReturn>(TTarget target, object[] args); public delegate T CtorInvoker<T>(object[] parameters); /// <summary> /// A dynamic reflection extensions library that emits IL to set/get fields/properties, call methods and invoke constructors /// Once the delegate is created, it can be stored and reused resulting in much faster access times than using regular reflection /// The results are cached. Once a delegate is generated, any subsequent call to generate the same delegate on the same field/property/method will return the previously generated delegate /// Note: Since this generates IL, it won't work on AOT platforms such as iOS an Android. But is useful and works very well in editor codes and standalone targets /// </summary> public static class FastReflection { private static ILEmitter emit = new ILEmitter(); private static Dictionary<int, Delegate> cache = new Dictionary<int, Delegate>(); private const string kCtorInvokerName = "CI<>"; private const string kMethodCallerName = "MC<>"; private const string kFieldSetterName = "FS<>"; private const string kFieldGetterName = "FG<>"; private const string kPropertySetterName = "PS<>"; private const string kPropertyGetterName = "PG<>"; /// <summary> /// Generates or gets a strongly-typed open-instance delegate to the specified type constructor that takes the specified type params /// </summary> public static CtorInvoker<T> DelegateForCtor<T>(this Type type, params Type[] paramTypes) { int key = kCtorInvokerName.GetHashCode() ^ type.GetHashCode(); for (int i = 0; i < paramTypes.Length; i++) key ^= paramTypes[i].GetHashCode(); Delegate result; if (cache.TryGetValue(key, out result)) return (CtorInvoker<T>) result; var dynMethod = new DynamicMethod(kCtorInvokerName, typeof(T), new Type[] { typeof(object[]) }); emit.il = dynMethod.GetILGenerator(); GenCtor<T>(type, paramTypes); result = dynMethod.CreateDelegate(typeof(CtorInvoker<T>)); cache[key] = result; return (CtorInvoker<T>) result; } /// <summary> /// Generates or gets a weakly-typed open-instance delegate to the specified type constructor that takes the specified type params /// </summary> public static CtorInvoker<object> DelegateForCtor(this Type type, params Type[] ctorParamTypes) { return DelegateForCtor<object>(type, ctorParamTypes); } /// <summary> /// Generates or gets a strongly-typed open-instance delegate to get the value of the specified property from a given target /// </summary> public static MemberGetter<TTarget, TReturn> DelegateForGet<TTarget, TReturn>(this PropertyInfo property) { if (!property.CanRead) throw new InvalidOperationException("Property is not readable " + property.Name); int key = GetKey<TTarget, TReturn>(property, kPropertyGetterName); Delegate result; if (cache.TryGetValue(key, out result)) return (MemberGetter<TTarget, TReturn>) result; return GenDelegateForMember<MemberGetter<TTarget, TReturn>, PropertyInfo>( property, key, kPropertyGetterName, GenPropertyGetter<TTarget>, typeof(TReturn), typeof(TTarget)); } /// <summary> /// Generates or gets a weakly-typed open-instance delegate to get the value of the specified property from a given target /// </summary> public static MemberGetter<object, object> DelegateForGet(this PropertyInfo property) { return DelegateForGet<object, object>(property); } /// <summary> /// Generates or gets a strongly-typed open-instance delegate to set the value of the specified property on a given target /// </summary> public static MemberSetter<TTarget, TValue> DelegateForSet<TTarget, TValue>(this PropertyInfo property) { if (!property.CanWrite) throw new InvalidOperationException("Property is not writable " + property.Name); int key = GetKey<TTarget, TValue>(property, kPropertySetterName); Delegate result; if (cache.TryGetValue(key, out result)) return (MemberSetter<TTarget, TValue>) result; return GenDelegateForMember<MemberSetter<TTarget, TValue>, PropertyInfo>( property, key, kPropertySetterName, GenPropertySetter<TTarget>, typeof(void), typeof(TTarget).MakeByRefType(), typeof(TValue)); } /// <summary> /// Generates or gets a weakly-typed open-instance delegate to set the value of the specified property on a given target /// </summary> public static MemberSetter<object, object> DelegateForSet(this PropertyInfo property) { return DelegateForSet<object, object>(property); } /// <summary> /// Generates an open-instance delegate to get the value of the property from a given target /// </summary> public static MemberGetter<TTarget, TReturn> DelegateForGet<TTarget, TReturn>(this FieldInfo field) { int key = GetKey<TTarget, TReturn>(field, kFieldGetterName); Delegate result; if (cache.TryGetValue(key, out result)) return (MemberGetter<TTarget, TReturn>) result; return GenDelegateForMember<MemberGetter<TTarget, TReturn>, FieldInfo>( field, key, kFieldGetterName, GenFieldGetter<TTarget>, typeof(TReturn), typeof(TTarget)); } /// <summary> /// Generates a weakly-typed open-instance delegate to set the value of the field in a given target /// </summary> public static MemberGetter<object, object> DelegateForGet(this FieldInfo field) { return DelegateForGet<object, object>(field); } /// <summary> /// Generates a strongly-typed open-instance delegate to set the value of the field in a given target /// </summary> public static MemberSetter<TTarget, TValue> DelegateForSet<TTarget, TValue>(this FieldInfo field) { int key = GetKey<TTarget, TValue>(field, kFieldSetterName); Delegate result; if (cache.TryGetValue(key, out result)) return (MemberSetter<TTarget, TValue>) result; return GenDelegateForMember<MemberSetter<TTarget, TValue>, FieldInfo>( field, key, kFieldSetterName, GenFieldSetter<TTarget>, typeof(void), typeof(TTarget).MakeByRefType(), typeof(TValue)); } /// <summary> /// Generates a weakly-typed open-instance delegate to set the value of the field in a given target /// </summary> public static MemberSetter<object, object> DelegateForSet(this FieldInfo field) { return DelegateForSet<object, object>(field); } /// <summary> /// Generates a strongly-typed open-instance delegate to invoke the specified method /// </summary> public static MethodCaller<TTarget, TReturn> DelegateForCall<TTarget, TReturn>(this MethodInfo method) { int key = GetKey<TTarget, TReturn>(method, kMethodCallerName); Delegate result; if (cache.TryGetValue(key, out result)) return (MethodCaller<TTarget, TReturn>) result; return GenDelegateForMember<MethodCaller<TTarget, TReturn>, MethodInfo>( method, key, kMethodCallerName, GenMethodInvocation<TTarget>, typeof(TReturn), typeof(TTarget), typeof(object[])); } /// <summary> /// Generates a weakly-typed open-instance delegate to invoke the specified method /// </summary> public static MethodCaller<object, object> DelegateForCall(this MethodInfo method) { return DelegateForCall<object, object>(method); } /// <summary> /// Executes the delegate on the specified target and arguments but only if it's not null /// </summary> public static void SafeInvoke<TTarget, TValue>(this MethodCaller<TTarget, TValue> caller, TTarget target, params object[] args) { if (caller != null) caller(target, args); } /// <summary> /// Executes the delegate on the specified target and value but only if it's not null /// </summary> public static void SafeInvoke<TTarget, TValue>(this MemberSetter<TTarget, TValue> setter, ref TTarget target, TValue value) { if (setter != null) setter(ref target, value); } /// <summary> /// Executes the delegate on the specified target only if it's not null, returns default(TReturn) otherwise /// </summary> public static TReturn SafeInvoke<TTarget, TReturn>(this MemberGetter<TTarget, TReturn> getter, TTarget target) { if (getter != null) return getter(target); return default(TReturn); } /// <summary> /// Generates a assembly called 'name' that's useful for debugging purposes and inspecting the resulting C# code in ILSpy /// If 'field' is not null, it generates a setter and getter for that field /// If 'property' is not null, it generates a setter and getter for that property /// If 'method' is not null, it generates a call for that method /// if 'targetType' and 'ctorParamTypes' are not null, it generates a constructor for the target type that takes the specified arguments /// </summary> public static void GenDebugAssembly(string name, FieldInfo field, PropertyInfo property, MethodInfo method, Type targetType, Type[] ctorParamTypes) { GenDebugAssembly<object>(name, field, property, method, targetType, ctorParamTypes); } /// <summary> /// Generates a assembly called 'name' that's useful for debugging purposes and inspecting the resulting C# code in ILSpy /// If 'field' is not null, it generates a setter and getter for that field /// If 'property' is not null, it generates a setter and getter for that property /// If 'method' is not null, it generates a call for that method /// if 'targetType' and 'ctorParamTypes' are not null, it generates a constructor for the target type that takes the specified arguments /// </summary> public static void GenDebugAssembly<TTarget>(string name, FieldInfo field, PropertyInfo property, MethodInfo method, Type targetType, Type[] ctorParamTypes) { var asmName = new AssemblyName("Asm"); var asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave); var modBuilder = asmBuilder.DefineDynamicModule("Mod", name); var typeBuilder = modBuilder.DefineType("Test", TypeAttributes.Public); var weakTyping = typeof(TTarget) == typeof(object); Func<string, Type, Type[], ILGenerator> buildMethod = (methodName, returnType, parameterTypes) => { var methodBuilder = typeBuilder.DefineMethod(methodName, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes); return methodBuilder.GetILGenerator(); }; if (field != null) { var fieldType = weakTyping ? typeof(object) : field.FieldType; emit.il = buildMethod("FieldSetter", typeof(void), new Type[] { typeof(TTarget).MakeByRefType(), fieldType }); GenFieldSetter<TTarget>(field); emit.il = buildMethod("FieldGetter", fieldType, new Type[] { typeof(TTarget) }); GenFieldGetter<TTarget>(field); } if (property != null) { var propType = weakTyping ? typeof(object) : property.PropertyType; emit.il = buildMethod("PropertySetter", typeof(void), new Type[] { typeof(TTarget).MakeByRefType(), propType }); GenPropertySetter<TTarget>(property); emit.il = buildMethod("PropertyGetter", propType, new Type[] { typeof(TTarget) }); GenPropertyGetter<TTarget>(property); } if (method != null) { var returnType = (weakTyping || method.ReturnType == typeof(void)) ? typeof(object) : method.ReturnType; emit.il = buildMethod("MethodCaller", returnType, new Type[] { typeof(TTarget), typeof(object[]) }); GenMethodInvocation<TTarget>(method); } if (targetType != null) { emit.il = buildMethod("Ctor", typeof(TTarget), new Type[] { typeof(object[]) }); GenCtor<TTarget>(targetType, ctorParamTypes); } typeBuilder.CreateType(); asmBuilder.Save(name); } private static int GetKey<T, R>(MemberInfo member, string dynMethodName) { return member.GetHashCode() ^ dynMethodName.GetHashCode() ^ typeof(T).GetHashCode() ^ typeof(R).GetHashCode(); } private static TDelegate GenDelegateForMember<TDelegate, TMember>(TMember member, int key, string dynMethodName, Action<TMember> generator, Type returnType, params Type[] paramTypes) where TMember : MemberInfo where TDelegate : class { var dynMethod = new DynamicMethod(dynMethodName, returnType, paramTypes, true); emit.il = dynMethod.GetILGenerator(); generator(member); var result = dynMethod.CreateDelegate(typeof(TDelegate)); cache[key] = result; return (TDelegate) (object) result; } private static void GenCtor<T>(Type type, Type[] paramTypes) { // arg0: object[] arguments // goal: return new T(arguments) Type targetType = typeof(T) == typeof(object) ? type : typeof(T); if (targetType.IsValueType && paramTypes.Length == 0) { var tmp = emit.declocal(targetType); emit.ldloca(tmp) .initobj(targetType) .ldloc(0); } else { var ctor = targetType.GetConstructor(paramTypes); if (ctor == null) throw new Exception("Generating constructor for type: " + targetType + (paramTypes.Length == 0 ? "No empty constructor found!" : "No constructor found that matches the following parameter types: " + string.Join(",", paramTypes.Select(x => x.Name).ToArray()))); // push parameters in order to then call ctor for (int i = 0, imax = paramTypes.Length; i < imax; i++) { emit.ldarg0() // push args array .ldc_i4(i) // push index .ldelem_ref() // push array[index] .unbox_any(paramTypes[i]); // cast } emit.newobj(ctor); } if (typeof(T) == typeof(object) && targetType.IsValueType) emit.box(targetType); emit.ret(); } private static void GenMethodInvocation<TTarget>(MethodInfo method) { var weaklyTyped = typeof(TTarget) == typeof(object); // push target if not static (instance-method. in that case first arg is always 'this') if (!method.IsStatic) { var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget); emit.declocal(targetType); emit.ldarg0(); if (weaklyTyped) emit.unbox_any(targetType); emit.stloc0() .ifclass_ldloc_else_ldloca(0, targetType); } // push arguments in order to call method var prams = method.GetParameters(); for (int i = 0, imax = prams.Length; i < imax; i++) { emit.ldarg1() // push array .ldc_i4(i) // push index .ldelem_ref(); // pop array, index and push array[index] var param = prams[i]; var dataType = param.ParameterType; if (dataType.IsByRef) dataType = dataType.GetElementType(); var tmp = emit.declocal(dataType); emit.unbox_any(dataType) .stloc(tmp) .ifbyref_ldloca_else_ldloc(tmp, param.ParameterType); } // perform the correct call (pushes the result) emit.callorvirt(method); // if method wasn't static that means we declared a temp local to load the target // that means our local variables index for the arguments start from 1 int localVarStart = method.IsStatic ? 0 : 1; for (int i = 0; i < prams.Length; i++) { var paramType = prams[i].ParameterType; if (paramType.IsByRef) { var byRefType = paramType.GetElementType(); emit.ldarg1() .ldc_i4(i) .ldloc(i + localVarStart); if (byRefType.IsValueType) emit.box(byRefType); emit.stelem_ref(); } } if (method.ReturnType == typeof(void)) emit.ldnull(); else if (weaklyTyped) emit.ifvaluetype_box(method.ReturnType); emit.ret(); } private static void GenFieldGetter<TTarget>(FieldInfo field) { GenMemberGetter<TTarget>(field, field.FieldType, field.IsStatic, (e, f) => e.lodfld((FieldInfo) f)); } private static void GenPropertyGetter<TTarget>(PropertyInfo property) { GenMemberGetter<TTarget>(property, property.PropertyType, property.GetGetMethod(true).IsStatic, (e, p) => e.callorvirt(((PropertyInfo) p).GetGetMethod(true))); } private static void GenMemberGetter<TTarget>(MemberInfo member, Type memberType, bool isStatic, Action<ILEmitter, MemberInfo> get) { if (typeof(TTarget) == typeof(object)) // weakly-typed? { // if we're static immediately load member and return value // otherwise load and cast target, get the member value and box it if neccessary: // return ((DeclaringType)target).member; if (!isStatic) emit.ldarg0() .unboxorcast(member.DeclaringType); emit.perform(get, member) .ifvaluetype_box(memberType); } else // we're strongly-typed, don't need any casting or boxing { // if we're static return member value immediately // otherwise load target and get member value immeidately // return target.member; if (!isStatic) emit.ifclass_ldarg_else_ldarga(0, typeof(TTarget)); emit.perform(get, member); } emit.ret(); } private static void GenFieldSetter<TTarget>(FieldInfo field) { GenMemberSetter<TTarget>(field, field.FieldType, field.IsStatic, (e, f) => e.setfld((FieldInfo) f)); } private static void GenPropertySetter<TTarget>(PropertyInfo property) { GenMemberSetter<TTarget>(property, property.PropertyType, property.GetSetMethod(true).IsStatic, (e, p) => e.callorvirt(((PropertyInfo) p).GetSetMethod(true))); } private static void GenMemberSetter<TTarget>(MemberInfo member, Type memberType, bool isStatic, Action<ILEmitter, MemberInfo> set) { var targetType = typeof(TTarget); var stronglyTyped = targetType != typeof(object); // if we're static set member immediately if (isStatic) { emit.ldarg1(); if (!stronglyTyped) emit.unbox_any(memberType); emit.perform(set, member) .ret(); return; } if (stronglyTyped) { // push target and value argument, set member immediately // target.member = value; emit.ldarg0() .ifclass_ldind_ref(targetType) .ldarg1() .perform(set, member) .ret(); return; } // we're weakly-typed targetType = member.DeclaringType; if (!targetType.IsValueType) // are we a reference-type? { // load and cast target, load and cast value and set // ((TargetType)target).member = (MemberType)value; emit.ldarg0() .ldind_ref() .cast(targetType) .ldarg1() .unbox_any(memberType) .perform(set, member) .ret(); return; } // we're a value-type // handle boxing/unboxing for the user so he doesn't have to do it himself // here's what we're basically generating (remember, we're weakly typed, so // the target argument is of type object here): // TargetType tmp = (TargetType)target; // unbox // tmp.member = (MemberField)value; // set member value // target = tmp; // box back emit.declocal(targetType); emit.ldarg0() .ldind_ref() .unbox_any(targetType) .stloc0() .ldloca(0) .ldarg1() .unbox_any(memberType) .perform(set, member) .ldarg0() .ldloc0() .box(targetType) .stind_ref() .ret(); } private class ILEmitter { public ILGenerator il; public ILEmitter ret() { il.Emit(OpCodes.Ret); return this; } public ILEmitter cast(Type type) { il.Emit(OpCodes.Castclass, type); return this; } public ILEmitter box(Type type) { il.Emit(OpCodes.Box, type); return this; } public ILEmitter unbox_any(Type type) { il.Emit(OpCodes.Unbox_Any, type); return this; } public ILEmitter unbox(Type type) { il.Emit(OpCodes.Unbox, type); return this; } public ILEmitter call(MethodInfo method) { il.Emit(OpCodes.Call, method); return this; } public ILEmitter callvirt(MethodInfo method) { il.Emit(OpCodes.Callvirt, method); return this; } public ILEmitter ldnull() { il.Emit(OpCodes.Ldnull); return this; } public ILEmitter bne_un(Label target) { il.Emit(OpCodes.Bne_Un, target); return this; } public ILEmitter beq(Label target) { il.Emit(OpCodes.Beq, target); return this; } public ILEmitter ldc_i4_0() { il.Emit(OpCodes.Ldc_I4_0); return this; } public ILEmitter ldc_i4_1() { il.Emit(OpCodes.Ldc_I4_1); return this; } public ILEmitter ldc_i4(int c) { il.Emit(OpCodes.Ldc_I4, c); return this; } public ILEmitter ldarg0() { il.Emit(OpCodes.Ldarg_0); return this; } public ILEmitter ldarg1() { il.Emit(OpCodes.Ldarg_1); return this; } public ILEmitter ldarg2() { il.Emit(OpCodes.Ldarg_2); return this; } public ILEmitter ldarga(int idx) { il.Emit(OpCodes.Ldarga, idx); return this; } public ILEmitter ldarga_s(int idx) { il.Emit(OpCodes.Ldarga_S, idx); return this; } public ILEmitter ldarg(int idx) { il.Emit(OpCodes.Ldarg, idx); return this; } public ILEmitter ldarg_s(int idx) { il.Emit(OpCodes.Ldarg_S, idx); return this; } public ILEmitter ifclass_ldind_ref(Type type) { if (!type.IsValueType) il.Emit(OpCodes.Ldind_Ref); return this; } public ILEmitter ldloc0() { il.Emit(OpCodes.Ldloc_0); return this; } public ILEmitter ldloc1() { il.Emit(OpCodes.Ldloc_1); return this; } public ILEmitter ldloc2() { il.Emit(OpCodes.Ldloc_2); return this; } public ILEmitter ldloca_s(int idx) { il.Emit(OpCodes.Ldloca_S, idx); return this; } public ILEmitter ldloca_s(LocalBuilder local) { il.Emit(OpCodes.Ldloca_S, local); return this; } public ILEmitter ldloc_s(int idx) { il.Emit(OpCodes.Ldloc_S, idx); return this; } public ILEmitter ldloc_s(LocalBuilder local) { il.Emit(OpCodes.Ldloc_S, local); return this; } public ILEmitter ldloca(int idx) { il.Emit(OpCodes.Ldloca, idx); return this; } public ILEmitter ldloca(LocalBuilder local) { il.Emit(OpCodes.Ldloca, local); return this; } public ILEmitter ldloc(int idx) { il.Emit(OpCodes.Ldloc, idx); return this; } public ILEmitter ldloc(LocalBuilder local) { il.Emit(OpCodes.Ldloc, local); return this; } public ILEmitter initobj(Type type) { il.Emit(OpCodes.Initobj, type); return this; } public ILEmitter newobj(ConstructorInfo ctor) { il.Emit(OpCodes.Newobj, ctor); return this; } public ILEmitter Throw() { il.Emit(OpCodes.Throw); return this; } public ILEmitter throw_new(Type type) { var exp = type.GetConstructor(Type.EmptyTypes); newobj(exp).Throw(); return this; } public ILEmitter stelem_ref() { il.Emit(OpCodes.Stelem_Ref); return this; } public ILEmitter ldelem_ref() { il.Emit(OpCodes.Ldelem_Ref); return this; } public ILEmitter ldlen() { il.Emit(OpCodes.Ldlen); return this; } public ILEmitter stloc(int idx) { il.Emit(OpCodes.Stloc, idx); return this; } public ILEmitter stloc_s(int idx) { il.Emit(OpCodes.Stloc_S, idx); return this; } public ILEmitter stloc(LocalBuilder local) { il.Emit(OpCodes.Stloc, local); return this; } public ILEmitter stloc_s(LocalBuilder local) { il.Emit(OpCodes.Stloc_S, local); return this; } public ILEmitter stloc0() { il.Emit(OpCodes.Stloc_0); return this; } public ILEmitter stloc1() { il.Emit(OpCodes.Stloc_1); return this; } public ILEmitter mark(Label label) { il.MarkLabel(label); return this; } public ILEmitter ldfld(FieldInfo field) { il.Emit(OpCodes.Ldfld, field); return this; } public ILEmitter ldsfld(FieldInfo field) { il.Emit(OpCodes.Ldsfld, field); return this; } public ILEmitter lodfld(FieldInfo field) { if (field.IsStatic) ldsfld(field); else ldfld(field); return this; } public ILEmitter ifvaluetype_box(Type type) { if (type.IsValueType) il.Emit(OpCodes.Box, type); return this; } public ILEmitter stfld(FieldInfo field) { il.Emit(OpCodes.Stfld, field); return this; } public ILEmitter stsfld(FieldInfo field) { il.Emit(OpCodes.Stsfld, field); return this; } public ILEmitter setfld(FieldInfo field) { if (field.IsStatic) stsfld(field); else stfld(field); return this; } public ILEmitter unboxorcast(Type type) { if (type.IsValueType) unbox(type); else cast(type); return this; } public ILEmitter callorvirt(MethodInfo method) { if (method.IsVirtual) il.Emit(OpCodes.Callvirt, method); else il.Emit(OpCodes.Call, method); return this; } public ILEmitter stind_ref() { il.Emit(OpCodes.Stind_Ref); return this; } public ILEmitter ldind_ref() { il.Emit(OpCodes.Ldind_Ref); return this; } public LocalBuilder declocal(Type type) { return il.DeclareLocal(type); } public Label deflabel() { return il.DefineLabel(); } public ILEmitter ifclass_ldarg_else_ldarga(int idx, Type type) { if (type.IsValueType) emit.ldarga(idx); else emit.ldarg(idx); return this; } public ILEmitter ifclass_ldloc_else_ldloca(int idx, Type type) { if (type.IsValueType) emit.ldloca(idx); else emit.ldloc(idx); return this; } public ILEmitter perform(Action<ILEmitter, MemberInfo> action, MemberInfo member) { action(this, member); return this; } public ILEmitter ifbyref_ldloca_else_ldloc(LocalBuilder local, Type type) { if (type.IsByRef) ldloca(local); else ldloc(local); return this; } } } }
// 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.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class PreIncrementAssignTests : IncDecAssignTests { [Theory] [PerCompilationType(nameof(Int16sAndIncrements))] [PerCompilationType(nameof(NullableInt16sAndIncrements))] [PerCompilationType(nameof(UInt16sAndIncrements))] [PerCompilationType(nameof(NullableUInt16sAndIncrements))] [PerCompilationType(nameof(Int32sAndIncrements))] [PerCompilationType(nameof(NullableInt32sAndIncrements))] [PerCompilationType(nameof(UInt32sAndIncrements))] [PerCompilationType(nameof(NullableUInt32sAndIncrements))] [PerCompilationType(nameof(Int64sAndIncrements))] [PerCompilationType(nameof(NullableInt64sAndIncrements))] [PerCompilationType(nameof(UInt64sAndIncrements))] [PerCompilationType(nameof(NullableUInt64sAndIncrements))] [PerCompilationType(nameof(DecimalsAndIncrements))] [PerCompilationType(nameof(NullableDecimalsAndIncrements))] [PerCompilationType(nameof(SinglesAndIncrements))] [PerCompilationType(nameof(NullableSinglesAndIncrements))] [PerCompilationType(nameof(DoublesAndIncrements))] [PerCompilationType(nameof(NullableDoublesAndIncrements))] public void ReturnsCorrectValues(Type type, object value, object result, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PreIncrementAssign(variable) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(Int16sAndIncrements))] [PerCompilationType(nameof(NullableInt16sAndIncrements))] [PerCompilationType(nameof(UInt16sAndIncrements))] [PerCompilationType(nameof(NullableUInt16sAndIncrements))] [PerCompilationType(nameof(Int32sAndIncrements))] [PerCompilationType(nameof(NullableInt32sAndIncrements))] [PerCompilationType(nameof(UInt32sAndIncrements))] [PerCompilationType(nameof(NullableUInt32sAndIncrements))] [PerCompilationType(nameof(Int64sAndIncrements))] [PerCompilationType(nameof(NullableInt64sAndIncrements))] [PerCompilationType(nameof(UInt64sAndIncrements))] [PerCompilationType(nameof(NullableUInt64sAndIncrements))] [PerCompilationType(nameof(DecimalsAndIncrements))] [PerCompilationType(nameof(NullableDecimalsAndIncrements))] [PerCompilationType(nameof(SinglesAndIncrements))] [PerCompilationType(nameof(NullableSinglesAndIncrements))] [PerCompilationType(nameof(DoublesAndIncrements))] [PerCompilationType(nameof(NullableDoublesAndIncrements))] public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter) { ParameterExpression variable = Expression.Variable(type); LabelTarget target = Expression.Label(type); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant(value, type)), Expression.PreIncrementAssign(variable), Expression.Return(target, variable), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void SingleNanToNan(bool useInterpreter) { TestPropertyClass<float> instance = new TestPropertyClass<float>(); instance.TestInstance = float.NaN; Assert.True(float.IsNaN( Expression.Lambda<Func<float>>( Expression.PreIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<float>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(float.IsNaN(instance.TestInstance)); } [Theory] [ClassData(typeof(CompilationTypes))] public void DoubleNanToNan(bool useInterpreter) { TestPropertyClass<double> instance = new TestPropertyClass<double>(); instance.TestInstance = double.NaN; Assert.True(double.IsNaN( Expression.Lambda<Func<double>>( Expression.PreIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<double>), "TestInstance" ) ) ).Compile(useInterpreter)() )); Assert.True(double.IsNaN(instance.TestInstance)); } [Theory] [PerCompilationType(nameof(IncrementOverflowingValues))] public void OverflowingValuesThrow(object value, bool useInterpreter) { ParameterExpression variable = Expression.Variable(value.GetType()); Action overflow = Expression.Lambda<Action>( Expression.Block( typeof(void), new[] { variable }, Expression.Assign(variable, Expression.Constant(value)), Expression.PreIncrementAssign(variable) ) ).Compile(useInterpreter); Assert.Throws<OverflowException>(overflow); } [Theory] [MemberData(nameof(UnincrementableAndUndecrementableTypes))] public void InvalidOperandType(Type type) { ParameterExpression variable = Expression.Variable(type); Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable)); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectResult(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")) ); Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Theory] [ClassData(typeof(CompilationTypes))] public void MethodCorrectAssign(bool useInterpreter) { ParameterExpression variable = Expression.Variable(typeof(string)); LabelTarget target = Expression.Label(typeof(string)); BlockExpression block = Expression.Block( new[] { variable }, Expression.Assign(variable, Expression.Constant("hello")), Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")), Expression.Return(target, variable), Expression.Label(target, Expression.Default(typeof(string))) ); Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)()); } [Fact] public void IncorrectMethodType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"); Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable, method)); } [Fact] public void IncorrectMethodParameterCount() { Expression variable = Expression.Variable(typeof(string)); MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals"); Assert.Throws<ArgumentException>(() => Expression.PreIncrementAssign(variable, method)); } [Fact] public void IncorrectMethodReturnType() { Expression variable = Expression.Variable(typeof(int)); MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString"); Assert.Throws<ArgumentException>(() => Expression.PreIncrementAssign(variable, method)); } [Theory] [ClassData(typeof(CompilationTypes))] public void StaticMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<uint>.TestStatic = 2U; Assert.Equal( 3U, Expression.Lambda<Func<uint>>( Expression.PreIncrementAssign( Expression.Property(null, typeof(TestPropertyClass<uint>), "TestStatic") ) ).Compile(useInterpreter)() ); Assert.Equal(3U, TestPropertyClass<uint>.TestStatic); } [Theory] [ClassData(typeof(CompilationTypes))] public void InstanceMemberAccessCorrect(bool useInterpreter) { TestPropertyClass<int> instance = new TestPropertyClass<int>(); instance.TestInstance = 2; Assert.Equal( 3, Expression.Lambda<Func<int>>( Expression.PreIncrementAssign( Expression.Property( Expression.Constant(instance), typeof(TestPropertyClass<int>), "TestInstance" ) ) ).Compile(useInterpreter)() ); Assert.Equal(3, instance.TestInstance); } [Theory] [ClassData(typeof(CompilationTypes))] public void ArrayAccessCorrect(bool useInterpreter) { int[] array = new int[1]; array[0] = 2; Assert.Equal( 3, Expression.Lambda<Func<int>>( Expression.PreIncrementAssign( Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0)) ) ).Compile(useInterpreter)() ); Assert.Equal(3, array[0]); } [Fact] public void CanReduce() { ParameterExpression variable = Expression.Variable(typeof(int)); UnaryExpression op = Expression.PreIncrementAssign(variable); Assert.True(op.CanReduce); Assert.NotSame(op, op.ReduceAndCheck()); } [Fact] public void NullOperand() { Assert.Throws<ArgumentNullException>("expression", () => Expression.PreIncrementAssign(null)); } [Fact] public void UnwritableOperand() { Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(Expression.Constant(1))); } [Fact] public void UnreadableOperand() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(value)); } [Fact] public void UpdateSameOperandSameNode() { UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int))); Assert.Same(op, op.Update(op.Operand)); } [Fact] public void UpdateDiffOperandDiffNode() { UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int))); Assert.NotSame(op, op.Update(Expression.Variable(typeof(int)))); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.Xml.Serialization; using System.ServiceModel.Diagnostics; using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.Serialization.Diagnostics; #if USE_REFEMIT public class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerWriteContext : XmlObjectSerializerContext #endif { ObjectReferenceStack byValObjectsInScope = new ObjectReferenceStack(); XmlSerializableWriter xmlSerializableWriter; const int depthToCheckCyclicReference = 512; protected bool preserveObjectReferences; ObjectToIdCache serializedObjects; bool isGetOnlyCollection; readonly bool unsafeTypeForwardingEnabled; protected bool serializeReadOnlyTypes; internal static XmlObjectSerializerWriteContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.DataContractSurrogate != null) ? new XmlObjectSerializerWriteContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerWriteContext(serializer, rootTypeDataContract, dataContractResolver); } internal static XmlObjectSerializerWriteContext CreateContext(NetDataContractSerializer serializer, Hashtable surrogateDataContracts) { return new XmlObjectSerializerWriteContextComplex(serializer, surrogateDataContracts); } protected XmlObjectSerializerWriteContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver resolver) : base(serializer, rootTypeDataContract, resolver) { this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; // Known types restricts the set of types that can be deserialized this.unsafeTypeForwardingEnabled = true; } protected XmlObjectSerializerWriteContext(NetDataContractSerializer serializer) : base(serializer) { this.unsafeTypeForwardingEnabled = NetDataContractSerializer.UnsafeTypeForwardingEnabled; } internal XmlObjectSerializerWriteContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { // Known types restricts the set of types that can be deserialized this.unsafeTypeForwardingEnabled = true; } #if USE_REFEMIT internal ObjectToIdCache SerializedObjects #else protected ObjectToIdCache SerializedObjects #endif { get { if (serializedObjects == null) serializedObjects = new ObjectToIdCache(); return serializedObjects; } } internal override bool IsGetOnlyCollection { get { return this.isGetOnlyCollection; } set { this.isGetOnlyCollection = value; } } internal bool SerializeReadOnlyTypes { get { return this.serializeReadOnlyTypes; } } internal bool UnsafeTypeForwardingEnabled { get { return this.unsafeTypeForwardingEnabled; } } #if USE_REFEMIT public void StoreIsGetOnlyCollection() #else internal void StoreIsGetOnlyCollection() #endif { this.isGetOnlyCollection = true; } public void InternalSerializeReference(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { if (!OnHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/)) InternalSerialize(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); OnEndHandleReference(xmlWriter, obj, true /*canContainCyclicReference*/); } public virtual void InternalSerialize(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) { if (writeXsiType) { Type declaredType = Globals.TypeOfObject; SerializeWithXsiType(xmlWriter, obj, Type.GetTypeHandle(obj), null/*type*/, -1, declaredType.TypeHandle, declaredType); } else if (isDeclaredType) { DataContract contract = GetDataContract(declaredTypeID, declaredTypeHandle); SerializeWithoutXsiType(contract, xmlWriter, obj, declaredTypeHandle); } else { RuntimeTypeHandle objTypeHandle = Type.GetTypeHandle(obj); if (declaredTypeHandle.Equals(objTypeHandle)) { DataContract dataContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, null /*type*/); SerializeWithoutXsiType(dataContract, xmlWriter, obj, declaredTypeHandle); } else { SerializeWithXsiType(xmlWriter, obj, objTypeHandle, null /*type*/, declaredTypeID, declaredTypeHandle, Type.GetTypeFromHandle(declaredTypeHandle)); } } } internal void SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); scopedKnownTypes.Pop(); } else { WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); } } internal virtual void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type declaredType = rootTypeDataContract.OriginalUnderlyingType; if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { if (DataContractResolver != null) { WriteResolvedTypeInfo(xmlWriter, graphType, declaredType); } } else if (!declaredType.IsArray) //Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, originalDeclaredTypeHandle, declaredType); } protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { DataContract dataContract; bool verifyKnownType = false; if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode)) dataContract = dataContract.GetValidContract(this.Mode); else dataContract = GetDataContract(declaredTypeHandle, declaredType); if (!WriteClrTypeInfo(xmlWriter, dataContract) && DataContractResolver != null) { if (objectType == null) { objectType = Type.GetTypeFromHandle(objectTypeHandle); } WriteResolvedTypeInfo(xmlWriter, objectType, declaredType); } } else if (declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { // A call to OnHandleIsReference is not necessary here -- arrays cannot be IsReference dataContract = GetDataContract(objectTypeHandle, objectType); WriteClrTypeInfo(xmlWriter, dataContract); dataContract = GetDataContract(declaredTypeHandle, declaredType); } else { dataContract = GetDataContract(objectTypeHandle, objectType); if (OnHandleIsReference(xmlWriter, dataContract, obj)) return; if (!WriteClrTypeInfo(xmlWriter, dataContract)) { DataContract declaredTypeContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType); verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract); } } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredTypeHandle, declaredType); } internal bool OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, object obj) { if (preserveObjectReferences || !contract.IsReference || isGetOnlyCollection) { return false; } bool isNew = true; int objectId = SerializedObjects.GetId(obj, ref isNew); byValObjectsInScope.EnsureSetAsIsReference(obj); if (isNew) { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return false; } else { xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId)); return true; } } protected void SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, bool verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (verifyKnownType) { if (!IsKnownType(dataContract, declaredType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } } WriteDataContractValue(dataContract, xmlWriter, obj, declaredTypeHandle); if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) { return false; } internal virtual bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, SerializationInfo serInfo) { return false; } public virtual void WriteAnyType(XmlWriterDelegator xmlWriter, object value) { xmlWriter.WriteAnyType(value); } public virtual void WriteString(XmlWriterDelegator xmlWriter, string value) { xmlWriter.WriteString(value); } public virtual void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteString(value); xmlWriter.WriteEndElementPrimitive(); } } public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value) { xmlWriter.WriteBase64(value); } public virtual void WriteBase64(XmlWriterDelegator xmlWriter, byte[] value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(byte[]), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteBase64(value); xmlWriter.WriteEndElementPrimitive(); } } public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value) { xmlWriter.WriteUri(value); } public virtual void WriteUri(XmlWriterDelegator xmlWriter, Uri value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(Uri), true/*isMemberTypeSerializable*/, name, ns); else { xmlWriter.WriteStartElementPrimitive(name, ns); xmlWriter.WriteUri(value); xmlWriter.WriteEndElementPrimitive(); } } public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value) { xmlWriter.WriteQName(value); } public virtual void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); else { if (ns != null && ns.Value != null && ns.Value.Length > 0) xmlWriter.WriteStartElement(Globals.ElementPrefix, name, ns); else xmlWriter.WriteStartElement(name, ns); xmlWriter.WriteQName(value); xmlWriter.WriteEndElement(); } } internal void HandleGraphAtTopLevel(XmlWriterDelegator writer, object obj, DataContract contract) { writer.WriteXmlnsAttribute(Globals.XsiPrefix, DictionaryGlobals.SchemaInstanceNamespace); if (contract.IsISerializable) writer.WriteXmlnsAttribute(Globals.XsdPrefix, DictionaryGlobals.SchemaNamespace); OnHandleReference(writer, obj, true /*canContainReferences*/); } internal virtual bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return false; if (canContainCyclicReference) { if (byValObjectsInScope.Count == 0 && DiagnosticUtility.ShouldTraceWarning) { TraceUtility.Trace(TraceEventType.Warning, TraceCode.ObjectWithLargeDepth, SR.GetString(SR.TraceCodeObjectWithLargeDepth)); } if (byValObjectsInScope.Contains(obj)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType())))); byValObjectsInScope.Push(obj); } return false; } internal virtual void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (xmlWriter.depth < depthToCheckCyclicReference) return; if (canContainCyclicReference) { byValObjectsInScope.Pop(obj); } } public void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); WriteNull(xmlWriter); } internal void WriteNull(XmlWriterDelegator xmlWriter, Type memberType, bool isMemberTypeSerializable, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteStartElement(name, ns); WriteNull(xmlWriter, memberType, isMemberTypeSerializable); xmlWriter.WriteEndElement(); } public void IncrementArrayCount(XmlWriterDelegator xmlWriter, Array array) { IncrementCollectionCount(xmlWriter, array.GetLength(0)); } public void IncrementCollectionCount(XmlWriterDelegator xmlWriter, ICollection collection) { IncrementCollectionCount(xmlWriter, collection.Count); } public void IncrementCollectionCountGeneric<T>(XmlWriterDelegator xmlWriter, ICollection<T> collection) { IncrementCollectionCount(xmlWriter, collection.Count); } void IncrementCollectionCount(XmlWriterDelegator xmlWriter, int size) { IncrementItemCount(size); WriteArraySize(xmlWriter, size); } internal virtual void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { } public static T GetDefaultValue<T>() { return default(T); } public static T GetNullableValue<T>(Nullable<T> value) where T : struct { // value.Value will throw if hasValue is false return value.Value; } public static void ThrowRequiredMemberMustBeEmitted(string memberName, Type type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.GetString(SR.RequiredMemberMustBeEmitted, memberName, type.FullName))); } public static bool GetHasValue<T>(Nullable<T> value) where T : struct { return value.HasValue; } internal void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { if (xmlSerializableWriter == null) xmlSerializableWriter = new XmlSerializableWriter(); WriteIXmlSerializable(xmlWriter, obj, xmlSerializableWriter); } internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, object obj) { WriteIXmlSerializable(xmlWriter, obj, new XmlSerializableWriter()); } static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter) { xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj); IXmlSerializable xmlSerializable = obj as IXmlSerializable; if (xmlSerializable != null) xmlSerializable.WriteXml(xmlSerializableWriter); else { XmlElement xmlElement = obj as XmlElement; if (xmlElement != null) xmlElement.WriteTo(xmlSerializableWriter); else { XmlNode[] xmlNodes = obj as XmlNode[]; if (xmlNodes != null) foreach (XmlNode xmlNode in xmlNodes) xmlNode.WriteTo(xmlSerializableWriter); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.UnknownXmlType, DataContract.GetClrTypeFullName(obj.GetType())))); } } xmlSerializableWriter.EndWrite(); } [Fx.Tag.SecurityNote(Critical = "Calls the critical methods of ISerializable", Safe = "Demanding Serialization formatter permission is enough.")] [SecuritySafeCritical] [MethodImpl(MethodImplOptions.NoInlining)] internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context) { // Demand the serialization formatter permission every time Globals.SerializationFormatterPermission.Demand(); obj.GetObjectData(serInfo, context); } public void WriteISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) { Type objType = obj.GetType(); SerializationInfo serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter, !this.UnsafeTypeForwardingEnabled); GetObjectData(obj, serInfo, GetStreamingContext()); if (!this.UnsafeTypeForwardingEnabled && serInfo.AssemblyName == Globals.MscorlibAssemblyName) { // Throw if a malicious type tries to set its assembly name to "0" to get deserialized in mscorlib throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ISerializableAssemblyNameSetToZero, DataContract.GetClrTypeFullName(obj.GetType())))); } WriteSerializationInfo(xmlWriter, objType, serInfo); } internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, SerializationInfo serInfo) { if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName) { if (DataContractResolver != null) { XmlDictionaryString typeName, typeNs; if (ResolveType(serInfo.ObjectType, objType, out typeName, out typeNs)) { xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, typeName, typeNs); } } else { string typeName, typeNs; DataContract.GetDefaultStableName(serInfo.FullTypeName, out typeName, out typeNs); xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, DataContract.GetClrTypeString(typeName), DataContract.GetClrTypeString(typeNs)); } } WriteClrTypeInfo(xmlWriter, objType, serInfo); IncrementItemCount(serInfo.MemberCount); foreach (SerializationEntry serEntry in serInfo) { XmlDictionaryString name = DataContract.GetClrTypeString(DataContract.EncodeLocalName(serEntry.Name)); xmlWriter.WriteStartElement(name, DictionaryGlobals.EmptyString); object obj = serEntry.Value; if (obj == null) WriteNull(xmlWriter); else InternalSerializeReference(xmlWriter, obj, false /*isDeclaredType*/, false /*writeXsiType*/, -1, Globals.TypeOfObject.TypeHandle); xmlWriter.WriteEndElement(); } } public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex) { if (IgnoreExtensionDataObject || extensionData == null) return; IList<ExtensionDataMember> members = extensionData.Members; if (members != null) { for (int i = 0; i < extensionData.Members.Count; i++) { ExtensionDataMember member = extensionData.Members[i]; if (member.MemberIndex == memberIndex) { WriteExtensionDataMember(xmlWriter, member); } } } } void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDataMember member) { xmlWriter.WriteStartElement(member.Name, member.Namespace); IDataNode dataNode = member.Value; WriteExtensionDataValue(xmlWriter, dataNode); xmlWriter.WriteEndElement(); } internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode) { if (dataNode.DataContractName != null) WriteTypeInfo(xmlWriter, dataNode.DataContractName, dataNode.DataContractNamespace); WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName); } internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode dataNode) { IncrementItemCount(1); if (dataNode == null) { WriteNull(xmlWriter); return; } if (dataNode.PreservesReferences && OnHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/)) return; Type dataType = dataNode.DataType; if (dataType == Globals.TypeOfClassDataNode) WriteExtensionClassData(xmlWriter, (ClassDataNode)dataNode); else if (dataType == Globals.TypeOfCollectionDataNode) WriteExtensionCollectionData(xmlWriter, (CollectionDataNode)dataNode); else if (dataType == Globals.TypeOfXmlDataNode) WriteExtensionXmlData(xmlWriter, (XmlDataNode)dataNode); else if (dataType == Globals.TypeOfISerializableDataNode) WriteExtensionISerializableData(xmlWriter, (ISerializableDataNode)dataNode); else { WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataType == Globals.TypeOfObject) { // NOTE: serialize value in DataNode<object> since it may contain non-primitive // deserialized object (ex. empty class) object o = dataNode.Value; if (o != null) InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, o.GetType().TypeHandle); } else xmlWriter.WriteExtensionData(dataNode); } if (dataNode.PreservesReferences) OnEndHandleReference(xmlWriter, (dataNode.Value == null ? dataNode : dataNode.Value), true /*canContainCyclicReference*/); } internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode) { object o = dataNode.Value; if (o == null) return false; Type declaredType = (dataNode.DataContractName == null) ? o.GetType() : Globals.TypeOfObject; InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, declaredType.TypeHandle); return true; } void WriteExtensionClassData(XmlWriterDelegator xmlWriter, ClassDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList<ExtensionDataMember> members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { WriteExtensionDataMember(xmlWriter, members[i]); } } } } void WriteExtensionCollectionData(XmlWriterDelegator xmlWriter, CollectionDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); WriteArraySize(xmlWriter, dataNode.Size); IList<IDataNode> items = dataNode.Items; if (items != null) { for (int i = 0; i < items.Count; i++) { xmlWriter.WriteStartElement(dataNode.ItemName, dataNode.ItemNamespace); WriteExtensionDataValue(xmlWriter, items[i]); xmlWriter.WriteEndElement(); } } } } void WriteExtensionISerializableData(XmlWriterDelegator xmlWriter, ISerializableDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { WriteExtensionDataTypeInfo(xmlWriter, dataNode); if (dataNode.FactoryTypeName != null) xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace); IList<ISerializableDataMember> members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) { ISerializableDataMember member = members[i]; xmlWriter.WriteStartElement(member.Name, String.Empty); WriteExtensionDataValue(xmlWriter, member.Value); xmlWriter.WriteEndElement(); } } } } void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dataNode) { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { IList<XmlAttribute> xmlAttributes = dataNode.XmlAttributes; if (xmlAttributes != null) { foreach (XmlAttribute attribute in xmlAttributes) attribute.WriteTo(xmlWriter.Writer); } WriteExtensionDataTypeInfo(xmlWriter, dataNode); IList<XmlNode> xmlChildNodes = dataNode.XmlChildNodes; if (xmlChildNodes != null) { foreach (XmlNode node in xmlChildNodes) node.WriteTo(xmlWriter.Writer); } } } protected virtual void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { dataContract.WriteXmlValue(xmlWriter, obj, this); } protected virtual void WriteNull(XmlWriterDelegator xmlWriter) { XmlObjectSerializer.WriteNull(xmlWriter); } void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType) { XmlDictionaryString typeName, typeNamespace; if (ResolveType(objectType, declaredType, out typeName, out typeNamespace)) { WriteTypeInfo(writer, typeName, typeNamespace); } } bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } if (typeName == null) { if (typeNamespace == null) { return false; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } } if (typeNamespace == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ResolveTypeReturnedNull, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); } return true; } protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if (!XmlObjectSerializer.IsContractDeclared(contract, declaredContract)) { if (DataContractResolver == null) { WriteTypeInfo(writer, contract.Name, contract.Namespace); return true; } else { WriteResolvedTypeInfo(writer, contract.OriginalUnderlyingType, declaredContract.OriginalUnderlyingType); return false; } } return false; } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryString dataContractName, XmlDictionaryString dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } } }
//--------------------------------------------------------------------- // <copyright file="EntityContainer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Data.Common; using System.Text; using System.Diagnostics; namespace System.Data.Metadata.Edm { /// <summary> /// Class for representing an entity container /// </summary> public sealed class EntityContainer : GlobalItem { #region Constructors /// <summary> /// The constructor for constructing the EntityContainer object with the name, namespaceName, and version. /// </summary> /// <param name="name">The name of this entity container</param> /// <param name="dataSpace">dataSpace in which this entity container belongs to</param> /// <exception cref="System.ArgumentNullException">Thrown if the name argument is null</exception> /// <exception cref="System.ArgumentException">Thrown if the name argument is empty string</exception> internal EntityContainer(string name, DataSpace dataSpace) { EntityUtil.CheckStringArgument(name, "name"); _name = name; this.DataSpace = dataSpace; _baseEntitySets = new ReadOnlyMetadataCollection<EntitySetBase>(new EntitySetBaseCollection(this)); _functionImports = new ReadOnlyMetadataCollection<EdmFunction>(new MetadataCollection<EdmFunction>()); } #endregion #region Fields private readonly string _name; private readonly ReadOnlyMetadataCollection<EntitySetBase> _baseEntitySets; private readonly ReadOnlyMetadataCollection<EdmFunction> _functionImports; #endregion #region Properties /// <summary> /// Returns the kind of the type /// </summary> public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.EntityContainer; } } /// <summary> /// Gets the identity for this item as a string /// </summary> internal override string Identity { get { return this.Name; } } /// <summary> /// Get the name of this EntityContainer object /// </summary> [MetadataProperty(PrimitiveTypeKind.String, false)] public String Name { get { return _name; } } /// <summary> /// Gets the collection of entity sets /// </summary> [MetadataProperty(BuiltInTypeKind.EntitySetBase, true)] public ReadOnlyMetadataCollection<EntitySetBase> BaseEntitySets { get { return _baseEntitySets; } } /// <summary> /// Gets the collection of function imports for this entity container /// </summary> [MetadataProperty(BuiltInTypeKind.EdmFunction, true)] public ReadOnlyMetadataCollection<EdmFunction> FunctionImports { get { return _functionImports; } } #endregion #region Methods /// <summary> /// Sets this item to be readonly, once this is set, the item will never be writable again. /// </summary> internal override void SetReadOnly() { if (!IsReadOnly) { base.SetReadOnly(); this.BaseEntitySets.Source.SetReadOnly(); this.FunctionImports.Source.SetReadOnly(); } } /// <summary> /// Get the entity set with the given name /// </summary> /// <param name="name">name of the entity set to look up for</param> /// <param name="ignoreCase">true if you want to do a case-insensitive lookup</param> /// <returns></returns> public EntitySet GetEntitySetByName(string name, bool ignoreCase) { EntitySet entitySet = (BaseEntitySets.GetValue(name, ignoreCase) as EntitySet); if (null != entitySet) { return entitySet; } throw EntityUtil.InvalidEntitySetName(name); } /// <summary> /// Get the entity set with the given name or return null if not found /// </summary> /// <param name="name">name of the entity set to look up for</param> /// <param name="ignoreCase">true if you want to do a case-insensitive lookup</param> /// <param name="entitySet">out parameter that will contain the result</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">if name argument is null</exception> public bool TryGetEntitySetByName(string name, bool ignoreCase, out EntitySet entitySet) { EntityUtil.CheckArgumentNull(name, "name"); EntitySetBase baseEntitySet = null; entitySet = null; if (this.BaseEntitySets.TryGetValue(name, ignoreCase, out baseEntitySet)) { if (Helper.IsEntitySet(baseEntitySet)) { entitySet = (EntitySet)baseEntitySet; return true; } } return false; } /// <summary> /// Get the relationship set with the given name /// </summary> /// <param name="name">name of the relationship set to look up for</param> /// <param name="ignoreCase">true if you want to do a case-insensitive lookup</param> /// <returns></returns> public RelationshipSet GetRelationshipSetByName(string name, bool ignoreCase) { RelationshipSet relationshipSet; if (!this.TryGetRelationshipSetByName(name, ignoreCase, out relationshipSet)) { throw EntityUtil.InvalidRelationshipSetName(name); } return relationshipSet; } /// <summary> /// Get the relationship set with the given name /// </summary> /// <param name="name">name of the relationship set to look up for</param> /// <param name="ignoreCase">true if you want to do a case-insensitive lookup</param> /// <param name="relationshipSet">out parameter that will have the result</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">if name argument is null</exception> public bool TryGetRelationshipSetByName(string name, bool ignoreCase, out RelationshipSet relationshipSet) { EntityUtil.CheckArgumentNull(name, "name"); EntitySetBase baseEntitySet = null; relationshipSet = null; if (this.BaseEntitySets.TryGetValue(name, ignoreCase, out baseEntitySet)) { if (Helper.IsRelationshipSet(baseEntitySet)) { relationshipSet = (RelationshipSet)baseEntitySet; return true; } } return false; } /// <summary> /// Overriding System.Object.ToString to provide better String representation /// for this type. /// </summary> public override string ToString() { return Name; } internal void AddEntitySetBase(EntitySetBase entitySetBase) { _baseEntitySets.Source.Add(entitySetBase); } internal void AddFunctionImport(EdmFunction function) { Debug.Assert(function != null, "function != null"); Debug.Assert(function.IsFunctionImport, "function.IsFunctionImport"); _functionImports.Source.Add(function); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer; using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using Directory = Lucene.Net.Store.Directory; using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using CheckHits = Lucene.Net.Search.CheckHits; using DefaultSimilarity = Lucene.Net.Search.DefaultSimilarity; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Query = Lucene.Net.Search.Query; using Scorer = Lucene.Net.Search.Scorer; using Searcher = Lucene.Net.Search.Searcher; using Similarity = Lucene.Net.Search.Similarity; using TermQuery = Lucene.Net.Search.TermQuery; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search.Spans { [TestFixture] public class TestSpans:LuceneTestCase { [Serializable] private class AnonymousClassDefaultSimilarity:DefaultSimilarity { public AnonymousClassDefaultSimilarity(TestSpans enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSpans enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSpans enclosingInstance; public TestSpans Enclosing_Instance { get { return enclosingInstance; } } public override float SloppyFreq(int distance) { return 0.0f; } } private class AnonymousClassSpanNearQuery:SpanNearQuery { private void InitBlock(Lucene.Net.Search.Similarity sim, TestSpans enclosingInstance) { this.sim = sim; this.enclosingInstance = enclosingInstance; } private Lucene.Net.Search.Similarity sim; private TestSpans enclosingInstance; public TestSpans Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassSpanNearQuery(Lucene.Net.Search.Similarity sim, TestSpans enclosingInstance, Lucene.Net.Search.Spans.SpanQuery[] Param1, int Param2, bool Param3):base(Param1, Param2, Param3) { InitBlock(sim, enclosingInstance); } public override Similarity GetSimilarity(Searcher s) { return sim; } } private IndexSearcher searcher; public const System.String field = "field"; [SetUp] public override void SetUp() { base.SetUp(); RAMDirectory directory = new RAMDirectory(); IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); for (int i = 0; i < docFields.Length; i++) { Document doc = new Document(); doc.Add(new Field(field, docFields[i], Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(doc); } writer.Close(); searcher = new IndexSearcher(directory); } private System.String[] docFields = new System.String[]{"w1 w2 w3 w4 w5", "w1 w3 w2 w3", "w1 xx w2 yy w3", "w1 w3 xx w2 yy w3", "u2 u2 u1", "u2 xx u2 u1", "u2 u2 xx u1", "u2 xx u2 yy u1", "u2 xx u1 u2", "u2 u1 xx u2", "u1 u2 xx u2", "t1 t2 t1 t3 t2 t3"}; public virtual SpanTermQuery MakeSpanTermQuery(System.String text) { return new SpanTermQuery(new Term(field, text)); } private void CheckHits(Query query, int[] results) { Lucene.Net.Search.CheckHits.CheckHits_Renamed_Method(query, field, searcher, results); } private void OrderedSlopTest3SQ(SpanQuery q1, SpanQuery q2, SpanQuery q3, int slop, int[] expectedDocs) { bool ordered = true; SpanNearQuery snq = new SpanNearQuery(new SpanQuery[]{q1, q2, q3}, slop, ordered); CheckHits(snq, expectedDocs); } public virtual void OrderedSlopTest3(int slop, int[] expectedDocs) { OrderedSlopTest3SQ(MakeSpanTermQuery("w1"), MakeSpanTermQuery("w2"), MakeSpanTermQuery("w3"), slop, expectedDocs); } public virtual void OrderedSlopTest3Equal(int slop, int[] expectedDocs) { OrderedSlopTest3SQ(MakeSpanTermQuery("w1"), MakeSpanTermQuery("w3"), MakeSpanTermQuery("w3"), slop, expectedDocs); } public virtual void OrderedSlopTest1Equal(int slop, int[] expectedDocs) { OrderedSlopTest3SQ(MakeSpanTermQuery("u2"), MakeSpanTermQuery("u2"), MakeSpanTermQuery("u1"), slop, expectedDocs); } [Test] public virtual void TestSpanNearOrdered01() { OrderedSlopTest3(0, new int[]{0}); } [Test] public virtual void TestSpanNearOrdered02() { OrderedSlopTest3(1, new int[]{0, 1}); } [Test] public virtual void TestSpanNearOrdered03() { OrderedSlopTest3(2, new int[]{0, 1, 2}); } [Test] public virtual void TestSpanNearOrdered04() { OrderedSlopTest3(3, new int[]{0, 1, 2, 3}); } [Test] public virtual void TestSpanNearOrdered05() { OrderedSlopTest3(4, new int[]{0, 1, 2, 3}); } [Test] public virtual void TestSpanNearOrderedEqual01() { OrderedSlopTest3Equal(0, new int[]{}); } [Test] public virtual void TestSpanNearOrderedEqual02() { OrderedSlopTest3Equal(1, new int[]{1}); } [Test] public virtual void TestSpanNearOrderedEqual03() { OrderedSlopTest3Equal(2, new int[]{1}); } [Test] public virtual void TestSpanNearOrderedEqual04() { OrderedSlopTest3Equal(3, new int[]{1, 3}); } [Test] public virtual void TestSpanNearOrderedEqual11() { OrderedSlopTest1Equal(0, new int[]{4}); } [Test] public virtual void TestSpanNearOrderedEqual12() { OrderedSlopTest1Equal(0, new int[]{4}); } [Test] public virtual void TestSpanNearOrderedEqual13() { OrderedSlopTest1Equal(1, new int[]{4, 5, 6}); } [Test] public virtual void TestSpanNearOrderedEqual14() { OrderedSlopTest1Equal(2, new int[]{4, 5, 6, 7}); } [Test] public virtual void TestSpanNearOrderedEqual15() { OrderedSlopTest1Equal(3, new int[]{4, 5, 6, 7}); } [Test] public virtual void TestSpanNearOrderedOverlap() { bool ordered = true; int slop = 1; SpanNearQuery snq = new SpanNearQuery(new SpanQuery[]{MakeSpanTermQuery("t1"), MakeSpanTermQuery("t2"), MakeSpanTermQuery("t3")}, slop, ordered); Spans spans = snq.GetSpans(searcher.GetIndexReader()); Assert.IsTrue(spans.Next(), "first range"); Assert.AreEqual(11, spans.Doc(), "first doc"); Assert.AreEqual(0, spans.Start(), "first start"); Assert.AreEqual(4, spans.End(), "first end"); Assert.IsTrue(spans.Next(), "second range"); Assert.AreEqual(11, spans.Doc(), "second doc"); Assert.AreEqual(2, spans.Start(), "second start"); Assert.AreEqual(6, spans.End(), "second end"); Assert.IsFalse(spans.Next(), "third range"); } [Test] public virtual void TestSpanNearUnOrdered() { //See http://www.gossamer-threads.com/lists/lucene/java-dev/52270 for discussion about this test SpanNearQuery snq; snq = new SpanNearQuery(new SpanQuery[]{MakeSpanTermQuery("u1"), MakeSpanTermQuery("u2")}, 0, false); Spans spans = snq.GetSpans(searcher.GetIndexReader()); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(4, spans.Doc(), "doc"); Assert.AreEqual(1, spans.Start(), "start"); Assert.AreEqual(3, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(5, spans.Doc(), "doc"); Assert.AreEqual(2, spans.Start(), "start"); Assert.AreEqual(4, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(8, spans.Doc(), "doc"); Assert.AreEqual(2, spans.Start(), "start"); Assert.AreEqual(4, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(9, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(2, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(10, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(2, spans.End(), "end"); Assert.IsTrue(spans.Next() == false, "Has next and it shouldn't: " + spans.Doc()); SpanNearQuery u1u2 = new SpanNearQuery(new SpanQuery[]{MakeSpanTermQuery("u1"), MakeSpanTermQuery("u2")}, 0, false); snq = new SpanNearQuery(new SpanQuery[]{u1u2, MakeSpanTermQuery("u2")}, 1, false); spans = snq.GetSpans(searcher.GetIndexReader()); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(4, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(3, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); //unordered spans can be subsets Assert.AreEqual(4, spans.Doc(), "doc"); Assert.AreEqual(1, spans.Start(), "start"); Assert.AreEqual(3, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(5, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(4, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(5, spans.Doc(), "doc"); Assert.AreEqual(2, spans.Start(), "start"); Assert.AreEqual(4, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(8, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(4, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(8, spans.Doc(), "doc"); Assert.AreEqual(2, spans.Start(), "start"); Assert.AreEqual(4, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(9, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(2, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(9, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(4, spans.End(), "end"); Assert.IsTrue(spans.Next(), "Does not have next and it should"); Assert.AreEqual(10, spans.Doc(), "doc"); Assert.AreEqual(0, spans.Start(), "start"); Assert.AreEqual(2, spans.End(), "end"); Assert.IsTrue(spans.Next() == false, "Has next and it shouldn't"); } private Spans OrSpans(System.String[] terms) { SpanQuery[] sqa = new SpanQuery[terms.Length]; for (int i = 0; i < terms.Length; i++) { sqa[i] = MakeSpanTermQuery(terms[i]); } return (new SpanOrQuery(sqa)).GetSpans(searcher.GetIndexReader()); } private void TstNextSpans(Spans spans, int doc, int start, int end) { Assert.IsTrue(spans.Next(), "next"); Assert.AreEqual(doc, spans.Doc(), "doc"); Assert.AreEqual(start, spans.Start(), "start"); Assert.AreEqual(end, spans.End(), "end"); } [Test] public virtual void TestSpanOrEmpty() { Spans spans = OrSpans(new System.String[0]); Assert.IsFalse(spans.Next(), "empty next"); SpanOrQuery a = new SpanOrQuery(new SpanQuery[0]); SpanOrQuery b = new SpanOrQuery(new SpanQuery[0]); Assert.IsTrue(a.Equals(b), "empty should equal"); } [Test] public virtual void TestSpanOrSingle() { Spans spans = OrSpans(new System.String[]{"w5"}); TstNextSpans(spans, 0, 4, 5); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrMovesForward() { Spans spans = OrSpans(new System.String[]{"w1", "xx"}); spans.Next(); int doc = spans.Doc(); Assert.AreEqual(0, doc); spans.SkipTo(0); doc = spans.Doc(); // LUCENE-1583: // according to Spans, a skipTo to the same doc or less // should still call next() on the underlying Spans Assert.AreEqual(1, doc); } [Test] public virtual void TestSpanOrDouble() { Spans spans = OrSpans(new System.String[]{"w5", "yy"}); TstNextSpans(spans, 0, 4, 5); TstNextSpans(spans, 2, 3, 4); TstNextSpans(spans, 3, 4, 5); TstNextSpans(spans, 7, 3, 4); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrDoubleSkip() { Spans spans = OrSpans(new System.String[]{"w5", "yy"}); Assert.IsTrue(spans.SkipTo(3), "initial skipTo"); Assert.AreEqual(3, spans.Doc(), "doc"); Assert.AreEqual(4, spans.Start(), "start"); Assert.AreEqual(5, spans.End(), "end"); TstNextSpans(spans, 7, 3, 4); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrUnused() { Spans spans = OrSpans(new System.String[]{"w5", "unusedTerm", "yy"}); TstNextSpans(spans, 0, 4, 5); TstNextSpans(spans, 2, 3, 4); TstNextSpans(spans, 3, 4, 5); TstNextSpans(spans, 7, 3, 4); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanOrTripleSameDoc() { Spans spans = OrSpans(new System.String[]{"t1", "t2", "t3"}); TstNextSpans(spans, 11, 0, 1); TstNextSpans(spans, 11, 1, 2); TstNextSpans(spans, 11, 2, 3); TstNextSpans(spans, 11, 3, 4); TstNextSpans(spans, 11, 4, 5); TstNextSpans(spans, 11, 5, 6); Assert.IsFalse(spans.Next(), "final next"); } [Test] public virtual void TestSpanScorerZeroSloppyFreq() { bool ordered = true; int slop = 1; Similarity sim = new AnonymousClassDefaultSimilarity(this); SpanNearQuery snq = new AnonymousClassSpanNearQuery(sim, this, new SpanQuery[]{MakeSpanTermQuery("t1"), MakeSpanTermQuery("t2")}, slop, ordered); Scorer spanScorer = snq.Weight(searcher).Scorer(searcher.GetIndexReader(), true, false); Assert.IsTrue(spanScorer.NextDoc() != DocIdSetIterator.NO_MORE_DOCS, "first doc"); Assert.AreEqual(spanScorer.DocID(), 11, "first doc number"); float score = spanScorer.Score(); Assert.IsTrue(score == 0.0f, "first doc score should be zero, " + score); Assert.IsTrue(spanScorer.NextDoc() == DocIdSetIterator.NO_MORE_DOCS, "no second doc"); } // LUCENE-1404 private void AddDoc(IndexWriter writer, System.String id, System.String text) { Document doc = new Document(); doc.Add(new Field("id", id, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.Add(new Field("text", text, Field.Store.YES, Field.Index.TOKENIZED)); writer.AddDocument(doc); } // LUCENE-1404 private int HitCount(Searcher searcher, System.String word) { return searcher.Search(new TermQuery(new Term("text", word)), 10).TotalHits; } // LUCENE-1404 private SpanQuery CreateSpan(System.String value_Renamed) { return new SpanTermQuery(new Term("text", value_Renamed)); } // LUCENE-1404 private SpanQuery CreateSpan(int slop, bool ordered, SpanQuery[] clauses) { return new SpanNearQuery(clauses, slop, ordered); } // LUCENE-1404 private SpanQuery CreateSpan(int slop, bool ordered, System.String term1, System.String term2) { return CreateSpan(slop, ordered, new SpanQuery[]{CreateSpan(term1), CreateSpan(term2)}); } // LUCENE-1404 [Test] public virtual void TestNPESpanQuery() { Directory dir = new MockRAMDirectory(); IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(new System.Collections.Hashtable(0)), IndexWriter.MaxFieldLength.LIMITED); // Add documents AddDoc(writer, "1", "the big dogs went running to the market"); AddDoc(writer, "2", "the cat chased the mouse, then the cat ate the mouse quickly"); // Commit writer.Close(); // Get searcher IndexReader reader = IndexReader.Open(dir); IndexSearcher searcher = new IndexSearcher(reader); // Control (make sure docs indexed) Assert.AreEqual(2, HitCount(searcher, "the")); Assert.AreEqual(1, HitCount(searcher, "cat")); Assert.AreEqual(1, HitCount(searcher, "dogs")); Assert.AreEqual(0, HitCount(searcher, "rabbit")); // This throws exception (it shouldn't) Assert.AreEqual(1, searcher.Search(CreateSpan(0, true, new SpanQuery[]{CreateSpan(4, false, "chased", "cat"), CreateSpan("ate")}), 10).TotalHits); reader.Close(); dir.Close(); } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace System { using System; using System.Threading; using System.Collections; using System.Runtime.CompilerServices; /** * <p>The <code>String</code> class represents a static string of characters. Many of * the <code>String</code> methods perform some type of transformation on the current * instance and return the result as a new <code>String</code>. All comparison methods are * implemented as a part of <code>String</code>.</p> As with arrays, character positions * (indices) are zero-based. * * <p>When passing a null string into a constructor in VJ and VC, the null should be * explicitly type cast to a <code>String</code>.</p> * <p>For Example:<br> * <pre>String s = new String((String)null); * Text.Out.WriteLine(s);</pre></p> * * @author Jay Roxe (jroxe) * @version */ [Serializable] [Clarity.ExportStub("System_String.cpp")] public sealed class String : IComparable { public static readonly String Empty = ""; private char[] m_chars; public override bool Equals(object obj) { String s = obj as String; if (s != null) { return String.Equals(this, s); } return false; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static bool Equals(String a, String b); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static bool operator ==(String a, String b); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static bool operator !=(String a, String b); [System.Runtime.CompilerServices.IndexerName("Chars")] public extern char this[int index] { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern char[] ToCharArray(); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern char[] ToCharArray(int startIndex, int length); public extern int Length { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String[] Split(params char[] separator); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String[] Split(char[] separator, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String Substring(int startIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String Substring(int startIndex, int length); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String Trim(params char[] trimChars); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String TrimStart(params char[] trimChars); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String TrimEnd(params char[] trimChars); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char[] value, int startIndex, int length); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char[] value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String(char c, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static int Compare(String strA, String strB); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int CompareTo(Object value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int CompareTo(String strB); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOf(char value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOf(char value, int startIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOf(char value, int startIndex, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOfAny(char[] anyOf); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOfAny(char[] anyOf, int startIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOfAny(char[] anyOf, int startIndex, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOf(String value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOf(String value, int startIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int IndexOf(String value, int startIndex, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOf(char value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOf(char value, int startIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOf(char value, int startIndex, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOfAny(char[] anyOf); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOfAny(char[] anyOf, int startIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOfAny(char[] anyOf, int startIndex, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOf(String value); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOf(String value, int startIndex); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern int LastIndexOf(String value, int startIndex, int count); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String ToLower(); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String ToUpper(); public override String ToString() { return this; } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern String Trim(); ////// This method contains the same functionality as StringBuilder Replace. The only difference is that ////// a new String has to be allocated since Strings are immutable public static String Concat(Object arg0) { if (arg0 == null) { return String.Empty; } return arg0.ToString(); } public static String Concat(Object arg0, Object arg1) { if (arg0 == null) { arg0 = String.Empty; } if (arg1 == null) { arg1 = String.Empty; } return Concat(arg0.ToString(), arg1.ToString()); } public static String Concat(Object arg0, Object arg1, Object arg2) { if (arg0 == null) { arg0 = String.Empty; } if (arg1 == null) { arg1 = String.Empty; } if (arg2 == null) { arg2 = String.Empty; } return Concat(arg0.ToString(), arg1.ToString(), arg2.ToString()); } public static String Concat(params Object[] args) { if (args == null) { throw new ArgumentNullException("args"); } int length = args.Length; String[] sArgs = new String[length]; int totalLength = 0; for (int i = 0; i < length; i++) { sArgs[i] = ((args[i] == null) ? (String.Empty) : (args[i].ToString())); totalLength += sArgs[i].Length; } return String.Concat(sArgs); } [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static String Concat(String str0, String str1); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static String Concat(String str0, String str1, String str2); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static String Concat(String str0, String str1, String str2, String str3); [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern static String Concat(params String[] values); public static String Intern(String str) { // We don't support "interning" of strings. So simply return the string. return str; } public static String IsInterned(String str) { // We don't support "interning" of strings. So simply return the string. return str; } } }
/* * 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.Linq.Impl { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Common; using Remotion.Linq; /// <summary> /// Fields query executor. /// </summary> internal class CacheFieldsQueryExecutor : IQueryExecutor { /** */ private readonly ICacheInternal _cache; /** */ private static readonly CopyOnWriteConcurrentDictionary<ConstructorInfo, object> CtorCache = new CopyOnWriteConcurrentDictionary<ConstructorInfo, object>(); /** */ private readonly bool _local; /** */ private readonly int _pageSize; /** */ private readonly bool _enableDistributedJoins; /** */ private readonly bool _enforceJoinOrder; /// <summary> /// Initializes a new instance of the <see cref="CacheFieldsQueryExecutor" /> class. /// </summary> /// <param name="cache">The executor function.</param> /// <param name="local">Local flag.</param> /// <param name="pageSize">Size of the page.</param> /// <param name="enableDistributedJoins">Distributed joins flag.</param> /// <param name="enforceJoinOrder">Enforce join order flag.</param> public CacheFieldsQueryExecutor(ICacheInternal cache, bool local, int pageSize, bool enableDistributedJoins, bool enforceJoinOrder) { Debug.Assert(cache != null); _cache = cache; _local = local; _pageSize = pageSize; _enableDistributedJoins = enableDistributedJoins; _enforceJoinOrder = enforceJoinOrder; } /// <summary> /// Gets the local flag. /// </summary> public bool Local { get { return _local; } } /// <summary> /// Gets the size of the page. /// </summary> public int PageSize { get { return _pageSize; } } /// <summary> /// Gets a value indicating whether distributed joins are enabled. /// </summary> public bool EnableDistributedJoins { get { return _enableDistributedJoins; } } /// <summary> /// Gets a value indicating whether join order should be enforced. /// </summary> public bool EnforceJoinOrder { get { return _enforceJoinOrder; } } /** <inheritdoc /> */ public T ExecuteScalar<T>(QueryModel queryModel) { return ExecuteSingle<T>(queryModel, false); } /** <inheritdoc /> */ public T ExecuteSingle<T>(QueryModel queryModel, bool returnDefaultWhenEmpty) { var col = ExecuteCollection<T>(queryModel); return returnDefaultWhenEmpty ? col.SingleOrDefault() : col.Single(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] public IEnumerable<T> ExecuteCollection<T>(QueryModel queryModel) { Debug.Assert(queryModel != null); var qryData = GetQueryData(queryModel); Debug.WriteLine("\nFields Query: {0} | {1}", qryData.QueryText, string.Join(", ", qryData.Parameters.Select(x => x == null ? "null" : x.ToString()))); var qry = new SqlFieldsQuery(qryData.QueryText, _local, qryData.Parameters.ToArray()) { EnableDistributedJoins = _enableDistributedJoins, PageSize = _pageSize, EnforceJoinOrder = _enforceJoinOrder }; var selector = GetResultSelector<T>(queryModel.SelectClause.Selector); return _cache.QueryFields(qry, selector); } /// <summary> /// Compiles the query. /// </summary> public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel, Delegate queryCaller) { Debug.Assert(queryModel != null); Debug.Assert(queryCaller != null); var qryData = GetQueryData(queryModel); var qryText = qryData.QueryText; var selector = GetResultSelector<T>(queryModel.SelectClause.Selector); // Compiled query is a delegate with query parameters // Delegate parameters order and query parameters order may differ // These are in order of usage in query var qryOrderParams = qryData.ParameterExpressions.OfType<MemberExpression>() .Select(x => x.Member.Name).ToList(); // These are in order they come from user var userOrderParams = queryCaller.Method.GetParameters().Select(x => x.Name).ToList(); if ((qryOrderParams.Count != qryData.Parameters.Count) || (qryOrderParams.Count != userOrderParams.Count)) throw new InvalidOperationException("Error compiling query: all compiled query arguments " + "should come from enclosing delegate parameters."); var indices = qryOrderParams.Select(x => userOrderParams.IndexOf(x)).ToArray(); // Check if user param order is already correct if (indices.SequenceEqual(Enumerable.Range(0, indices.Length))) return args => _cache.QueryFields(new SqlFieldsQuery(qryText, _local, args) { EnableDistributedJoins = _enableDistributedJoins, PageSize = _pageSize, EnforceJoinOrder = _enforceJoinOrder }, selector); // Return delegate with reorder return args => _cache.QueryFields(new SqlFieldsQuery(qryText, _local, args.Select((x, i) => args[indices[i]]).ToArray()) { EnableDistributedJoins = _enableDistributedJoins, PageSize = _pageSize, EnforceJoinOrder = _enforceJoinOrder }, selector); } /** <inheritdoc /> */ public static QueryData GetQueryData(QueryModel queryModel) { Debug.Assert(queryModel != null); return new CacheQueryModelVisitor().GenerateQuery(queryModel); } /// <summary> /// Gets the result selector. /// </summary> private static Func<IBinaryRawReader, int, T> GetResultSelector<T>(Expression selectorExpression) { var newExpr = selectorExpression as NewExpression; if (newExpr != null) return GetCompiledCtor<T>(newExpr.Constructor); var entryCtor = GetCacheEntryCtorInfo(typeof(T)); if (entryCtor != null) return GetCompiledCtor<T>(entryCtor); if (typeof(T) == typeof(bool)) return ReadBool<T>; return (reader, count) => reader.ReadObject<T>(); } /// <summary> /// Reads the bool. Actual data may be bool or int/long. /// </summary> private static T ReadBool<T>(IBinaryRawReader reader, int count) { var obj = reader.ReadObject<object>(); if (obj is bool) return (T) obj; if (obj is long) return TypeCaster<T>.Cast((long) obj != 0); if (obj is int) return TypeCaster<T>.Cast((int) obj != 0); throw new InvalidOperationException("Expected bool, got: " + obj); } /// <summary> /// Gets the cache entry constructor. /// </summary> private static ConstructorInfo GetCacheEntryCtorInfo(Type entryType) { if (!entryType.IsGenericType || entryType.GetGenericTypeDefinition() != typeof(ICacheEntry<,>)) return null; var args = entryType.GetGenericArguments(); var targetType = typeof (CacheEntry<,>).MakeGenericType(args); return targetType.GetConstructors().Single(); } /// <summary> /// Gets the compiled constructor. /// </summary> private static Func<IBinaryRawReader, int, T> GetCompiledCtor<T>(ConstructorInfo ctorInfo) { object result; if (CtorCache.TryGetValue(ctorInfo, out result)) return (Func<IBinaryRawReader, int, T>) result; return (Func<IBinaryRawReader, int, T>) CtorCache.GetOrAdd(ctorInfo, x => { var innerCtor1 = DelegateConverter.CompileCtor<T>(x, GetCacheEntryCtorInfo); return (Func<IBinaryRawReader, int, T>) ((r, c) => innerCtor1(r)); }); } } }
// // MenuItem.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 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 Xwt.Backends; using System.ComponentModel; using Xwt.Drawing; namespace Xwt { [BackendType (typeof(IMenuItemBackend))] public class MenuItem: XwtComponent, ICellContainer { CellViewCollection cells; Menu subMenu; EventHandler clicked; Image image; protected class MenuItemBackendHost: BackendHost<MenuItem,IMenuItemBackend>, IMenuItemEventSink { protected override void OnBackendCreated () { base.OnBackendCreated (); Backend.Initialize (this); } public void OnClicked () { Parent.DoClick (); } } protected override Xwt.Backends.BackendHost CreateBackendHost () { return new MenuItemBackendHost (); } static MenuItem () { MapEvent (MenuItemEvent.Clicked, typeof(MenuItem), "OnClicked"); } public MenuItem () { if (!IsSeparator) UseMnemonic = true; } public MenuItem (Command command) { VerifyConstructorCall (this); LoadCommandProperties (command); } public MenuItem (string label) { VerifyConstructorCall (this); Label = label; } protected void LoadCommandProperties (Command command) { Label = command.Label; Image = command.Icon; } IMenuItemBackend Backend { get { return (IMenuItemBackend) base.BackendHost.Backend; } } bool IsSeparator { get { return this is SeparatorMenuItem; } } [DefaultValue ("")] public string Label { get { return Backend.Label; } set { if (IsSeparator) throw new NotSupportedException (); Backend.Label = value; } } /// <summary> /// Gets or sets the tooltip text. /// </summary> /// <value>The tooltip text.</value> [DefaultValue("")] public string TooltipText { get { return Backend.TooltipText ?? ""; } set { if (IsSeparator) throw new NotSupportedException(); Backend.TooltipText = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Xwt.Button"/> uses a mnemonic. /// </summary> /// <value><c>true</c> if it uses a mnemonic; otherwise, <c>false</c>.</value> /// <remarks> /// When set to true, the character after the first underscore character in the Label property value is /// interpreted as the mnemonic for that Label. /// </remarks> [DefaultValue(true)] public bool UseMnemonic { get { return Backend.UseMnemonic; } set { if (IsSeparator) throw new NotSupportedException (); Backend.UseMnemonic = value; } } [DefaultValue (true)] public bool Sensitive { get { return Backend.Sensitive; } set { Backend.Sensitive = value; } } [DefaultValue (true)] public bool Visible { get { return Backend.Visible; } set { Backend.Visible = value; } } public Image Image { get { return image; } set { if (IsSeparator) throw new NotSupportedException (); image = value; if (!IsSeparator) Backend.SetImage (image != null ? image.GetImageDescription (BackendHost.ToolkitEngine) : ImageDescription.Null); } } public void Show () { Visible = true; } public void Hide () { Visible = false; } public CellViewCollection Cells { get { if (cells == null) cells = new CellViewCollection (this); return cells; } } public Menu SubMenu { get { return subMenu; } set { if (IsSeparator) throw new NotSupportedException (); Backend.SetSubmenu ((IMenuBackend)BackendHost.ToolkitEngine.GetSafeBackend (value)); subMenu = value; } } public void NotifyCellChanged () { throw new NotImplementedException (); } internal virtual void DoClick () { OnClicked (EventArgs.Empty); } protected virtual void OnClicked (EventArgs e) { if (clicked != null) clicked (this, e); } public event EventHandler Clicked { add { base.BackendHost.OnBeforeEventAdd (MenuItemEvent.Clicked, clicked); clicked += value; } remove { clicked -= value; base.BackendHost.OnAfterEventRemove (MenuItemEvent.Clicked, clicked); } } } public enum MenuItemType { Normal, CheckBox, RadioButton } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.42 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.42. // namespace WebsitePanel.EnterpriseServer { using System.Diagnostics; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Xml.Serialization; using System.Data; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="esCommentsSoap", Namespace="http://smbsaas/websitepanel/enterpriseserver")] public partial class esComments : Microsoft.Web.Services3.WebServicesClientProtocol { private System.Threading.SendOrPostCallback GetCommentsOperationCompleted; private System.Threading.SendOrPostCallback AddCommentOperationCompleted; private System.Threading.SendOrPostCallback DeleteCommentOperationCompleted; /// <remarks/> public esComments() { this.Url = "http://localhost/WebsitePanelEnterpriseServer11/esComments.asmx"; } /// <remarks/> public event GetCommentsCompletedEventHandler GetCommentsCompleted; /// <remarks/> public event AddCommentCompletedEventHandler AddCommentCompleted; /// <remarks/> public event DeleteCommentCompletedEventHandler DeleteCommentCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetComments", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetComments(int userId, string itemTypeId, int itemId) { object[] results = this.Invoke("GetComments", new object[] { userId, itemTypeId, itemId}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetComments(int userId, string itemTypeId, int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetComments", new object[] { userId, itemTypeId, itemId}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetComments(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetCommentsAsync(int userId, string itemTypeId, int itemId) { this.GetCommentsAsync(userId, itemTypeId, itemId, null); } /// <remarks/> public void GetCommentsAsync(int userId, string itemTypeId, int itemId, object userState) { if ((this.GetCommentsOperationCompleted == null)) { this.GetCommentsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetCommentsOperationCompleted); } this.InvokeAsync("GetComments", new object[] { userId, itemTypeId, itemId}, this.GetCommentsOperationCompleted, userState); } private void OnGetCommentsOperationCompleted(object arg) { if ((this.GetCommentsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetCommentsCompleted(this, new GetCommentsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/AddComment", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int AddComment(string itemTypeId, int itemId, string commentText, int severityId) { object[] results = this.Invoke("AddComment", new object[] { itemTypeId, itemId, commentText, severityId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAddComment(string itemTypeId, int itemId, string commentText, int severityId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddComment", new object[] { itemTypeId, itemId, commentText, severityId}, callback, asyncState); } /// <remarks/> public int EndAddComment(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void AddCommentAsync(string itemTypeId, int itemId, string commentText, int severityId) { this.AddCommentAsync(itemTypeId, itemId, commentText, severityId, null); } /// <remarks/> public void AddCommentAsync(string itemTypeId, int itemId, string commentText, int severityId, object userState) { if ((this.AddCommentOperationCompleted == null)) { this.AddCommentOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddCommentOperationCompleted); } this.InvokeAsync("AddComment", new object[] { itemTypeId, itemId, commentText, severityId}, this.AddCommentOperationCompleted, userState); } private void OnAddCommentOperationCompleted(object arg) { if ((this.AddCommentCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddCommentCompleted(this, new AddCommentCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteComment", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int DeleteComment(int commentId) { object[] results = this.Invoke("DeleteComment", new object[] { commentId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteComment(int commentId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteComment", new object[] { commentId}, callback, asyncState); } /// <remarks/> public int EndDeleteComment(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void DeleteCommentAsync(int commentId) { this.DeleteCommentAsync(commentId, null); } /// <remarks/> public void DeleteCommentAsync(int commentId, object userState) { if ((this.DeleteCommentOperationCompleted == null)) { this.DeleteCommentOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteCommentOperationCompleted); } this.InvokeAsync("DeleteComment", new object[] { commentId}, this.DeleteCommentOperationCompleted, userState); } private void OnDeleteCommentOperationCompleted(object arg) { if ((this.DeleteCommentCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteCommentCompleted(this, new DeleteCommentCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetCommentsCompletedEventHandler(object sender, GetCommentsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetCommentsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetCommentsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddCommentCompletedEventHandler(object sender, AddCommentCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AddCommentCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AddCommentCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteCommentCompletedEventHandler(object sender, DeleteCommentCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteCommentCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteCommentCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Globalization { public partial class CompareInfo { private void InitSort(CultureInfo culture) { _sortName = culture.SortName; } internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { fixed (char* pSource = source) fixed (char* pValue = value) { char* pSrc = &pSource[startIndex]; int index = FindStringOrdinal(pSrc, count, pValue, value.Length, FindStringOptions.Start, ignoreCase); if (index >= 0) { return index + startIndex; } return -1; } } internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase) { fixed (char* pSource = source) fixed (char* pValue = value) { char* pSrc = &pSource[startIndex - count + 1]; int index = FindStringOrdinal(pSrc, count, pValue, value.Length, FindStringOptions.End, ignoreCase); if (index >= 0) { return index + startIndex - (count - 1); } return -1; } } private unsafe bool StartsWith(string source, string prefix, CompareOptions options) { fixed (char* pSource = source) fixed (char* pValue = prefix) { return FindStringOrdinal(pSource, source.Length, pValue, prefix.Length, FindStringOptions.StartsWith, (options & CompareOptions.IgnoreCase) != 0) >= 0; } } private unsafe bool EndsWith(string source, string suffix, CompareOptions options) { fixed (char* pSource = source) fixed (char* pValue = suffix) { return FindStringOrdinal(pSource, source.Length, pValue, suffix.Length, FindStringOptions.EndsWith, (options & CompareOptions.IgnoreCase) != 0) >= 0; } } private unsafe int IndexOfCore(string source, string value, int startIndex, int count, CompareOptions options, int *matchLengthPtr) { int index = IndexOfOrdinal(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); if ((index != -1) && (matchLengthPtr != null)) *matchLengthPtr = value.Length; return index; } private unsafe int LastIndexOfCore(string source, string value, int startIndex, int count, CompareOptions options) { return LastIndexOfOrdinal(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { bool ignoreCase = (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0; if (ignoreCase) { return source.ToUpper().GetHashCode(); } return source.GetHashCode(); } private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options) { fixed (char* pStr1 = string1) fixed (char* pStr2 = string2) { char* pString1 = &pStr1[offset1]; char* pString2 = &pStr2[offset2]; return CompareString(pString1, length1, pString2, length2, options); } } private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { return CompareString(string1, count1, string2, count2, 0); } private static unsafe int CompareString(char* pString1, int length1, char* pString2, int length2, CompareOptions options) { bool ignoreCase = (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0; int index = 0; if (ignoreCase) { while (index < length1 && index < length2 && ToUpper(pString1[index]) == ToUpper(pString2[index])) { index++; } } else { while (index < length1 && index < length2 && pString1[index] == pString2[index]) { index++; } } if (index >= length1) { if (index >= length2) { return 0; } return -1; } if (index >= length2) { return 1; } return ignoreCase ? ToUpper(pString1[index]) - ToUpper(pString2[index]) : pString1[index] - pString2[index]; } private static unsafe int FindStringOrdinal(char* source, int sourceCount, char* value, int valueCount, FindStringOptions option, bool ignoreCase) { int ctrSource = 0; // index value into source int ctrValue = 0; // index value into value char sourceChar; // Character for case lookup in source char valueChar; // Character for case lookup in value int lastSourceStart; Debug.Assert(source != null); Debug.Assert(value != null); Debug.Assert(sourceCount >= 0); Debug.Assert(valueCount >= 0); if (valueCount == 0) { switch (option) { case FindStringOptions.StartsWith: case FindStringOptions.Start: return (0); case FindStringOptions.EndsWith: case FindStringOptions.End: return (sourceCount); default: return -1; } } if (sourceCount < valueCount) { return -1; } switch (option) { case FindStringOptions.StartsWith: { if (ignoreCase) { for (ctrValue = 0; ctrValue < valueCount; ctrValue++) { sourceChar = ToUpper(source[ctrValue]); valueChar = ToUpper(value[ctrValue]); if (sourceChar != valueChar) { break; } } } else { for (ctrValue = 0; ctrValue < valueCount; ctrValue++) { sourceChar = source[ctrValue]; valueChar = value[ctrValue]; if (sourceChar != valueChar) { break; } } } if (ctrValue == valueCount) { return 0; } } break; case FindStringOptions.Start: { lastSourceStart = sourceCount - valueCount; if (ignoreCase) { char firstValueChar = ToUpper(value[0]); for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++) { sourceChar = ToUpper(source[ctrSource]); if (sourceChar != firstValueChar) { continue; } for (ctrValue = 1; ctrValue < valueCount; ctrValue++) { sourceChar = ToUpper(source[ctrSource + ctrValue]); valueChar = ToUpper(value[ctrValue]); if (sourceChar != valueChar) { break; } } if (ctrValue == valueCount) { return ctrSource; } } } else { char firstValueChar = value[0]; for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++) { sourceChar = source[ctrSource]; if (sourceChar != firstValueChar) { continue; } for (ctrValue = 1; ctrValue < valueCount; ctrValue++) { sourceChar = source[ctrSource + ctrValue]; valueChar = value[ctrValue]; if (sourceChar != valueChar) { break; } } if (ctrValue == valueCount) { return ctrSource; } } } } break; case FindStringOptions.EndsWith: { lastSourceStart = sourceCount - valueCount; if (ignoreCase) { for (ctrSource = lastSourceStart, ctrValue = 0; ctrValue < valueCount; ctrSource++, ctrValue++) { sourceChar = ToUpper(source[ctrSource]); valueChar = ToUpper(value[ctrValue]); if (sourceChar != valueChar) { break; } } } else { for (ctrSource = lastSourceStart, ctrValue = 0; ctrValue < valueCount; ctrSource++, ctrValue++) { sourceChar = source[ctrSource]; valueChar = value[ctrValue]; if (sourceChar != valueChar) { break; } } } if (ctrValue == valueCount) { return sourceCount - valueCount; } } break; case FindStringOptions.End: { lastSourceStart = sourceCount - valueCount; if (ignoreCase) { char firstValueChar = ToUpper(value[0]); for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--) { sourceChar = ToUpper(source[ctrSource]); if (sourceChar != firstValueChar) { continue; } for (ctrValue = 1; ctrValue < valueCount; ctrValue++) { sourceChar = ToUpper(source[ctrSource + ctrValue]); valueChar = ToUpper(value[ctrValue]); if (sourceChar != valueChar) { break; } } if (ctrValue == valueCount) { return ctrSource; } } } else { char firstValueChar = value[0]; for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--) { sourceChar = source[ctrSource]; if (sourceChar != firstValueChar) { continue; } for (ctrValue = 1; ctrValue < valueCount; ctrValue++) { sourceChar = source[ctrSource + ctrValue]; valueChar = value[ctrValue]; if (sourceChar != valueChar) { break; } } if (ctrValue == valueCount) { return ctrSource; } } } } break; default: return -1; } return -1; } private static char ToUpper(char c) { return ('a' <= c && c <= 'z') ? (char)(c - 0x20) : c; } private enum FindStringOptions { Start, StartsWith, End, EndsWith, } private unsafe SortKey CreateSortKey(String source, CompareOptions options) { if (source == null) { throw new ArgumentNullException(nameof(source)); } Contract.EndContractBlock(); if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } throw new NotImplementedException(); } private static unsafe bool IsSortable(char* text, int length) { // CompareInfo c = CultureInfo.InvariantCulture.CompareInfo; // return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length)); throw new NotImplementedException(); } private SortVersion GetSortVersion() { throw new NotImplementedException(); } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { // Gear Joint: // C0 = (coordinate1 + ratio * coordinate2)_initial // C = (coordinate1 + ratio * coordinate2) - C0 = 0 // J = [J1 ratio * J2] // K = J * invM * JT // = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T // // Revolute: // coordinate = rotation // Cdot = angularVelocity // J = [0 0 1] // K = J * invM * JT = invI // // Prismatic: // coordinate = dot(p - pg, ug) // Cdot = dot(v + cross(w, r), ug) // J = [ug cross(r, ug)] // K = J * invM * JT = invMass + invI * cross(r, ug)^2 /// <summary> /// A gear joint is used to connect two joints together. /// Either joint can be a revolute or prismatic joint. /// You specify a gear ratio to bind the motions together: /// <![CDATA[coordinate1 + ratio * coordinate2 = ant]]> /// The ratio can be negative or positive. If one joint is a revolute joint /// and the other joint is a prismatic joint, then the ratio will have units /// of length or units of 1/length. /// /// Warning: You have to manually destroy the gear joint if jointA or jointB is destroyed. /// </summary> public class GearJoint : Joint { #region Properties/Fields public override Vector2 worldAnchorA { get { return _bodyA.getWorldPoint( _localAnchorA ); } set { Debug.Assert( false, "You can't set the world anchor on this joint type." ); } } public override Vector2 worldAnchorB { get { return _bodyB.getWorldPoint( _localAnchorB ); } set { Debug.Assert( false, "You can't set the world anchor on this joint type." ); } } /// <summary> /// The gear ratio. /// </summary> public float ratio { get { return _ratio; } set { Debug.Assert( MathUtils.isValid( value ) ); _ratio = value; } } /// <summary> /// The first revolute/prismatic joint attached to the gear joint. /// </summary> public Joint jointA { get; private set; } /// <summary> /// The second revolute/prismatic joint attached to the gear joint. /// </summary> public Joint jointB { get; private set; } JointType _typeA; JointType _typeB; Body _bodyA; Body _bodyB; Body _bodyC; Body _bodyD; // Solver shared Vector2 _localAnchorA; Vector2 _localAnchorB; Vector2 _localAnchorC; Vector2 _localAnchorD; Vector2 _localAxisC; Vector2 _localAxisD; float _referenceAngleA; float _referenceAngleB; float _constant; float _ratio; float _impulse; // Solver temp int _indexA, _indexB, _indexC, _indexD; Vector2 _lcA, _lcB, _lcC, _lcD; float _mA, _mB, _mC, _mD; float _iA, _iB, _iC, _iD; Vector2 _JvAC, _JvBD; float _JwA, _JwB, _JwC, _JwD; float _mass; #endregion /// <summary> /// Requires two existing revolute or prismatic joints (any combination will work). /// The provided joints must attach a dynamic body to a static body. /// </summary> /// <param name="jointA">The first joint.</param> /// <param name="jointB">The second joint.</param> /// <param name="ratio">The ratio.</param> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> public GearJoint( Body bodyA, Body bodyB, Joint jointA, Joint jointB, float ratio = 1f ) { jointType = JointType.Gear; base.bodyA = bodyA; base.bodyB = bodyB; this.jointA = jointA; this.jointB = jointB; this.ratio = ratio; _typeA = jointA.jointType; _typeB = jointB.jointType; //Debug.Assert(_typeA == JointType.Revolute || _typeA == JointType.Prismatic ); //Debug.Assert(_typeB == JointType.Revolute || _typeB == JointType.Prismatic ); float coordinateA, coordinateB; // TODO_ERIN there might be some problem with the joint edges in b2Joint. _bodyC = jointA.bodyA; _bodyA = jointA.bodyB; // Get geometry of joint1 Transform xfA = _bodyA._xf; float aA = _bodyA._sweep.a; Transform xfC = _bodyC._xf; float aC = _bodyC._sweep.a; if( _typeA == JointType.Revolute ) { RevoluteJoint revolute = (RevoluteJoint)jointA; _localAnchorC = revolute.localAnchorA; _localAnchorA = revolute.localAnchorB; _referenceAngleA = revolute.referenceAngle; _localAxisC = Vector2.Zero; coordinateA = aA - aC - _referenceAngleA; } else { PrismaticJoint prismatic = (PrismaticJoint)jointA; _localAnchorC = prismatic.localAnchorA; _localAnchorA = prismatic.localAnchorB; _referenceAngleA = prismatic.referenceAngle; _localAxisC = prismatic.localXAxis; Vector2 pC = _localAnchorC; Vector2 pA = MathUtils.mulT( xfC.q, MathUtils.mul( xfA.q, _localAnchorA ) + ( xfA.p - xfC.p ) ); coordinateA = Vector2.Dot( pA - pC, _localAxisC ); } _bodyD = jointB.bodyA; _bodyB = jointB.bodyB; // Get geometry of joint2 Transform xfB = _bodyB._xf; float aB = _bodyB._sweep.a; Transform xfD = _bodyD._xf; float aD = _bodyD._sweep.a; if( _typeB == JointType.Revolute ) { RevoluteJoint revolute = (RevoluteJoint)jointB; _localAnchorD = revolute.localAnchorA; _localAnchorB = revolute.localAnchorB; _referenceAngleB = revolute.referenceAngle; _localAxisD = Vector2.Zero; coordinateB = aB - aD - _referenceAngleB; } else { PrismaticJoint prismatic = (PrismaticJoint)jointB; _localAnchorD = prismatic.localAnchorA; _localAnchorB = prismatic.localAnchorB; _referenceAngleB = prismatic.referenceAngle; _localAxisD = prismatic.localXAxis; Vector2 pD = _localAnchorD; Vector2 pB = MathUtils.mulT( xfD.q, MathUtils.mul( xfB.q, _localAnchorB ) + ( xfB.p - xfD.p ) ); coordinateB = Vector2.Dot( pB - pD, _localAxisD ); } _ratio = ratio; _constant = coordinateA + _ratio * coordinateB; _impulse = 0.0f; } public override Vector2 getReactionForce( float invDt ) { Vector2 P = _impulse * _JvAC; return invDt * P; } public override float getReactionTorque( float invDt ) { float L = _impulse * _JwA; return invDt * L; } internal override void initVelocityConstraints( ref SolverData data ) { _indexA = _bodyA.islandIndex; _indexB = _bodyB.islandIndex; _indexC = _bodyC.islandIndex; _indexD = _bodyD.islandIndex; _lcA = _bodyA._sweep.localCenter; _lcB = _bodyB._sweep.localCenter; _lcC = _bodyC._sweep.localCenter; _lcD = _bodyD._sweep.localCenter; _mA = _bodyA._invMass; _mB = _bodyB._invMass; _mC = _bodyC._invMass; _mD = _bodyD._invMass; _iA = _bodyA._invI; _iB = _bodyB._invI; _iC = _bodyC._invI; _iD = _bodyD._invI; float aA = data.positions[_indexA].a; Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; float aB = data.positions[_indexB].a; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; float aC = data.positions[_indexC].a; Vector2 vC = data.velocities[_indexC].v; float wC = data.velocities[_indexC].w; float aD = data.positions[_indexD].a; Vector2 vD = data.velocities[_indexD].v; float wD = data.velocities[_indexD].w; Rot qA = new Rot( aA ), qB = new Rot( aB ), qC = new Rot( aC ), qD = new Rot( aD ); _mass = 0.0f; if( _typeA == JointType.Revolute ) { _JvAC = Vector2.Zero; _JwA = 1.0f; _JwC = 1.0f; _mass += _iA + _iC; } else { Vector2 u = MathUtils.mul( qC, _localAxisC ); Vector2 rC = MathUtils.mul( qC, _localAnchorC - _lcC ); Vector2 rA = MathUtils.mul( qA, _localAnchorA - _lcA ); _JvAC = u; _JwC = MathUtils.cross( rC, u ); _JwA = MathUtils.cross( rA, u ); _mass += _mC + _mA + _iC * _JwC * _JwC + _iA * _JwA * _JwA; } if( _typeB == JointType.Revolute ) { _JvBD = Vector2.Zero; _JwB = _ratio; _JwD = _ratio; _mass += _ratio * _ratio * ( _iB + _iD ); } else { Vector2 u = MathUtils.mul( qD, _localAxisD ); Vector2 rD = MathUtils.mul( qD, _localAnchorD - _lcD ); Vector2 rB = MathUtils.mul( qB, _localAnchorB - _lcB ); _JvBD = _ratio * u; _JwD = _ratio * MathUtils.cross( rD, u ); _JwB = _ratio * MathUtils.cross( rB, u ); _mass += _ratio * _ratio * ( _mD + _mB ) + _iD * _JwD * _JwD + _iB * _JwB * _JwB; } // Compute effective mass. _mass = _mass > 0.0f ? 1.0f / _mass : 0.0f; if( Settings.enableWarmstarting ) { vA += ( _mA * _impulse ) * _JvAC; wA += _iA * _impulse * _JwA; vB += ( _mB * _impulse ) * _JvBD; wB += _iB * _impulse * _JwB; vC -= ( _mC * _impulse ) * _JvAC; wC -= _iC * _impulse * _JwC; vD -= ( _mD * _impulse ) * _JvBD; wD -= _iD * _impulse * _JwD; } else { _impulse = 0.0f; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; data.velocities[_indexC].v = vC; data.velocities[_indexC].w = wC; data.velocities[_indexD].v = vD; data.velocities[_indexD].w = wD; } internal override void solveVelocityConstraints( ref SolverData data ) { Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; Vector2 vC = data.velocities[_indexC].v; float wC = data.velocities[_indexC].w; Vector2 vD = data.velocities[_indexD].v; float wD = data.velocities[_indexD].w; float Cdot = Vector2.Dot( _JvAC, vA - vC ) + Vector2.Dot( _JvBD, vB - vD ); Cdot += ( _JwA * wA - _JwC * wC ) + ( _JwB * wB - _JwD * wD ); float impulse = -_mass * Cdot; _impulse += impulse; vA += ( _mA * impulse ) * _JvAC; wA += _iA * impulse * _JwA; vB += ( _mB * impulse ) * _JvBD; wB += _iB * impulse * _JwB; vC -= ( _mC * impulse ) * _JvAC; wC -= _iC * impulse * _JwC; vD -= ( _mD * impulse ) * _JvBD; wD -= _iD * impulse * _JwD; data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; data.velocities[_indexC].v = vC; data.velocities[_indexC].w = wC; data.velocities[_indexD].v = vD; data.velocities[_indexD].w = wD; } internal override bool solvePositionConstraints( ref SolverData data ) { Vector2 cA = data.positions[_indexA].c; float aA = data.positions[_indexA].a; Vector2 cB = data.positions[_indexB].c; float aB = data.positions[_indexB].a; Vector2 cC = data.positions[_indexC].c; float aC = data.positions[_indexC].a; Vector2 cD = data.positions[_indexD].c; float aD = data.positions[_indexD].a; Rot qA = new Rot( aA ), qB = new Rot( aB ), qC = new Rot( aC ), qD = new Rot( aD ); const float linearError = 0.0f; float coordinateA, coordinateB; Vector2 JvAC, JvBD; float JwA, JwB, JwC, JwD; float mass = 0.0f; if( _typeA == JointType.Revolute ) { JvAC = Vector2.Zero; JwA = 1.0f; JwC = 1.0f; mass += _iA + _iC; coordinateA = aA - aC - _referenceAngleA; } else { Vector2 u = MathUtils.mul( qC, _localAxisC ); Vector2 rC = MathUtils.mul( qC, _localAnchorC - _lcC ); Vector2 rA = MathUtils.mul( qA, _localAnchorA - _lcA ); JvAC = u; JwC = MathUtils.cross( rC, u ); JwA = MathUtils.cross( rA, u ); mass += _mC + _mA + _iC * JwC * JwC + _iA * JwA * JwA; Vector2 pC = _localAnchorC - _lcC; Vector2 pA = MathUtils.mulT( qC, rA + ( cA - cC ) ); coordinateA = Vector2.Dot( pA - pC, _localAxisC ); } if( _typeB == JointType.Revolute ) { JvBD = Vector2.Zero; JwB = _ratio; JwD = _ratio; mass += _ratio * _ratio * ( _iB + _iD ); coordinateB = aB - aD - _referenceAngleB; } else { Vector2 u = MathUtils.mul( qD, _localAxisD ); Vector2 rD = MathUtils.mul( qD, _localAnchorD - _lcD ); Vector2 rB = MathUtils.mul( qB, _localAnchorB - _lcB ); JvBD = _ratio * u; JwD = _ratio * MathUtils.cross( rD, u ); JwB = _ratio * MathUtils.cross( rB, u ); mass += _ratio * _ratio * ( _mD + _mB ) + _iD * JwD * JwD + _iB * JwB * JwB; Vector2 pD = _localAnchorD - _lcD; Vector2 pB = MathUtils.mulT( qD, rB + ( cB - cD ) ); coordinateB = Vector2.Dot( pB - pD, _localAxisD ); } float C = ( coordinateA + _ratio * coordinateB ) - _constant; float impulse = 0.0f; if( mass > 0.0f ) { impulse = -C / mass; } cA += _mA * impulse * JvAC; aA += _iA * impulse * JwA; cB += _mB * impulse * JvBD; aB += _iB * impulse * JwB; cC -= _mC * impulse * JvAC; aC -= _iC * impulse * JwC; cD -= _mD * impulse * JvBD; aD -= _iD * impulse * JwD; data.positions[_indexA].c = cA; data.positions[_indexA].a = aA; data.positions[_indexB].c = cB; data.positions[_indexB].a = aB; data.positions[_indexC].c = cC; data.positions[_indexC].a = aC; data.positions[_indexD].c = cD; data.positions[_indexD].a = aD; // TODO_ERIN not implemented return linearError < Settings.linearSlop; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Reflection; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// This class implements update-typeData command. /// </summary> [Cmdlet(VerbsData.Update, "TypeData", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, DefaultParameterSetName = FileParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097131")] public class UpdateTypeDataCommand : UpdateData { #region dynamic type set // Dynamic type set name and type data set name private const string DynamicTypeSet = "DynamicTypeSet"; private const string TypeDataSet = "TypeDataSet"; private static readonly object s_notSpecified = new(); private static bool HasBeenSpecified(object obj) { return !System.Object.ReferenceEquals(obj, s_notSpecified); } private PSMemberTypes _memberType; private bool _isMemberTypeSet = false; /// <summary> /// The member type of to be added. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] [ValidateSet(System.Management.Automation.Runspaces.TypeData.NoteProperty, System.Management.Automation.Runspaces.TypeData.AliasProperty, System.Management.Automation.Runspaces.TypeData.ScriptProperty, System.Management.Automation.Runspaces.TypeData.CodeProperty, System.Management.Automation.Runspaces.TypeData.ScriptMethod, System.Management.Automation.Runspaces.TypeData.CodeMethod, IgnoreCase = true)] public PSMemberTypes MemberType { get { return _memberType; } set { _memberType = value; _isMemberTypeSet = true; } } private string _memberName; /// <summary> /// The name of the new member. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string MemberName { get { return _memberName; } set { _memberName = value; } } private object _value1 = s_notSpecified; /// <summary> /// First value of the new member. The meaning of this value /// changes according to the member type. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] public object Value { get { return _value1; } set { _value1 = value; } } private object _value2; /// <summary> /// Second value of the new member. The meaning of this value /// changes according to the member type. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public object SecondValue { get { return _value2; } set { _value2 = value; } } private Type _typeConverter; /// <summary> /// The type converter to be added. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TypeConverter { get { return _typeConverter; } set { _typeConverter = value; } } private Type _typeAdapter; /// <summary> /// The type adapter to be added. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TypeAdapter { get { return _typeAdapter; } set { _typeAdapter = value; } } /// <summary> /// SerializationMethod. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string SerializationMethod { get { return _serializationMethod; } set { _serializationMethod = value; } } /// <summary> /// TargetTypeForDeserialization. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public Type TargetTypeForDeserialization { get { return _targetTypeForDeserialization; } set { _targetTypeForDeserialization = value; } } /// <summary> /// SerializationDepth. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] [ValidateRange(0, int.MaxValue)] public int SerializationDepth { get { return _serializationDepth; } set { _serializationDepth = value; } } /// <summary> /// DefaultDisplayProperty. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string DefaultDisplayProperty { get { return _defaultDisplayProperty; } set { _defaultDisplayProperty = value; } } /// <summary> /// InheritPropertySerializationSet. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNull] public bool? InheritPropertySerializationSet { get { return _inheritPropertySerializationSet; } set { _inheritPropertySerializationSet = value; } } /// <summary> /// StringSerializationSource. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string StringSerializationSource { get { return _stringSerializationSource; } set { _stringSerializationSource = value; } } /// <summary> /// DefaultDisplayPropertySet. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] DefaultDisplayPropertySet { get { return _defaultDisplayPropertySet; } set { _defaultDisplayPropertySet = value; } } /// <summary> /// DefaultKeyPropertySet. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] DefaultKeyPropertySet { get { return _defaultKeyPropertySet; } set { _defaultKeyPropertySet = value; } } /// <summary> /// PropertySerializationSet. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(ParameterSetName = DynamicTypeSet)] [ValidateNotNullOrEmpty] public string[] PropertySerializationSet { get { return _propertySerializationSet; } set { _propertySerializationSet = value; } } // These members are represented as NoteProperty in types.ps1xml private string _serializationMethod; private Type _targetTypeForDeserialization; private int _serializationDepth = int.MinValue; private string _defaultDisplayProperty; private bool? _inheritPropertySerializationSet; // These members are represented as AliasProperty in types.ps1xml private string _stringSerializationSource; // These members are represented as PropertySet in types.ps1xml private string[] _defaultDisplayPropertySet; private string[] _defaultKeyPropertySet; private string[] _propertySerializationSet; private string _typeName; /// <summary> /// The type name we want to update on. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = DynamicTypeSet)] [ArgumentToTypeNameTransformationAttribute()] [ValidateNotNullOrEmpty] public string TypeName { get { return _typeName; } set { _typeName = value; } } private bool _force = false; /// <summary> /// True if we should overwrite a possibly existing member. /// </summary> [Parameter(ParameterSetName = DynamicTypeSet)] [Parameter(ParameterSetName = TypeDataSet)] public SwitchParameter Force { get { return _force; } set { _force = value; } } #endregion dynamic type set #region strong type data set private TypeData[] _typeData; /// <summary> /// The TypeData instances. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = TypeDataSet)] public TypeData[] TypeData { get { return _typeData; } set { _typeData = value; } } #endregion strong type data set /// <summary> /// This method verify if the Type Table is shared and cannot be updated. /// </summary> protected override void BeginProcessing() { if (Context.TypeTable.isShared) { var ex = new InvalidOperationException(TypesXmlStrings.SharedTypeTableCannotBeUpdated); this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedTypeTable", ErrorCategory.InvalidOperation, null)); } } /// <summary> /// This method implements the ProcessRecord method for update-typeData command. /// </summary> protected override void ProcessRecord() { switch (ParameterSetName) { case FileParameterSet: ProcessTypeFiles(); break; case DynamicTypeSet: ProcessDynamicType(); break; case TypeDataSet: ProcessStrongTypeData(); break; } } /// <summary> /// This method implements the EndProcessing method for update-typeData command. /// </summary> protected override void EndProcessing() { this.Context.TypeTable.ClearConsolidatedMembers(); } #region strong typeData private void ProcessStrongTypeData() { string action = UpdateDataStrings.UpdateTypeDataAction; string target = UpdateDataStrings.UpdateTypeDataTarget; foreach (TypeData item in _typeData) { // If type contains no members at all, report the error and skip it if (!EnsureTypeDataIsNotEmpty(item)) { continue; } TypeData type = item.Copy(); // Set property IsOverride to be true if -Force parameter is specified if (_force) { type.IsOverride = true; } string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, type.TypeName); if (ShouldProcess(formattedTarget, action)) { try { var errors = new ConcurrentBag<string>(); this.Context.TypeTable.Update(type, errors, false); // Write out errors... if (!errors.IsEmpty) { foreach (string s in errors) { RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } else { // Update successfully, we add the TypeData into cache if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } } } #endregion strong typeData #region dynamic type processing /// <summary> /// Process the dynamic type update. /// </summary> private void ProcessDynamicType() { if (string.IsNullOrWhiteSpace(_typeName)) { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } TypeData type = new(_typeName) { IsOverride = _force }; GetMembers(type.Members); if (_typeConverter != null) { type.TypeConverter = _typeConverter; } if (_typeAdapter != null) { type.TypeAdapter = _typeAdapter; } if (_serializationMethod != null) { type.SerializationMethod = _serializationMethod; } if (_targetTypeForDeserialization != null) { type.TargetTypeForDeserialization = _targetTypeForDeserialization; } if (_serializationDepth != int.MinValue) { type.SerializationDepth = (uint)_serializationDepth; } if (_defaultDisplayProperty != null) { type.DefaultDisplayProperty = _defaultDisplayProperty; } if (_inheritPropertySerializationSet != null) { type.InheritPropertySerializationSet = _inheritPropertySerializationSet.Value; } if (_stringSerializationSource != null) { type.StringSerializationSource = _stringSerializationSource; } if (_defaultDisplayPropertySet != null) { PropertySetData defaultDisplayPropertySet = new(_defaultDisplayPropertySet); type.DefaultDisplayPropertySet = defaultDisplayPropertySet; } if (_defaultKeyPropertySet != null) { PropertySetData defaultKeyPropertySet = new(_defaultKeyPropertySet); type.DefaultKeyPropertySet = defaultKeyPropertySet; } if (_propertySerializationSet != null) { PropertySetData propertySerializationSet = new(_propertySerializationSet); type.PropertySerializationSet = propertySerializationSet; } // If the type contains no members at all, report the error and return if (!EnsureTypeDataIsNotEmpty(type)) { return; } // Load the resource strings string action = UpdateDataStrings.UpdateTypeDataAction; string target = UpdateDataStrings.UpdateTypeDataTarget; string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, _typeName); if (ShouldProcess(formattedTarget, action)) { try { var errors = new ConcurrentBag<string>(); this.Context.TypeTable.Update(type, errors, false); // Write out errors... if (!errors.IsEmpty) { foreach (string s in errors) { RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } else { // Update successfully, we add the TypeData into cache if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, false)); } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } } /// <summary> /// Get the members for the TypeData. /// </summary> /// <returns></returns> private void GetMembers(Dictionary<string, TypeMemberData> members) { if (!_isMemberTypeSet) { // If the MemberType is not specified, the MemberName, Value, and SecondValue parameters // should not be specified either if (_memberName != null || HasBeenSpecified(_value1) || _value2 != null) { ThrowTerminatingError(NewError("MemberTypeIsMissing", UpdateDataStrings.MemberTypeIsMissing, null)); } return; } switch (MemberType) { case PSMemberTypes.NoteProperty: NotePropertyData note = GetNoteProperty(); members.Add(note.Name, note); break; case PSMemberTypes.AliasProperty: AliasPropertyData alias = GetAliasProperty(); members.Add(alias.Name, alias); break; case PSMemberTypes.ScriptProperty: ScriptPropertyData scriptProperty = GetScriptProperty(); members.Add(scriptProperty.Name, scriptProperty); break; case PSMemberTypes.CodeProperty: CodePropertyData codeProperty = GetCodeProperty(); members.Add(codeProperty.Name, codeProperty); break; case PSMemberTypes.ScriptMethod: ScriptMethodData scriptMethod = GetScriptMethod(); members.Add(scriptMethod.Name, scriptMethod); break; case PSMemberTypes.CodeMethod: CodeMethodData codeMethod = GetCodeMethod(); members.Add(codeMethod.Name, codeMethod); break; default: ThrowTerminatingError(NewError("CannotUpdateMemberType", UpdateDataStrings.CannotUpdateMemberType, null, _memberType.ToString())); break; } } private static T GetParameterType<T>(object sourceValue) { return (T)LanguagePrimitives.ConvertTo(sourceValue, typeof(T), CultureInfo.InvariantCulture); } private void EnsureMemberNameHasBeenSpecified() { if (string.IsNullOrEmpty(_memberName)) { ThrowTerminatingError(NewError("MemberNameShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "MemberName", _memberType)); } } private void EnsureValue1HasBeenSpecified() { if (!HasBeenSpecified(_value1)) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldBeSpecified, null, "Value", _memberType)); } } private void EnsureValue1NotNullOrEmpty() { if (_value1 is string) { if (string.IsNullOrEmpty((string)_value1)) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } return; } if (_value1 == null) { ThrowTerminatingError(NewError("ValueShouldBeSpecified", UpdateDataStrings.ShouldNotBeNull, null, "Value", _memberType)); } } private void EnsureValue2HasNotBeenSpecified() { if (_value2 != null) { ThrowTerminatingError(NewError("SecondValueShouldNotBeSpecified", UpdateDataStrings.ShouldNotBeSpecified, null, "SecondValue", _memberType)); } } private void EnsureValue1AndValue2AreNotBothNull() { if (_value1 == null && _value2 == null) { ThrowTerminatingError(NewError("ValueAndSecondValueAreNotBothNull", UpdateDataStrings.Value1AndValue2AreNotBothNull, null, _memberType)); } } /// <summary> /// Check if the TypeData instance contains no members. /// </summary> /// <param name="typeData"></param> /// <returns>False if empty, true if not.</returns> private bool EnsureTypeDataIsNotEmpty(TypeData typeData) { if (typeData.Members.Count == 0 && typeData.StandardMembers.Count == 0 && typeData.TypeConverter == null && typeData.TypeAdapter == null && typeData.DefaultDisplayPropertySet == null && typeData.DefaultKeyPropertySet == null && typeData.PropertySerializationSet == null) { this.WriteError(NewError("TypeDataEmpty", UpdateDataStrings.TypeDataEmpty, null, typeData.TypeName)); return false; } return true; } private NotePropertyData GetNoteProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); return new NotePropertyData(_memberName, _value1); } private AliasPropertyData GetAliasProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1NotNullOrEmpty(); AliasPropertyData alias; string referencedName = GetParameterType<string>(_value1); if (_value2 != null) { Type type = GetParameterType<Type>(_value2); alias = new AliasPropertyData(_memberName, referencedName, type); return alias; } alias = new AliasPropertyData(_memberName, referencedName); return alias; } private ScriptPropertyData GetScriptProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1AndValue2AreNotBothNull(); ScriptBlock value1ScriptBlock = null; if (_value1 != null) { value1ScriptBlock = GetParameterType<ScriptBlock>(_value1); } ScriptBlock value2ScriptBlock = null; if (_value2 != null) { value2ScriptBlock = GetParameterType<ScriptBlock>(_value2); } ScriptPropertyData scriptProperty = new(_memberName, value1ScriptBlock, value2ScriptBlock); return scriptProperty; } private CodePropertyData GetCodeProperty() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue1AndValue2AreNotBothNull(); MethodInfo value1CodeReference = null; if (_value1 != null) { value1CodeReference = GetParameterType<MethodInfo>(_value1); } MethodInfo value2CodeReference = null; if (_value2 != null) { value2CodeReference = GetParameterType<MethodInfo>(_value2); } CodePropertyData codeProperty = new(_memberName, value1CodeReference, value2CodeReference); return codeProperty; } private ScriptMethodData GetScriptMethod() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); ScriptBlock method = GetParameterType<ScriptBlock>(_value1); ScriptMethodData scriptMethod = new(_memberName, method); return scriptMethod; } private CodeMethodData GetCodeMethod() { EnsureMemberNameHasBeenSpecified(); EnsureValue1HasBeenSpecified(); EnsureValue2HasNotBeenSpecified(); MethodInfo codeReference = GetParameterType<MethodInfo>(_value1); CodeMethodData codeMethod = new(_memberName, codeReference); return codeMethod; } /// <summary> /// Generate error record. /// </summary> /// <param name="errorId"></param> /// <param name="template"></param> /// <param name="targetObject"></param> /// <param name="args"></param> /// <returns></returns> private static ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); ErrorRecord errorRecord = new( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, targetObject); return errorRecord; } #endregion dynamic type processing #region type files processing private void ProcessTypeFiles() { Collection<string> prependPathTotal = Glob(this.PrependPath, "TypesPrependPathException", this); Collection<string> appendPathTotal = Glob(this.AppendPath, "TypesAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob if ((PrependPath.Length > 0 || AppendPath.Length > 0) && prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } string action = UpdateDataStrings.UpdateTypeDataAction; // Load the resource once and format it whenever a new target // filename is available string target = UpdateDataStrings.UpdateTarget; if (Context.InitialSessionState != null) { // This hashSet is to detect if there are duplicate type files var fullFileNameHash = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); var newTypes = new Collection<SessionStateTypeEntry>(); for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, prependPathTotal[i]); string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(prependPathTotal[i], Context) ?? prependPathTotal[i]; if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i])); } } } // Copy everything from context's TypeTable to newTypes foreach (var entry in Context.InitialSessionState.Types) { if (entry.FileName != null) { string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(entry); } } else { newTypes.Add(entry); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.InvariantCulture, target, appendPathTotalItem); string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(appendPathTotalItem, Context) ?? appendPathTotalItem; if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(resolvedPath)) { fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); } } } Context.InitialSessionState.Types.Clear(); Context.TypeTable.Clear(); var errors = new ConcurrentBag<string>(); foreach (SessionStateTypeEntry sste in newTypes) { try { if (sste.TypeTable != null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateTypeWithTypeTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateTypeWithTypeTable", ErrorCategory.InvalidOperation, null)); continue; } else if (sste.FileName != null) { bool unused; Context.TypeTable.Update(sste.FileName, sste.FileName, errors, Context.AuthorizationManager, Context.InitialSessionState.Host, out unused); } else { Context.TypeTable.Update(sste.TypeData, errors, sste.IsRemove); } } catch (RuntimeException ex) { this.WriteError(new ErrorRecord(ex, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } Context.InitialSessionState.Types.Add(sste); // Write out any errors... if (!errors.IsEmpty) { foreach (string s in errors) { RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } errors = new ConcurrentBag<string>(); } } } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-Typedata to work"); } } #endregion type files processing } /// <summary> /// This class implements update-typeData command. /// </summary> [Cmdlet(VerbsData.Update, "FormatData", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low, DefaultParameterSetName = FileParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097135")] public class UpdateFormatDataCommand : UpdateData { /// <summary> /// This method verify if the Format database manager is shared and cannot be updated. /// </summary> protected override void BeginProcessing() { if (Context.FormatDBManager.isShared) { var ex = new InvalidOperationException(FormatAndOutXmlLoadingStrings.SharedFormatTableCannotBeUpdated); this.ThrowTerminatingError(new ErrorRecord(ex, "CannotUpdateSharedFormatTable", ErrorCategory.InvalidOperation, null)); } } /// <summary> /// This method implements the ProcessRecord method for update-FormatData command. /// </summary> protected override void ProcessRecord() { Collection<string> prependPathTotal = Glob(this.PrependPath, "FormatPrependPathException", this); Collection<string> appendPathTotal = Glob(this.AppendPath, "FormatAppendPathException", this); // There are file path input but they did not pass the validation in the method Glob if ((PrependPath.Length > 0 || AppendPath.Length > 0) && prependPathTotal.Count == 0 && appendPathTotal.Count == 0) { return; } string action = UpdateDataStrings.UpdateFormatDataAction; // Load the resource once and format it whenever a new target // filename is available string target = UpdateDataStrings.UpdateTarget; if (Context.InitialSessionState != null) { if (Context.InitialSessionState.DisableFormatUpdates) { throw new PSInvalidOperationException(UpdateDataStrings.FormatUpdatesDisabled); } // This hashSet is to detect if there are duplicate format files var fullFileNameHash = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); var newFormats = new Collection<SessionStateFormatEntry>(); for (int i = prependPathTotal.Count - 1; i >= 0; i--) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, prependPathTotal[i]); if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(prependPathTotal[i])) { fullFileNameHash.Add(prependPathTotal[i]); newFormats.Add(new SessionStateFormatEntry(prependPathTotal[i])); } } } // Always add InitialSessionState.Formats to the new list foreach (SessionStateFormatEntry entry in Context.InitialSessionState.Formats) { if (entry.FileName != null) { if (!fullFileNameHash.Contains(entry.FileName)) { fullFileNameHash.Add(entry.FileName); newFormats.Add(entry); } } else { newFormats.Add(entry); } } foreach (string appendPathTotalItem in appendPathTotal) { string formattedTarget = string.Format(CultureInfo.CurrentCulture, target, appendPathTotalItem); if (ShouldProcess(formattedTarget, action)) { if (!fullFileNameHash.Contains(appendPathTotalItem)) { fullFileNameHash.Add(appendPathTotalItem); newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem)); } } } var originalFormats = Context.InitialSessionState.Formats; try { // Always rebuild the format information Context.InitialSessionState.Formats.Clear(); var entries = new Collection<PSSnapInTypeAndFormatErrors>(); // Now update the formats... foreach (SessionStateFormatEntry ssfe in newFormats) { string name = ssfe.FileName; PSSnapInInfo snapin = ssfe.PSSnapIn; if (snapin != null && !string.IsNullOrEmpty(snapin.Name)) { name = snapin.Name; } if (ssfe.Formattable != null) { var ex = new PSInvalidOperationException(UpdateDataStrings.CannotUpdateFormatWithFormatTable); this.WriteError(new ErrorRecord(ex, "CannotUpdateFormatWithFormatTable", ErrorCategory.InvalidOperation, null)); continue; } else if (ssfe.FormatData != null) { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FormatData)); } else { entries.Add(new PSSnapInTypeAndFormatErrors(name, ssfe.FileName)); } Context.InitialSessionState.Formats.Add(ssfe); } if (entries.Count > 0) { Context.FormatDBManager.UpdateDataBase(entries, this.Context.AuthorizationManager, this.Context.EngineHostInterface, false); FormatAndTypeDataHelper.ThrowExceptionOnError("ErrorsUpdatingFormats", null, entries, FormatAndTypeDataHelper.Category.Formats); } } catch (RuntimeException e) { // revert Formats if there is a failure Context.InitialSessionState.Formats.Clear(); Context.InitialSessionState.Formats.Add(originalFormats); this.WriteError(new ErrorRecord(e, "FormatXmlUpdateException", ErrorCategory.InvalidOperation, null)); } } else { Dbg.Assert(false, "InitialSessionState must be non-null for Update-FormatData to work"); } } } /// <summary> /// Remove-TypeData cmdlet. /// </summary> [Cmdlet(VerbsCommon.Remove, "TypeData", SupportsShouldProcess = true, DefaultParameterSetName = RemoveTypeDataSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096622")] public class RemoveTypeDataCommand : PSCmdlet { private const string RemoveTypeSet = "RemoveTypeSet"; private const string RemoveFileSet = "RemoveFileSet"; private const string RemoveTypeDataSet = "RemoveTypeDataSet"; private string _typeName; /// <summary> /// The target type to remove. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveTypeSet)] [ArgumentToTypeNameTransformationAttribute()] [ValidateNotNullOrEmpty] public string TypeName { get { return _typeName; } set { _typeName = value; } } private string[] _typeFiles; /// <summary> /// The type xml file to remove from the cache. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] [Parameter(Mandatory = true, ParameterSetName = RemoveFileSet)] [ValidateNotNullOrEmpty] public string[] Path { get { return _typeFiles; } set { _typeFiles = value; } } private TypeData _typeData; /// <summary> /// The TypeData to remove. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = RemoveTypeDataSet)] public TypeData TypeData { get { return _typeData; } set { _typeData = value; } } private static void ConstructFileToIndexMap(string fileName, int index, Dictionary<string, List<int>> fileNameToIndexMap) { List<int> indexList; if (fileNameToIndexMap.TryGetValue(fileName, out indexList)) { indexList.Add(index); } else { fileNameToIndexMap[fileName] = new List<int> { index }; } } /// <summary> /// This method implements the ProcessRecord method for Remove-TypeData command. /// </summary> protected override void ProcessRecord() { if (ParameterSetName == RemoveFileSet) { // Load the resource strings string removeFileAction = UpdateDataStrings.RemoveTypeFileAction; string removeFileTarget = UpdateDataStrings.UpdateTarget; Collection<string> typeFileTotal = UpdateData.Glob(_typeFiles, "TypePathException", this); if (typeFileTotal.Count == 0) { return; } // Key of the map is the name of the file that is in the cache. Value of the map is a index list. Duplicate files might // exist in the cache because the user can add arbitrary files to the cache by $host.Runspace.InitialSessionState.Types.Add() Dictionary<string, List<int>> fileToIndexMap = new(StringComparer.OrdinalIgnoreCase); List<int> indicesToRemove = new(); if (Context.InitialSessionState != null) { for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) { string fileName = Context.InitialSessionState.Types[index].FileName; if (fileName == null) { continue; } // Resolving the file path because the path to the types file in module manifest is now specified as // ..\..\types.ps1xml which expands to C:\Windows\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Core\..\..\types.ps1xml fileName = ModuleCmdletBase.ResolveRootedFilePath(fileName, Context) ?? fileName; ConstructFileToIndexMap(fileName, index, fileToIndexMap); } } foreach (string typeFile in typeFileTotal) { string removeFileFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeFileTarget, typeFile); if (ShouldProcess(removeFileFormattedTarget, removeFileAction)) { List<int> indexList; if (fileToIndexMap.TryGetValue(typeFile, out indexList)) { indicesToRemove.AddRange(indexList); } else { this.WriteError(NewError("TypeFileNotExistsInCurrentSession", UpdateDataStrings.TypeFileNotExistsInCurrentSession, null, typeFile)); } } } if (indicesToRemove.Count > 0) { indicesToRemove.Sort(); for (int i = indicesToRemove.Count - 1; i >= 0; i--) { if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.RemoveItem(indicesToRemove[i]); } } try { if (Context.InitialSessionState != null) { bool oldRefreshTypeFormatSetting = Context.InitialSessionState.RefreshTypeAndFormatSetting; try { Context.InitialSessionState.RefreshTypeAndFormatSetting = true; Context.InitialSessionState.UpdateTypes(Context, false); } finally { Context.InitialSessionState.RefreshTypeAndFormatSetting = oldRefreshTypeFormatSetting; } } } catch (RuntimeException ex) { this.WriteError(new ErrorRecord(ex, "TypesFileRemoveException", ErrorCategory.InvalidOperation, null)); } } return; } // Load the resource strings string removeTypeAction = UpdateDataStrings.RemoveTypeDataAction; string removeTypeTarget = UpdateDataStrings.RemoveTypeDataTarget; string typeNameToRemove = null; if (ParameterSetName == RemoveTypeDataSet) { typeNameToRemove = _typeData.TypeName; } else { if (string.IsNullOrWhiteSpace(_typeName)) { ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } typeNameToRemove = _typeName; } Dbg.Assert(!string.IsNullOrEmpty(typeNameToRemove), "TypeNameToRemove should be not null and not empty at this point"); TypeData type = new(typeNameToRemove); string removeTypeFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeTypeTarget, typeNameToRemove); if (ShouldProcess(removeTypeFormattedTarget, removeTypeAction)) { try { var errors = new ConcurrentBag<string>(); Context.TypeTable.Update(type, errors, true); // Write out errors... if (!errors.IsEmpty) { foreach (string s in errors) { RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); } } else { // Type is removed successfully, add it into the cache if (Context.InitialSessionState != null) { Context.InitialSessionState.Types.Add(new SessionStateTypeEntry(type, true)); } else { Dbg.Assert(false, "InitialSessionState must be non-null for Remove-Typedata to work"); } } } catch (RuntimeException e) { this.WriteError(new ErrorRecord(e, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); } } } /// <summary> /// This method implements the EndProcessing method for Remove-TypeData command. /// </summary> protected override void EndProcessing() { this.Context.TypeTable.ClearConsolidatedMembers(); } private static ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); ErrorRecord errorRecord = new( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, targetObject); return errorRecord; } } /// <summary> /// Get-TypeData cmdlet. /// </summary> [Cmdlet(VerbsCommon.Get, "TypeData", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097018")] [OutputType(typeof(System.Management.Automation.PSObject))] public class GetTypeDataCommand : PSCmdlet { private WildcardPattern[] _filter; /// <summary> /// Get Formatting information only for the specified typename. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [ValidateNotNullOrEmpty] [Parameter(Position = 0, ValueFromPipeline = true)] public string[] TypeName { get; set; } private void ValidateTypeName() { if (TypeName == null) { _filter = new WildcardPattern[] { WildcardPattern.Get("*", WildcardOptions.None) }; return; } var typeNames = new List<string>(); var exception = new InvalidOperationException(UpdateDataStrings.TargetTypeNameEmpty); foreach (string typeName in TypeName) { if (string.IsNullOrWhiteSpace(typeName)) { WriteError( new ErrorRecord( exception, "TargetTypeNameEmpty", ErrorCategory.InvalidOperation, typeName)); continue; } Type type; string typeNameInUse = typeName; // Respect the type shortcut if (LanguagePrimitives.TryConvertTo(typeNameInUse, out type)) { typeNameInUse = type.FullName; } typeNames.Add(typeNameInUse); } _filter = new WildcardPattern[typeNames.Count]; for (int i = 0; i < _filter.Length; i++) { _filter[i] = WildcardPattern.Get(typeNames[i], WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); } } /// <summary> /// Takes out the content from the database and writes it out. /// </summary> protected override void ProcessRecord() { ValidateTypeName(); Dictionary<string, TypeData> alltypes = Context.TypeTable.GetAllTypeData(); Collection<TypeData> typedefs = new(); foreach (string type in alltypes.Keys) { foreach (WildcardPattern pattern in _filter) { if (pattern.IsMatch(type)) { typedefs.Add(alltypes[type]); break; } } } // write out all the available type definitions foreach (TypeData typedef in typedefs) { WriteObject(typedef); } } } /// <summary> /// To make it easier to specify a TypeName, we add an ArgumentTransformationAttribute here. /// * string: return the string /// * Type: return the Type.ToString() /// * instance: return instance.GetType().ToString() . /// </summary> internal sealed class ArgumentToTypeNameTransformationAttribute : ArgumentTransformationAttribute { public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { string typeName; object target = PSObject.Base(inputData); if (target is Type) { typeName = ((Type)target).FullName; } else if (target is string) { // Respect the type shortcut Type type; typeName = (string)target; if (LanguagePrimitives.TryConvertTo(typeName, out type)) { typeName = type.FullName; } } else if (target is TypeData) { typeName = ((TypeData)target).TypeName; } else { typeName = target.GetType().FullName; } return typeName; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Buffers { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Text; using DotNetty.Common; using DotNetty.Common.Internal; using DotNetty.Common.Internal.Logging; using DotNetty.Common.Utilities; public class PooledByteBufferAllocator : AbstractByteBufferAllocator { static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance<PooledByteBufferAllocator>(); static readonly int DEFAULT_NUM_HEAP_ARENA; static readonly int DEFAULT_PAGE_SIZE; static readonly int DEFAULT_MAX_ORDER; // 8192 << 11 = 16 MiB per chunk static readonly int DEFAULT_TINY_CACHE_SIZE; static readonly int DEFAULT_SMALL_CACHE_SIZE; static readonly int DEFAULT_NORMAL_CACHE_SIZE; static readonly int DEFAULT_MAX_CACHED_BUFFER_CAPACITY; static readonly int DEFAULT_CACHE_TRIM_INTERVAL; static readonly int MIN_PAGE_SIZE = 4096; static readonly int MAX_CHUNK_SIZE = (int)((int.MaxValue + 1L) / 2); static PooledByteBufferAllocator() { int defaultPageSize = SystemPropertyUtil.GetInt("io.netty.allocator.pageSize", 8192); Exception pageSizeFallbackCause = null; try { ValidateAndCalculatePageShifts(defaultPageSize); } catch (Exception t) { pageSizeFallbackCause = t; defaultPageSize = 8192; } DEFAULT_PAGE_SIZE = defaultPageSize; int defaultMaxOrder = SystemPropertyUtil.GetInt("io.netty.allocator.maxOrder", 11); Exception maxOrderFallbackCause = null; try { ValidateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder); } catch (Exception t) { maxOrderFallbackCause = t; defaultMaxOrder = 11; } DEFAULT_MAX_ORDER = defaultMaxOrder; // todo: Determine reasonable default for heapArenaCount // Assuming each arena has 3 chunks, the pool should not consume more than 50% of max memory. // Use 2 * cores by default to reduce contention as we use 2 * cores for the number of EventLoops // in NIO and EPOLL as well. If we choose a smaller number we will run into hotspots as allocation and // deallocation needs to be synchronized on the PoolArena. // See https://github.com/netty/netty/issues/3888 int defaultMinNumArena = Environment.ProcessorCount * 2; int defaultChunkSize = DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER; DEFAULT_NUM_HEAP_ARENA = Math.Max(0, SystemPropertyUtil.GetInt("dotNetty.allocator.numHeapArenas", defaultMinNumArena)); // cache sizes DEFAULT_TINY_CACHE_SIZE = SystemPropertyUtil.GetInt("io.netty.allocator.tinyCacheSize", 512); DEFAULT_SMALL_CACHE_SIZE = SystemPropertyUtil.GetInt("io.netty.allocator.smallCacheSize", 256); DEFAULT_NORMAL_CACHE_SIZE = SystemPropertyUtil.GetInt("io.netty.allocator.normalCacheSize", 64); // 32 kb is the default maximum capacity of the cached buffer. Similar to what is explained in // 'Scalable memory allocation using jemalloc' DEFAULT_MAX_CACHED_BUFFER_CAPACITY = SystemPropertyUtil.GetInt("io.netty.allocator.maxCachedBufferCapacity", 32 * 1024); // the number of threshold of allocations when cached entries will be freed up if not frequently used DEFAULT_CACHE_TRIM_INTERVAL = SystemPropertyUtil.GetInt( "io.netty.allocator.cacheTrimInterval", 8192); if (Logger.DebugEnabled) { Logger.Debug("-Dio.netty.allocator.numHeapArenas: {}", DEFAULT_NUM_HEAP_ARENA); if (pageSizeFallbackCause == null) { Logger.Debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE); } else { Logger.Debug("-Dio.netty.allocator.pageSize: {}", DEFAULT_PAGE_SIZE, pageSizeFallbackCause); } if (maxOrderFallbackCause == null) { Logger.Debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER); } else { Logger.Debug("-Dio.netty.allocator.maxOrder: {}", DEFAULT_MAX_ORDER, maxOrderFallbackCause); } Logger.Debug("-Dio.netty.allocator.chunkSize: {}", DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER); Logger.Debug("-Dio.netty.allocator.tinyCacheSize: {}", DEFAULT_TINY_CACHE_SIZE); Logger.Debug("-Dio.netty.allocator.smallCacheSize: {}", DEFAULT_SMALL_CACHE_SIZE); Logger.Debug("-Dio.netty.allocator.normalCacheSize: {}", DEFAULT_NORMAL_CACHE_SIZE); Logger.Debug("-Dio.netty.allocator.maxCachedBufferCapacity: {}", DEFAULT_MAX_CACHED_BUFFER_CAPACITY); Logger.Debug("-Dio.netty.allocator.cacheTrimInterval: {}", DEFAULT_CACHE_TRIM_INTERVAL); } Default = new PooledByteBufferAllocator(); } public static readonly PooledByteBufferAllocator Default; readonly PoolArena<byte[]>[] heapArenas; readonly int tinyCacheSize; readonly int smallCacheSize; readonly int normalCacheSize; readonly IReadOnlyList<IPoolArenaMetric> heapArenaMetrics; readonly PoolThreadLocalCache threadCache; public PooledByteBufferAllocator() : this(DEFAULT_NUM_HEAP_ARENA, DEFAULT_PAGE_SIZE, DEFAULT_MAX_ORDER) { } public PooledByteBufferAllocator(int heapArenaCount, int pageSize, int maxOrder) : this(heapArenaCount, pageSize, maxOrder, DEFAULT_TINY_CACHE_SIZE, DEFAULT_SMALL_CACHE_SIZE, DEFAULT_NORMAL_CACHE_SIZE) { } public PooledByteBufferAllocator(int heapArenaCount, int pageSize, int maxOrder, int tinyCacheSize, int smallCacheSize, int normalCacheSize) : this(heapArenaCount, pageSize, maxOrder, tinyCacheSize, smallCacheSize, normalCacheSize, int.MaxValue) { } public PooledByteBufferAllocator(long maxMemory) : this(DEFAULT_NUM_HEAP_ARENA, DEFAULT_PAGE_SIZE, DEFAULT_MAX_ORDER, DEFAULT_TINY_CACHE_SIZE, DEFAULT_SMALL_CACHE_SIZE, DEFAULT_NORMAL_CACHE_SIZE, Math.Max(1, (int)Math.Min(maxMemory / DEFAULT_NUM_HEAP_ARENA / (DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER), int.MaxValue))) { } public PooledByteBufferAllocator(int heapArenaCount, int pageSize, int maxOrder, int tinyCacheSize, int smallCacheSize, int normalCacheSize, int maxChunkCountPerArena) { Contract.Requires(heapArenaCount >= 0); this.threadCache = new PoolThreadLocalCache(this); this.tinyCacheSize = tinyCacheSize; this.smallCacheSize = smallCacheSize; this.normalCacheSize = normalCacheSize; int chunkSize = ValidateAndCalculateChunkSize(pageSize, maxOrder); int pageShifts = ValidateAndCalculatePageShifts(pageSize); if (heapArenaCount > 0) { this.heapArenas = NewArenaArray<byte[]>(heapArenaCount); var metrics = new List<IPoolArenaMetric>(this.heapArenas.Length); for (int i = 0; i < this.heapArenas.Length; i++) { var arena = new HeapArena(this, pageSize, maxOrder, pageShifts, chunkSize, maxChunkCountPerArena); this.heapArenas[i] = arena; metrics.Add(arena); } this.heapArenaMetrics = metrics.AsReadOnly(); } else { this.heapArenas = null; this.heapArenaMetrics = new List<IPoolArenaMetric>(); } } static PoolArena<T>[] NewArenaArray<T>(int size) => new PoolArena<T>[size]; static int ValidateAndCalculatePageShifts(int pageSize) { Contract.Requires(pageSize >= MIN_PAGE_SIZE); Contract.Requires((pageSize & pageSize - 1) == 0, "Expected power of 2"); // Logarithm base 2. At this point we know that pageSize is a power of two. return IntegerExtensions.Log2(pageSize); } static int ValidateAndCalculateChunkSize(int pageSize, int maxOrder) { if (maxOrder > 14) { throw new ArgumentException("maxOrder: " + maxOrder + " (expected: 0-14)"); } // Ensure the resulting chunkSize does not overflow. int chunkSize = pageSize; for (int i = maxOrder; i > 0; i--) { if (chunkSize > MAX_CHUNK_SIZE >> 1) { throw new ArgumentException($"pageSize ({pageSize}) << maxOrder ({maxOrder}) must not exceed {MAX_CHUNK_SIZE}"); } chunkSize <<= 1; } return chunkSize; } protected override IByteBuffer NewBuffer(int initialCapacity, int maxCapacity) { PoolThreadCache<byte[]> cache = this.threadCache.Value; PoolArena<byte[]> heapArena = cache.HeapArena; IByteBuffer buf; if (heapArena != null) { buf = heapArena.Allocate(cache, initialCapacity, maxCapacity); } else { buf = new UnpooledHeapByteBuffer(this, initialCapacity, maxCapacity); } return ToLeakAwareBuffer(buf); } sealed class PoolThreadLocalCache : FastThreadLocal<PoolThreadCache<byte[]>> { readonly PooledByteBufferAllocator owner; public PoolThreadLocalCache(PooledByteBufferAllocator owner) { this.owner = owner; } protected override PoolThreadCache<byte[]> GetInitialValue() { lock (this) { PoolArena<byte[]> heapArena = this.GetLeastUsedArena(this.owner.heapArenas); return new PoolThreadCache<byte[]>( heapArena, this.owner.tinyCacheSize, this.owner.smallCacheSize, this.owner.normalCacheSize, DEFAULT_MAX_CACHED_BUFFER_CAPACITY, DEFAULT_CACHE_TRIM_INTERVAL); } } protected override void OnRemoval(PoolThreadCache<byte[]> threadCache) => threadCache.Free(); PoolArena<T> GetLeastUsedArena<T>(PoolArena<T>[] arenas) { if (arenas == null || arenas.Length == 0) { return null; } PoolArena<T> minArena = arenas[0]; for (int i = 1; i < arenas.Length; i++) { PoolArena<T> arena = arenas[i]; if (arena.NumThreadCaches < minArena.NumThreadCaches) { minArena = arena; } } return minArena; } } /** * Return the number of heap arenas. */ public int NumHeapArenas() => this.heapArenaMetrics.Count; /** * Return a {@link List} of all heap {@link PoolArenaMetric}s that are provided by this pool. */ public IReadOnlyList<IPoolArenaMetric> HeapArenas() => this.heapArenaMetrics; /** * Return the number of thread local caches used by this {@link PooledByteBufferAllocator}. */ public int NumThreadLocalCaches() { PoolArena<byte[]>[] arenas = this.heapArenas; if (arenas == null) { return 0; } int total = 0; for (int i = 0; i < arenas.Length; i++) { total += arenas[i].NumThreadCaches; } return total; } /// Return the size of the tiny cache. public int TinyCacheSize => this.tinyCacheSize; /// Return the size of the small cache. public int SmallCacheSize => this.smallCacheSize; /// Return the size of the normal cache. public int NormalCacheSize => this.normalCacheSize; internal PoolThreadCache<T> ThreadCache<T>() => (PoolThreadCache<T>)(object)this.threadCache.Value; /// Returns the status of the allocator (which contains all metrics) as string. Be aware this may be expensive /// and so should not called too frequently. public string DumpStats() { int heapArenasLen = this.heapArenas?.Length ?? 0; StringBuilder buf = new StringBuilder(512) .Append(heapArenasLen) .Append(" heap arena(s):") .Append(StringUtil.Newline); if (heapArenasLen > 0) { foreach (PoolArena<byte[]> a in this.heapArenas) { buf.Append(a); } } return buf.ToString(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime; namespace Orleans.Streams { /// <summary> /// DeploymentBasedQueueBalancer is a stream queue balancer that uses deployment information to /// help balance queue distribution. /// DeploymentBasedQueueBalancer uses the deployment configuration to determine how many silos /// to expect and uses a silo status oracle to determine which of the silos are available. With /// this information it tries to balance the queues using a best fit resource balancing algorithm. /// </summary> internal class DeploymentBasedQueueBalancer : ISiloStatusListener, IStreamQueueBalancer { private readonly TimeSpan siloMaturityPeriod; private readonly ISiloStatusOracle siloStatusOracle; private readonly IDeploymentConfiguration deploymentConfig; private readonly ReadOnlyCollection<QueueId> allQueues; private readonly List<IStreamQueueBalanceListener> queueBalanceListeners; private readonly ConcurrentDictionary<SiloAddress, bool> immatureSilos; private readonly bool isFixed; private bool isStarting; public DeploymentBasedQueueBalancer( ISiloStatusOracle siloStatusOracle, IDeploymentConfiguration deploymentConfig, IStreamQueueMapper queueMapper, TimeSpan maturityPeriod, bool isFixed) { if (siloStatusOracle == null) { throw new ArgumentNullException("siloStatusOracle"); } if (deploymentConfig == null) { throw new ArgumentNullException("deploymentConfig"); } if (queueMapper == null) { throw new ArgumentNullException("queueMapper"); } this.siloStatusOracle = siloStatusOracle; this.deploymentConfig = deploymentConfig; allQueues = new ReadOnlyCollection<QueueId>(queueMapper.GetAllQueues().ToList()); queueBalanceListeners = new List<IStreamQueueBalanceListener>(); immatureSilos = new ConcurrentDictionary<SiloAddress, bool>(); this.isFixed = isFixed; siloMaturityPeriod = maturityPeriod; isStarting = true; // register for notification of changes to silo status for any silo in the cluster this.siloStatusOracle.SubscribeToSiloStatusEvents(this); // record all already active silos as already mature. // Even if they are not yet, they will be mature by the time I mature myself (after I become !isStarting). foreach (var silo in siloStatusOracle.GetApproximateSiloStatuses(true).Keys.Where(s => !s.Equals(siloStatusOracle.SiloAddress))) { immatureSilos[silo] = false; // record as mature } NotifyAfterStart().Ignore(); } private async Task NotifyAfterStart() { await Task.Delay(siloMaturityPeriod); isStarting = false; await NotifyListeners(); } /// <summary> /// Called when the status of a silo in the cluster changes. /// - Notify listeners /// </summary> /// <param name="updatedSilo">Silo which status has changed</param> /// <param name="status">new silo status</param> public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { if (status == SiloStatus.Dead) { // just clean up garbage from immatureSilos. bool ignore; immatureSilos.TryRemove(updatedSilo, out ignore); } SiloStatusChangeNotification().Ignore(); } private async Task SiloStatusChangeNotification() { List<Task> tasks = new List<Task>(); // look at all currently active silos not including myself foreach (var silo in siloStatusOracle.GetApproximateSiloStatuses(true).Keys.Where(s => !s.Equals(siloStatusOracle.SiloAddress))) { bool ignore; if (!immatureSilos.TryGetValue(silo, out ignore)) { tasks.Add(RecordImmatureSilo(silo)); } } if (!isStarting) { // notify, uncoditionaly, and deal with changes in GetMyQueues() NotifyListeners().Ignore(); } if (tasks.Count > 0) { await Task.WhenAll(tasks); await NotifyListeners(); // notify, uncoditionaly, and deal with changes it in GetMyQueues() } } private async Task RecordImmatureSilo(SiloAddress updatedSilo) { immatureSilos[updatedSilo] = true; // record as immature await Task.Delay(siloMaturityPeriod); immatureSilos[updatedSilo] = false; // record as mature } public IEnumerable<QueueId> GetMyQueues() { BestFitBalancer<string, QueueId> balancer = GetBalancer(); bool useIdealDistribution = isFixed || isStarting; Dictionary<string, List<QueueId>> distribution = useIdealDistribution ? balancer.IdealDistribution : balancer.GetDistribution(GetActiveSilos(siloStatusOracle, immatureSilos)); List<QueueId> myQueues; if (distribution.TryGetValue(siloStatusOracle.SiloName, out myQueues)) { if (!useIdealDistribution) { HashSet<QueueId> queuesOfImmatureSilos = GetQueuesOfImmatureSilos(siloStatusOracle, immatureSilos, balancer.IdealDistribution); // filter queues that belong to immature silos myQueues.RemoveAll(queue => queuesOfImmatureSilos.Contains(queue)); } return myQueues; } return Enumerable.Empty<QueueId>(); } public bool SubscribeToQueueDistributionChangeEvents(IStreamQueueBalanceListener observer) { if (observer == null) { throw new ArgumentNullException("observer"); } lock (queueBalanceListeners) { if (queueBalanceListeners.Contains(observer)) { return false; } queueBalanceListeners.Add(observer); return true; } } public bool UnSubscribeToQueueDistributionChangeEvents(IStreamQueueBalanceListener observer) { if (observer == null) { throw new ArgumentNullException("observer"); } lock (queueBalanceListeners) { return queueBalanceListeners.Contains(observer) && queueBalanceListeners.Remove(observer); } } /// <summary> /// Checks to see if deployment configuration has changed, by adding or removing silos. /// If so, it updates the list of all silo names and creates a new resource balancer. /// This should occure rarely. /// </summary> private BestFitBalancer<string, QueueId> GetBalancer() { var allSiloNames = deploymentConfig.GetAllSiloNames(); // rebuild balancer with new list of instance names return new BestFitBalancer<string, QueueId>(allSiloNames, allQueues); } private static List<string> GetActiveSilos(ISiloStatusOracle siloStatusOracle, ConcurrentDictionary<SiloAddress, bool> immatureSilos) { var activeSiloNames = new List<string>(); foreach (var kvp in siloStatusOracle.GetApproximateSiloStatuses(true)) { bool immatureBit; if (!(immatureSilos.TryGetValue(kvp.Key, out immatureBit) && immatureBit)) // if not immature now or any more { string siloName; if (siloStatusOracle.TryGetSiloName(kvp.Key, out siloName)) { activeSiloNames.Add(siloName); } } } return activeSiloNames; } private static HashSet<QueueId> GetQueuesOfImmatureSilos(ISiloStatusOracle siloStatusOracle, ConcurrentDictionary<SiloAddress, bool> immatureSilos, Dictionary<string, List<QueueId>> idealDistribution) { HashSet<QueueId> queuesOfImmatureSilos = new HashSet<QueueId>(); foreach (var silo in immatureSilos.Where(s => s.Value)) // take only those from immature set that have their immature status bit set { string siloName; if (siloStatusOracle.TryGetSiloName(silo.Key, out siloName)) { List<QueueId> queues; if (idealDistribution.TryGetValue(siloName, out queues)) { queuesOfImmatureSilos.UnionWith(queues); } } } return queuesOfImmatureSilos; } private Task NotifyListeners() { List<IStreamQueueBalanceListener> queueBalanceListenersCopy; lock (queueBalanceListeners) { queueBalanceListenersCopy = queueBalanceListeners.ToList(); // make copy } var notificatioTasks = new List<Task>(queueBalanceListenersCopy.Count); foreach (IStreamQueueBalanceListener listener in queueBalanceListenersCopy) { notificatioTasks.Add(listener.QueueDistributionChangeNotification()); } return Task.WhenAll(notificatioTasks); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.UserModel { using System; using System.Collections.Generic; /** * Enumerates error values in SpreadsheetML formula calculations. * * See also OOO's excelfileformat.pdf (2.5.6) */ public class FormulaError { static FormulaError() { _values = new FormulaError[] { FormulaError.NULL, FormulaError.DIV0, FormulaError.VALUE, FormulaError.REF, FormulaError.NAME, FormulaError.NUM, FormulaError.NA, FormulaError.CIRCULAR_REF, FormulaError.FUNCTION_NOT_IMPLEMENTED }; foreach (FormulaError error in _values) { bmap.Add(error.Code, error); imap.Add(error.LongCode, error); smap.Add(error.String, error); } } private static FormulaError[] _values; /** * Intended to indicate when two areas are required to intersect, but do not. * <p>Example: * In the case of SUM(B1 C1), the space between B1 and C1 is treated as the binary * intersection operator, when a comma was intended. end example] * </p> */ public static readonly FormulaError NULL = new FormulaError(0x00, "#NULL!"); /** * Intended to indicate when any number, including zero, is divided by zero. * Note: However, any error code divided by zero results in that error code. */ public static readonly FormulaError DIV0 = new FormulaError(0x07, "#DIV/0!"); /** * Intended to indicate when an incompatible type argument is passed to a function, or * an incompatible type operand is used with an operator. * <p>Example: * In the case of a function argument, text was expected, but a number was provided * </p> */ public static readonly FormulaError VALUE = new FormulaError(0x0F, "#VALUE!"); /** * Intended to indicate when a cell reference is invalid. * <p>Example: * If a formula Contains a reference to a cell, and then the row or column Containing that cell is deleted, * a #REF! error results. If a worksheet does not support 20,001 columns, * OFFSET(A1,0,20000) will result in a #REF! error. * </p> */ public static readonly FormulaError REF = new FormulaError(0x17, "#REF!"); /* * Intended to indicate when what looks like a name is used, but no such name has been defined. * <p>Example: * XYZ/3, where XYZ is not a defined name. Total is &amp; A10, * where neither Total nor is is a defined name. Presumably, "Total is " & A10 * was intended. SUM(A1C10), where the range A1:C10 was intended. * </p> */ public static readonly FormulaError NAME = new FormulaError(0x1D, "#NAME?"); /** * Intended to indicate when an argument to a function has a compatible type, but has a * value that is outside the domain over which that function is defined. (This is known as * a domain error.) * <p>Example: * Certain calls to ASIN, ATANH, FACT, and SQRT might result in domain errors. * </p> * Intended to indicate that the result of a function cannot be represented in a value of * the specified type, typically due to extreme magnitude. (This is known as a range * error.) * <p>Example: FACT(1000) might result in a range error. </p> */ public static readonly FormulaError NUM = new FormulaError(0x24, "#NUM!"); /** * Intended to indicate when a designated value is not available. * <p>Example: * Some functions, such as SUMX2MY2, perform a series of operations on corresponding * elements in two arrays. If those arrays do not have the same number of elements, then * for some elements in the longer array, there are no corresponding elements in the * shorter one; that is, one or more values in the shorter array are not available. * </p> * This error value can be produced by calling the function NA */ public static readonly FormulaError NA = new FormulaError(0x2A, "#N/A"); // These are POI-specific error codes // It is desirable to make these (arbitrary) strings look clearly different from any other // value expression that might appear in a formula. In addition these error strings should // look unlike the standard Excel errors. Hence tilde ('~') was used. /** * POI specific code to indicate that there is a circular reference * in the formula */ public static readonly FormulaError CIRCULAR_REF = new FormulaError(unchecked((int)0xFFFFFFC4), "~CIRCULAR~REF~"); /** * POI specific code to indicate that the funcition required is * not implemented in POI */ public static readonly FormulaError FUNCTION_NOT_IMPLEMENTED = new FormulaError(unchecked((int)0xFFFFFFE2), "~FUNCTION~NOT~IMPLEMENTED~"); private byte type; private int longType; private String repr; private FormulaError(int type, String repr) { this.type = (byte)type; this.longType = type; this.repr = repr; //if(imap==null) // imap = new Dictionary<Byte, FormulaError>(); //imap.Add(this.Code, this); //if (smap == null) // smap = new Dictionary<string, FormulaError>(); //smap.Add(this.String, this); } /** * @return numeric code of the error */ public byte Code { get { return type; } } /** * @return long (internal) numeric code of the error */ public int LongCode { get { return longType; } } /** * @return string representation of the error */ public String String { get { return repr; } } private static Dictionary<String, FormulaError> smap = new Dictionary<string, FormulaError>(); private static Dictionary<Byte, FormulaError> bmap = new Dictionary<byte, FormulaError>(); private static Dictionary<int, FormulaError> imap = new Dictionary<int, FormulaError>(); public static bool IsValidCode(int errorCode) { foreach (FormulaError error in _values) { if (error.Code == errorCode) return true; if (error.LongCode == errorCode) return true; } return false; } public static FormulaError ForInt(byte type) { if (bmap.ContainsKey(type)) return bmap[type]; throw new ArgumentException("Unknown error type: " + type); } public static FormulaError ForInt(int type) { if (imap.ContainsKey(type)) return imap[type]; if (bmap.ContainsKey((byte)type)) return bmap[(byte)type]; throw new ArgumentException("Unknown error type: " + type); } public static FormulaError ForString(String code) { if (smap.ContainsKey(code)) return smap[code]; throw new ArgumentException("Unknown error code: " + code); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class output by Measure-Object. /// </summary> public abstract class MeasureInfo { /// <summary> /// Property name. /// </summary> public string Property { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> public sealed class GenericMeasureInfo : MeasureInfo { /// <summary> /// Initializes a new instance of the <see cref="GenericMeasureInfo"/> class. /// </summary> public GenericMeasureInfo() { Average = Sum = Maximum = Minimum = StandardDeviation = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int Count { get; set; } /// <summary> /// The average of property values. /// </summary> public double? Average { get; set; } /// <summary> /// The sum of property values. /// </summary> public double? Sum { get; set; } /// <summary> /// The max of property values. /// </summary> public double? Maximum { get; set; } /// <summary> /// The min of property values. /// </summary> public double? Minimum { get; set; } /// <summary> /// The Standard Deviation of property values. /// </summary> public double? StandardDeviation { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> /// <remarks> /// This class is created to make 'Measure-Object -MAX -MIN' work with ANYTHING that supports 'CompareTo'. /// GenericMeasureInfo class is shipped with PowerShell V2. Fixing this bug requires, changing the type of /// Maximum and Minimum properties which would be a breaking change. Hence created a new class to not /// have an appcompat issues with PS V2. /// </remarks> public sealed class GenericObjectMeasureInfo : MeasureInfo { /// <summary> /// Initializes a new instance of the <see cref="GenericObjectMeasureInfo"/> class. /// Default ctor. /// </summary> public GenericObjectMeasureInfo() { Average = Sum = StandardDeviation = null; Maximum = Minimum = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int Count { get; set; } /// <summary> /// The average of property values. /// </summary> public double? Average { get; set; } /// <summary> /// The sum of property values. /// </summary> public double? Sum { get; set; } /// <summary> /// The max of property values. /// </summary> public object Maximum { get; set; } /// <summary> /// The min of property values. /// </summary> public object Minimum { get; set; } /// <summary> /// The Standard Deviation of property values. /// </summary> public double? StandardDeviation { get; set; } } /// <summary> /// Class output by Measure-Object. /// </summary> public sealed class TextMeasureInfo : MeasureInfo { /// <summary> /// Initializes a new instance of the <see cref="TextMeasureInfo"/> class. /// Default ctor. /// </summary> public TextMeasureInfo() { Lines = Words = Characters = null; } /// <summary> /// Keeping track of number of objects with a certain property. /// </summary> public int? Lines { get; set; } /// <summary> /// The average of property values. /// </summary> public int? Words { get; set; } /// <summary> /// The sum of property values. /// </summary> public int? Characters { get; set; } } /// <summary> /// Measure object cmdlet. /// </summary> [Cmdlet(VerbsDiagnostic.Measure, "Object", DefaultParameterSetName = GenericParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096617", RemotingCapability = RemotingCapability.None)] [OutputType(typeof(GenericMeasureInfo), typeof(TextMeasureInfo), typeof(GenericObjectMeasureInfo))] public sealed class MeasureObjectCommand : PSCmdlet { /// <summary> /// Dictionary to be used by Measure-Object implementation. /// Keys are strings. Keys are compared with OrdinalIgnoreCase. /// </summary> /// <typeparam name="TValue">Value type.</typeparam> private sealed class MeasureObjectDictionary<TValue> : Dictionary<string, TValue> where TValue : new() { /// <summary> /// Initializes a new instance of the <see cref="MeasureObjectDictionary{TValue}"/> class. /// Default ctor. /// </summary> internal MeasureObjectDictionary() : base(StringComparer.OrdinalIgnoreCase) { } /// <summary> /// Attempt to look up the value associated with the /// the specified key. If a value is not found, associate /// the key with a new value created via the value type's /// default constructor. /// </summary> /// <param name="key">The key to look up.</param> /// <returns> /// The existing value, or a newly-created value. /// </returns> public TValue EnsureEntry(string key) { TValue val; if (!TryGetValue(key, out val)) { val = new TValue(); this[key] = val; } return val; } } /// <summary> /// Convenience class to track statistics without having /// to maintain two sets of MeasureInfo and constantly checking /// what mode we're in. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class Statistics { // Common properties internal int count = 0; // Generic/Numeric statistics internal double sum = 0.0; internal double sumPrevious = 0.0; internal double variance = 0.0; internal object max = null; internal object min = null; // Text statistics internal int characters = 0; internal int words = 0; internal int lines = 0; } /// <summary> /// Initializes a new instance of the <see cref="MeasureObjectCommand"/> class. /// Default constructor. /// </summary> public MeasureObjectCommand() : base() { } #region Command Line Switches #region Common parameters in both sets /// <summary> /// Incoming object. /// </summary> /// <value></value> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { get; set; } = AutomationNull.Value; /// <summary> /// Properties to be examined. /// </summary> /// <value></value> [ValidateNotNullOrEmpty] [Parameter(Position = 0)] public PSPropertyExpression[] Property { get; set; } #endregion Common parameters in both sets /// <summary> /// Set to true if Standard Deviation is to be returned. /// </summary> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter StandardDeviation { get { return _measureStandardDeviation; } set { _measureStandardDeviation = value; } } private bool _measureStandardDeviation; /// <summary> /// Set to true is Sum is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Sum { get { return _measureSum; } set { _measureSum = value; } } private bool _measureSum; /// <summary> /// Gets or sets the value indicating if all statistics should be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter AllStats { get { return _allStats; } set { _allStats = value; } } private bool _allStats; /// <summary> /// Set to true is Average is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Average { get { return _measureAverage; } set { _measureAverage = value; } } private bool _measureAverage; /// <summary> /// Set to true is Max is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Maximum { get { return _measureMax; } set { _measureMax = value; } } private bool _measureMax; /// <summary> /// Set to true is Min is to be returned. /// </summary> /// <value></value> [Parameter(ParameterSetName = GenericParameterSet)] public SwitchParameter Minimum { get { return _measureMin; } set { _measureMin = value; } } private bool _measureMin; #region TextMeasure ParameterSet /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Line { get { return _measureLines; } set { _measureLines = value; } } private bool _measureLines = false; /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Word { get { return _measureWords; } set { _measureWords = value; } } private bool _measureWords = false; /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter Character { get { return _measureCharacters; } set { _measureCharacters = value; } } private bool _measureCharacters = false; /// <summary> /// </summary> /// <value></value> [Parameter(ParameterSetName = TextParameterSet)] public SwitchParameter IgnoreWhiteSpace { get { return _ignoreWhiteSpace; } set { _ignoreWhiteSpace = value; } } private bool _ignoreWhiteSpace; #endregion TextMeasure ParameterSet #endregion Command Line Switches /// <summary> /// Which parameter set the Cmdlet is in. /// </summary> private bool IsMeasuringGeneric { get { return string.Equals(ParameterSetName, GenericParameterSet, StringComparison.Ordinal); } } /// <summary> /// Does the begin part of the cmdlet. /// </summary> protected override void BeginProcessing() { // Sets all other generic parameters to true to get all statistics. if (_allStats) { _measureSum = _measureStandardDeviation = _measureAverage = _measureMax = _measureMin = true; } // finally call the base class. base.BeginProcessing(); } /// <summary> /// Collect data about each record that comes in. /// Side effects: Updates totalRecordCount. /// </summary> protected override void ProcessRecord() { if (InputObject == null || InputObject == AutomationNull.Value) { return; } _totalRecordCount++; if (Property == null) AnalyzeValue(null, InputObject.BaseObject); else AnalyzeObjectProperties(InputObject); } /// <summary> /// Analyze an object on a property-by-property basis instead /// of as a simple value. /// Side effects: Updates statistics. /// </summary> /// <param name="inObj">The object to analyze.</param> private void AnalyzeObjectProperties(PSObject inObj) { // Keep track of which properties are counted for an // input object so that repeated properties won't be // counted twice. MeasureObjectDictionary<object> countedProperties = new(); // First iterate over the user-specified list of // properties... foreach (var expression in Property) { List<PSPropertyExpression> resolvedNames = expression.ResolveNames(inObj); if (resolvedNames == null || resolvedNames.Count == 0) { // Insert a blank entry so we can track // property misses in EndProcessing. if (!expression.HasWildCardCharacters) { string propertyName = expression.ToString(); _statistics.EnsureEntry(propertyName); } continue; } // Each property value can potentially refer // to multiple properties via globbing. Iterate over // the actual property names. foreach (PSPropertyExpression resolvedName in resolvedNames) { string propertyName = resolvedName.ToString(); // skip duplicated properties if (countedProperties.ContainsKey(propertyName)) { continue; } List<PSPropertyExpressionResult> tempExprRes = resolvedName.GetValues(inObj); if (tempExprRes == null || tempExprRes.Count == 0) { // Shouldn't happen - would somehow mean // that the property went away between when // we resolved it and when we tried to get its // value. continue; } AnalyzeValue(propertyName, tempExprRes[0].Result); // Remember resolved propertyNames that have been counted countedProperties[propertyName] = null; } } } /// <summary> /// Analyze a value for generic/text statistics. /// Side effects: Updates statistics. May set nonNumericError. /// </summary> /// <param name="propertyName">The property this value corresponds to.</param> /// <param name="objValue">The value to analyze.</param> private void AnalyzeValue(string propertyName, object objValue) { if (propertyName == null) propertyName = thisObject; Statistics stat = _statistics.EnsureEntry(propertyName); // Update common properties. stat.count++; if (_measureCharacters || _measureWords || _measureLines) { string strValue = (objValue == null) ? string.Empty : objValue.ToString(); AnalyzeString(strValue, stat); } if (_measureAverage || _measureSum || _measureStandardDeviation) { double numValue = 0.0; if (!LanguagePrimitives.TryConvertTo(objValue, out numValue)) { _nonNumericError = true; ErrorRecord errorRecord = new( PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue), "NonNumericInputObject", ErrorCategory.InvalidType, objValue); WriteError(errorRecord); return; } AnalyzeNumber(numValue, stat); } // Measure-Object -MAX -MIN should work with ANYTHING that supports CompareTo if (_measureMin) { stat.min = Compare(objValue, stat.min, true); } if (_measureMax) { stat.max = Compare(objValue, stat.max, false); } } /// <summary> /// Compare is a helper function used to find the min/max between the supplied input values. /// </summary> /// <param name="objValue"> /// Current input value. /// </param> /// <param name="statMinOrMaxValue"> /// Current minimum or maximum value in the statistics. /// </param> /// <param name="isMin"> /// Indicates if minimum or maximum value has to be found. /// If true is passed in then the minimum of the two values would be returned. /// If false is passed in then maximum of the two values will be returned.</param> /// <returns></returns> private static object Compare(object objValue, object statMinOrMaxValue, bool isMin) { object currentValue = objValue; object statValue = statMinOrMaxValue; double temp; currentValue = ((objValue != null) && LanguagePrimitives.TryConvertTo<double>(objValue, out temp)) ? temp : currentValue; statValue = ((statValue != null) && LanguagePrimitives.TryConvertTo<double>(statValue, out temp)) ? temp : statValue; if (currentValue != null && statValue != null && !currentValue.GetType().Equals(statValue.GetType())) { currentValue = PSObject.AsPSObject(currentValue).ToString(); statValue = PSObject.AsPSObject(statValue).ToString(); } if (statValue == null) { return objValue; } int comparisonResult = LanguagePrimitives.Compare(statValue, currentValue, ignoreCase: false, CultureInfo.CurrentCulture); return (isMin ? comparisonResult : -comparisonResult) > 0 ? objValue : statMinOrMaxValue; } /// <summary> /// Class contains util static functions. /// </summary> private static class TextCountUtilities { /// <summary> /// Count chars in inStr. /// </summary> /// <param name="inStr">String whose chars are counted.</param> /// <param name="ignoreWhiteSpace">True to discount white space.</param> /// <returns>Number of chars in inStr.</returns> internal static int CountChar(string inStr, bool ignoreWhiteSpace) { if (string.IsNullOrEmpty(inStr)) { return 0; } if (!ignoreWhiteSpace) { return inStr.Length; } int len = 0; foreach (char c in inStr) { if (!char.IsWhiteSpace(c)) { len++; } } return len; } /// <summary> /// Count words in inStr. /// </summary> /// <param name="inStr">String whose words are counted.</param> /// <returns>Number of words in inStr.</returns> internal static int CountWord(string inStr) { if (string.IsNullOrEmpty(inStr)) { return 0; } int wordCount = 0; bool wasAWhiteSpace = true; foreach (char c in inStr) { if (char.IsWhiteSpace(c)) { wasAWhiteSpace = true; } else { if (wasAWhiteSpace) { wordCount++; } wasAWhiteSpace = false; } } return wordCount; } /// <summary> /// Count lines in inStr. /// </summary> /// <param name="inStr">String whose lines are counted.</param> /// <returns>Number of lines in inStr.</returns> internal static int CountLine(string inStr) { if (string.IsNullOrEmpty(inStr)) { return 0; } int numberOfLines = 0; foreach (char c in inStr) { if (c == '\n') { numberOfLines++; } } // 'abc\nd' has two lines // but 'abc\n' has one line if (inStr[inStr.Length - 1] != '\n') { numberOfLines++; } return numberOfLines; } } /// <summary> /// Update text statistics. /// </summary> /// <param name="strValue">The text to analyze.</param> /// <param name="stat">The Statistics object to update.</param> private void AnalyzeString(string strValue, Statistics stat) { if (_measureCharacters) stat.characters += TextCountUtilities.CountChar(strValue, _ignoreWhiteSpace); if (_measureWords) stat.words += TextCountUtilities.CountWord(strValue); if (_measureLines) stat.lines += TextCountUtilities.CountLine(strValue); } /// <summary> /// Update number statistics. /// </summary> /// <param name="numValue">The number to analyze.</param> /// <param name="stat">The Statistics object to update.</param> private void AnalyzeNumber(double numValue, Statistics stat) { if (_measureSum || _measureAverage || _measureStandardDeviation) { stat.sumPrevious = stat.sum; stat.sum += numValue; } if (_measureStandardDeviation && stat.count > 1) { // Based off of iterative method of calculating variance on // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm double avgPrevious = stat.sumPrevious / (stat.count - 1); stat.variance *= (stat.count - 2.0) / (stat.count - 1); stat.variance += (numValue - avgPrevious) * (numValue - avgPrevious) / stat.count; } } /// <summary> /// WriteError when a property is not found. /// </summary> /// <param name="propertyName">The missing property.</param> /// <param name="errorId">The error ID to write.</param> private void WritePropertyNotFoundError(string propertyName, string errorId) { Diagnostics.Assert(Property != null, "no property and no InputObject should have been addressed"); ErrorRecord errorRecord = new( PSTraceSource.NewArgumentException("Property"), errorId, ErrorCategory.InvalidArgument, null); errorRecord.ErrorDetails = new ErrorDetails( this, "MeasureObjectStrings", "PropertyNotFound", propertyName); WriteError(errorRecord); } /// <summary> /// Output collected statistics. /// Side effects: Updates statistics. Writes objects to stream. /// </summary> protected override void EndProcessing() { // Fix for 917114: If Property is not set, // and we aren't passed any records at all, // output 0s to emulate wc behavior. if (_totalRecordCount == 0 && Property == null) { _statistics.EnsureEntry(thisObject); } foreach (string propertyName in _statistics.Keys) { Statistics stat = _statistics[propertyName]; if (stat.count == 0 && Property != null) { // Why are there two different ids for this error? string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; WritePropertyNotFoundError(propertyName, errorId); continue; } MeasureInfo mi = null; if (IsMeasuringGeneric) { double temp; if ((stat.min == null || LanguagePrimitives.TryConvertTo<double>(stat.min, out temp)) && (stat.max == null || LanguagePrimitives.TryConvertTo<double>(stat.max, out temp))) { mi = CreateGenericMeasureInfo(stat, true); } else { mi = CreateGenericMeasureInfo(stat, false); } } else mi = CreateTextMeasureInfo(stat); // Set common properties. if (Property != null) mi.Property = propertyName; WriteObject(mi); } } /// <summary> /// Create a MeasureInfo object for generic stats. /// </summary> /// <param name="stat">The statistics to use.</param> /// <param name="shouldUseGenericMeasureInfo"></param> /// <returns>A new GenericMeasureInfo object.</returns> private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGenericMeasureInfo) { double? sum = null; double? average = null; double? StandardDeviation = null; object max = null; object min = null; if (!_nonNumericError) { if (_measureSum) sum = stat.sum; if (_measureAverage && stat.count > 0) average = stat.sum / stat.count; if (_measureStandardDeviation) { StandardDeviation = Math.Sqrt(stat.variance); } } if (_measureMax) { if (shouldUseGenericMeasureInfo && (stat.max != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.max, out temp); max = temp; } else { max = stat.max; } } if (_measureMin) { if (shouldUseGenericMeasureInfo && (stat.min != null)) { double temp; LanguagePrimitives.TryConvertTo<double>(stat.min, out temp); min = temp; } else { min = stat.min; } } if (shouldUseGenericMeasureInfo) { GenericMeasureInfo gmi = new(); gmi.Count = stat.count; gmi.Sum = sum; gmi.Average = average; gmi.StandardDeviation = StandardDeviation; if (max != null) { gmi.Maximum = (double)max; } if (min != null) { gmi.Minimum = (double)min; } return gmi; } else { GenericObjectMeasureInfo gomi = new(); gomi.Count = stat.count; gomi.Sum = sum; gomi.Average = average; gomi.Maximum = max; gomi.Minimum = min; return gomi; } } /// <summary> /// Create a MeasureInfo object for text stats. /// </summary> /// <param name="stat">The statistics to use.</param> /// <returns>A new TextMeasureInfo object.</returns> private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) { TextMeasureInfo tmi = new(); if (_measureCharacters) tmi.Characters = stat.characters; if (_measureWords) tmi.Words = stat.words; if (_measureLines) tmi.Lines = stat.lines; return tmi; } /// <summary> /// The observed statistics keyed by property name. /// If Property is not set, then the key used will be the value of thisObject. /// </summary> private readonly MeasureObjectDictionary<Statistics> _statistics = new(); /// <summary> /// Whether or not a numeric conversion error occurred. /// If true, then average/sum/standard deviation will not be output. /// </summary> private bool _nonNumericError = false; /// <summary> /// The total number of records encountered. /// </summary> private int _totalRecordCount = 0; /// <summary> /// Parameter set name for measuring objects. /// </summary> private const string GenericParameterSet = "GenericMeasure"; /// <summary> /// Parameter set name for measuring text. /// </summary> private const string TextParameterSet = "TextMeasure"; /// <summary> /// Key that statistics are stored under when Property is not set. /// </summary> private const string thisObject = "$_"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public abstract class ChannelFactoryBase : ChannelManagerBase, IChannelFactory, IAsyncChannelFactory { private TimeSpan _closeTimeout = ServiceDefaults.CloseTimeout; private TimeSpan _openTimeout = ServiceDefaults.OpenTimeout; private TimeSpan _receiveTimeout = ServiceDefaults.ReceiveTimeout; private TimeSpan _sendTimeout = ServiceDefaults.SendTimeout; protected ChannelFactoryBase() { } protected ChannelFactoryBase(IDefaultCommunicationTimeouts timeouts) { InitializeTimeouts(timeouts); } protected override TimeSpan DefaultCloseTimeout { get { return _closeTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return _openTimeout; } } protected override TimeSpan DefaultReceiveTimeout { get { return _receiveTimeout; } } protected override TimeSpan DefaultSendTimeout { get { return _sendTimeout; } } public virtual T GetProperty<T>() where T : class { if (typeof(T) == typeof(IChannelFactory)) { return (T)(object)this; } return default(T); } protected override void OnAbort() { } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected internal override Task OnCloseAsync(TimeSpan timeout) { return TaskHelpers.CompletedTask(); } protected override void OnClose(TimeSpan timeout) { } protected override void OnEndClose(IAsyncResult result) { CompletedAsyncResult.End(result); } private void InitializeTimeouts(IDefaultCommunicationTimeouts timeouts) { if (timeouts != null) { _closeTimeout = timeouts.CloseTimeout; _openTimeout = timeouts.OpenTimeout; _receiveTimeout = timeouts.ReceiveTimeout; _sendTimeout = timeouts.SendTimeout; } } } public abstract class ChannelFactoryBase<TChannel> : ChannelFactoryBase, IChannelFactory<TChannel> { private CommunicationObjectManager<IChannel> _channels; protected ChannelFactoryBase() : this(null) { } protected ChannelFactoryBase(IDefaultCommunicationTimeouts timeouts) : base(timeouts) { _channels = new CommunicationObjectManager<IChannel>(ThisLock); } public TChannel CreateChannel(EndpointAddress address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(address)); } return InternalCreateChannel(address, address.Uri); } public TChannel CreateChannel(EndpointAddress address, Uri via) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(address)); } if (via == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(via)); } return InternalCreateChannel(address, via); } private TChannel InternalCreateChannel(EndpointAddress address, Uri via) { ValidateCreateChannel(); TChannel channel = OnCreateChannel(address, via); bool success = false; try { _channels.Add((IChannel)(object)channel); success = true; } finally { if (!success) { ((IChannel)(object)channel).Abort(); } } return channel; } protected abstract TChannel OnCreateChannel(EndpointAddress address, Uri via); protected void ValidateCreateChannel() { ThrowIfDisposed(); if (State != CommunicationState.Opened) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ChannelFactoryCannotBeUsedToCreateChannels, GetType().ToString()))); } } protected override void OnAbort() { IChannel[] currentChannels = _channels.ToArray(); foreach (IChannel channel in currentChannels) { channel.Abort(); } _channels.Abort(); } protected override void OnClose(TimeSpan timeout) { IChannel[] currentChannels = _channels.ToArray(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); foreach (IChannel channel in currentChannels) { channel.Close(timeoutHelper.RemainingTime()); } _channels.Close(timeoutHelper.RemainingTime()); } protected internal override Task OnCloseAsync(TimeSpan timeout) { return OnCloseAsyncInternal(timeout); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedCloseAsyncResult(timeout, callback, state, _channels.BeginClose, _channels.EndClose, _channels.ToArray()); } protected override void OnEndClose(IAsyncResult result) { ChainedCloseAsyncResult.End(result); } private async Task OnCloseAsyncInternal(TimeSpan timeout) { IChannel[] currentChannels = _channels.ToArray(); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); foreach (IChannel channel in currentChannels) { await CloseOtherAsync(channel, timeoutHelper.RemainingTime()); } // CommunicationObjectManager (_channels) is not a CommunicationObject, // so just choose existing synchronous or asynchronous close if (_isSynchronousClose) { await TaskHelpers.CallActionAsync(_channels.Close, timeoutHelper.RemainingTime()); } else { await Task.Factory.FromAsync(_channels.BeginClose, _channels.EndClose, timeoutHelper.RemainingTime(), TaskCreationOptions.None); } } } }
// <copyright file="Callbacks.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames.Native.PInvoke { using System; using System.Collections; using System.Runtime.InteropServices; using GooglePlayGames.Native.Cwrapper; using GooglePlayGames.OurUtils; static class Callbacks { internal static readonly Action<CommonErrorStatus.UIStatus> NoopUICallback = status => { Logger.d("Received UI callback: " + status); }; internal delegate void ShowUICallbackInternal(CommonErrorStatus.UIStatus status,IntPtr data); internal static IntPtr ToIntPtr<T>(Action<T> callback, Func<IntPtr, T> conversionFunction) where T : BaseReferenceHolder { Action<IntPtr> pointerReceiver = result => { using (T converted = conversionFunction(result)) { if (callback != null) { callback(converted); } } }; return ToIntPtr(pointerReceiver); } internal static IntPtr ToIntPtr<T, P>(Action<T, P> callback, Func<IntPtr, P> conversionFunction) where P : BaseReferenceHolder { Action<T, IntPtr> pointerReceiver = (param1, param2) => { using (P converted = conversionFunction(param2)) { if (callback != null) { callback(param1, converted); } } }; return ToIntPtr(pointerReceiver); } internal static IntPtr ToIntPtr(Delegate callback) { if (callback == null) { return IntPtr.Zero; } // Once the callback is passed off to native, we don't retain a reference to it - which // means it's eligible for garbage collecting or being moved around by the runtime. If // the garbage collector runs before the native code invokes the callback, chaos will // ensue. // // To handle this, we create a normal GCHandle. The GCHandle will be freed when the callback returns the and // handle is converted back to callback via IntPtrToCallback. var handle = GCHandle.Alloc(callback); return GCHandle.ToIntPtr(handle); } internal static T IntPtrToTempCallback<T>(IntPtr handle) where T : class { return IntPtrToCallback<T>(handle, true); } private static T IntPtrToCallback<T>(IntPtr handle, bool unpinHandle) where T : class { if (PInvokeUtilities.IsNull(handle)) { return null; } var gcHandle = GCHandle.FromIntPtr(handle); try { return (T)gcHandle.Target; } catch (System.InvalidCastException e) { Logger.e("GC Handle pointed to unexpected type: " + gcHandle.Target.ToString() + ". Expected " + typeof(T)); throw e; } finally { if (unpinHandle) { gcHandle.Free(); } } } // TODO(hsakai): Better way of handling this. internal static T IntPtrToPermanentCallback<T>(IntPtr handle) where T : class { return IntPtrToCallback<T>(handle, false); } [AOT.MonoPInvokeCallback(typeof(ShowUICallbackInternal))] internal static void InternalShowUICallback(CommonErrorStatus.UIStatus status, IntPtr data) { Logger.d("Showing UI Internal callback: " + status); var callback = IntPtrToTempCallback<Action<CommonErrorStatus.UIStatus>>(data); try { callback(status); } catch (Exception e) { Logger.e("Error encountered executing InternalShowAllUICallback. " + "Smothering to avoid passing exception into Native: " + e); } } internal enum Type { Permanent, Temporary} ; internal static void PerformInternalCallback(string callbackName, Type callbackType, IntPtr response, IntPtr userData) { Logger.d("Entering internal callback for " + callbackName); Action<IntPtr> callback = callbackType == Type.Permanent ? IntPtrToPermanentCallback<Action<IntPtr>>(userData) : IntPtrToTempCallback<Action<IntPtr>>(userData); if (callback == null) { return; } try { callback(response); } catch (Exception e) { Logger.e("Error encountered executing " + callbackName + ". " + "Smothering to avoid passing exception into Native: " + e); } } internal static void PerformInternalCallback<T>(string callbackName, Type callbackType, T param1, IntPtr param2, IntPtr userData) { Logger.d("Entering internal callback for " + callbackName); Action<T, IntPtr> callback = null; try { callback = callbackType == Type.Permanent ? IntPtrToPermanentCallback<Action<T, IntPtr>>(userData) : IntPtrToTempCallback<Action<T, IntPtr>>(userData); } catch (Exception e) { Logger.e("Error encountered converting " + callbackName + ". " + "Smothering to avoid passing exception into Native: " + e); return; } Logger.d("Internal Callback converted to action"); if (callback == null) { return; } try { callback(param1, param2); } catch (Exception e) { Logger.e("Error encountered executing " + callbackName + ". " + "Smothering to avoid passing exception into Native: " + e); } } internal static Action<T> AsOnGameThreadCallback<T>(Action<T> toInvokeOnGameThread) { return result => { if (toInvokeOnGameThread == null) { return; } PlayGamesHelperObject.RunOnGameThread(() => toInvokeOnGameThread(result)); }; } internal static Action<T1, T2> AsOnGameThreadCallback<T1, T2>( Action<T1, T2> toInvokeOnGameThread) { return (result1, result2) => { if (toInvokeOnGameThread == null) { return; } PlayGamesHelperObject.RunOnGameThread(() => toInvokeOnGameThread(result1, result2)); }; } internal static void AsCoroutine(IEnumerator routine) { PlayGamesHelperObject.RunCoroutine(routine); } internal static byte[] IntPtrAndSizeToByteArray(IntPtr data, UIntPtr dataLength) { if (dataLength.ToUInt64() == 0) { return null; } byte[] convertedData = new byte[dataLength.ToUInt32()]; Marshal.Copy(data, convertedData, 0, (int)dataLength.ToUInt32()); return convertedData; } } } #endif
namespace Orleans.CodeGeneration { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Orleans.CodeGenerator; using Orleans.Runtime; using Orleans.Serialization; /// <summary> /// Generates factory, grain reference, and invoker classes for grain interfaces. /// Generates state object classes for grain implementation classes. /// </summary> public class GrainClientGenerator : MarshalByRefObject { private static readonly RoslynCodeGenerator CodeGenerator = new RoslynCodeGenerator(); [Serializable] internal class CodeGenOptions { public FileInfo InputLib; public bool InvalidLanguage; public List<string> ReferencedAssemblies = new List<string>(); public string CodeGenFile; public string SourcesDir; } [Serializable] internal class GrainClientGeneratorFlags { internal static bool Verbose = false; internal static bool FailOnPathNotFound = false; } private static readonly int[] suppressCompilerWarnings = { 162, // CS0162 - Unreachable code detected. 219, // CS0219 - The variable 'V' is assigned but its value is never used. 414, // CS0414 - The private field 'F' is assigned but its value is never used. 649, // CS0649 - Field 'F' is never assigned to, and will always have its default value. 693, // CS0693 - Type parameter 'type parameter' has the same name as the type parameter from outer type 'T' 1591, // CS1591 - Missing XML comment for publicly visible type or member 'Type_or_Member' 1998 // CS1998 - This async method lacks 'await' operators and will run synchronously }; /// <summary> /// Generates one GrainReference class for each Grain Type in the inputLib file /// and output one GrainClient.dll under outputLib directory /// </summary> private static bool CreateGrainClientAssembly(CodeGenOptions options) { AppDomain appDomain = null; try { var assembly = typeof (GrainClientGenerator).GetTypeInfo().Assembly; // Create AppDomain. var appDomainSetup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assembly.Location), DisallowBindingRedirects = false, ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile }; appDomain = AppDomain.CreateDomain("Orleans-CodeGen Domain", null, appDomainSetup); // Set up assembly resolver var refResolver = new ReferenceResolver(options.ReferencedAssemblies); appDomain.AssemblyResolve += refResolver.ResolveAssembly; // Create an instance var generator = (GrainClientGenerator) appDomain.CreateInstanceAndUnwrap( assembly.FullName, typeof(GrainClientGenerator).FullName); // Call a method return generator.CreateGrainClient(options); } finally { if (appDomain != null) AppDomain.Unload(appDomain); // Unload the AppDomain } } /// <summary> /// Generate one GrainReference class for each Grain Type in the inputLib file /// and output one GrainClient.dll under outputLib directory /// </summary> private bool CreateGrainClient(CodeGenOptions options) { // Load input assembly // special case Orleans.dll because there is a circular dependency. var assemblyName = AssemblyName.GetAssemblyName(options.InputLib.FullName); var grainAssembly = (Path.GetFileName(options.InputLib.FullName) != "Orleans.dll") ? Assembly.LoadFrom(options.InputLib.FullName) : Assembly.Load(assemblyName); // Create sources directory if (!Directory.Exists(options.SourcesDir)) Directory.CreateDirectory(options.SourcesDir); // Generate source var outputFileName = Path.Combine( options.SourcesDir, Path.GetFileNameWithoutExtension(options.InputLib.Name) + ".codegen.cs"); ConsoleText.WriteStatus("Orleans-CodeGen - Generating file {0}", outputFileName); SerializationManager.RegisterBuiltInSerializers(); using (var sourceWriter = new StreamWriter(outputFileName)) { sourceWriter.WriteLine("#if !EXCLUDE_CODEGEN"); DisableWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine(CodeGenerator.GenerateSourceForAssembly(grainAssembly)); RestoreWarnings(sourceWriter, suppressCompilerWarnings); sourceWriter.WriteLine("#endif"); } ConsoleText.WriteStatus("Orleans-CodeGen - Generated file written {0}", outputFileName); #if !NETSTANDARD // Copy intermediate file to permanent location, if newer. ConsoleText.WriteStatus( "Orleans-CodeGen - Updating IntelliSense file {0} -> {1}", outputFileName, options.CodeGenFile); UpdateIntellisenseFile(options.CodeGenFile, outputFileName); #endif return true; } private static void DisableWarnings(TextWriter sourceWriter, IEnumerable<int> warnings) { foreach (var warningNum in warnings) sourceWriter.WriteLine("#pragma warning disable {0}", warningNum); } private static void RestoreWarnings(TextWriter sourceWriter, IEnumerable<int> warnings) { foreach (var warningNum in warnings) sourceWriter.WriteLine("#pragma warning restore {0}", warningNum); } /// <summary> /// Updates the source file in the project if required. /// </summary> /// <param name="sourceFileToBeUpdated">Path to file to be updated.</param> /// <param name="outputFileGenerated">File that was updated.</param> private static void UpdateIntellisenseFile(string sourceFileToBeUpdated, string outputFileGenerated) { if (string.IsNullOrEmpty(sourceFileToBeUpdated)) throw new ArgumentNullException("sourceFileToBeUpdated", "Output file must not be blank"); if (string.IsNullOrEmpty(outputFileGenerated)) throw new ArgumentNullException("outputFileGenerated", "Generated file must already exist"); var sourceToUpdateFileInfo = new FileInfo(sourceFileToBeUpdated); var generatedFileInfo = new FileInfo(outputFileGenerated); if (!generatedFileInfo.Exists) throw new Exception("Generated file must already exist"); if (File.Exists(sourceFileToBeUpdated)) { bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo); if (filesMatch) { ConsoleText.WriteStatus( "Orleans-CodeGen - No changes to the generated file {0}", sourceFileToBeUpdated); return; } // we come here only if files don't match sourceToUpdateFileInfo.Attributes = sourceToUpdateFileInfo.Attributes & (~FileAttributes.ReadOnly); // remove read only attribute ConsoleText.WriteStatus( "Orleans-CodeGen - copying file {0} to {1}", outputFileGenerated, sourceFileToBeUpdated); File.Copy(outputFileGenerated, sourceFileToBeUpdated, true); filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo); ConsoleText.WriteStatus( "Orleans-CodeGen - After copying file {0} to {1} Matchs={2}", outputFileGenerated, sourceFileToBeUpdated, filesMatch); } else { var dir = Path.GetDirectoryName(sourceFileToBeUpdated); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); ConsoleText.WriteStatus( "Orleans-CodeGen - copying file {0} to {1}", outputFileGenerated, sourceFileToBeUpdated); File.Copy(outputFileGenerated, sourceFileToBeUpdated, true); bool filesMatch = CheckFilesMatch(generatedFileInfo, sourceToUpdateFileInfo); ConsoleText.WriteStatus( "Orleans-CodeGen - After copying file {0} to {1} Matchs={2}", outputFileGenerated, sourceFileToBeUpdated, filesMatch); } } private static bool CheckFilesMatch(FileInfo file1, FileInfo file2) { bool isMatching; long len1 = -1; long len2 = -1; if (file1.Exists) len1 = file1.Length; if (file2.Exists) len2 = file2.Length; if (len1 <= 0 || len2 <= 0) { isMatching = false; } else if (len1 != len2) { isMatching = false; } else { byte[] arr1 = File.ReadAllBytes(file1.FullName); byte[] arr2 = File.ReadAllBytes(file2.FullName); isMatching = true; // initially assume files match for (int i = 0; i < arr1.Length; i++) { if (arr1[i] != arr2[i]) { isMatching = false; // unless we know they don't match break; } } } if (GrainClientGeneratorFlags.Verbose) ConsoleText.WriteStatus( "Orleans-CodeGen - CheckFilesMatch = {0} File1 = {1} Len = {2} File2 = {3} Len = {4}", isMatching, file1, len1, file2, len2); return isMatching; } private static readonly string CodeGenFileRelativePathCSharp = Path.Combine("Properties", "orleans.codegen.cs"); public int RunMain(string[] args) { ConsoleText.WriteStatus("Orleans-CodeGen - command-line = {0}", Environment.CommandLine); if (args.Length < 1) { Console.WriteLine( "Usage: ClientGenerator.exe <grain interface dll path> [<client dll path>] [<key file>] [<referenced assemblies>]"); Console.WriteLine( " ClientGenerator.exe /server <grain dll path> [<factory dll path>] [<key file>] [<referenced assemblies>]"); return 1; } try { var options = new CodeGenOptions(); // STEP 1 : Parse parameters if (args.Length == 1 && args[0].StartsWith("@")) { // Read command line args from file string arg = args[0]; string argsFile = arg.Trim('"').Substring(1).Trim('"'); Console.WriteLine("Orleans-CodeGen - Reading code-gen params from file={0}", argsFile); AssertWellFormed(argsFile, true); args = File.ReadAllLines(argsFile); } int i = 1; foreach (string a in args) { string arg = a.Trim('"').Trim().Trim('"'); if (GrainClientGeneratorFlags.Verbose) Console.WriteLine("Orleans-CodeGen - arg #{0}={1}", i++, arg); if (string.IsNullOrEmpty(arg) || string.IsNullOrWhiteSpace(arg)) continue; if (arg.StartsWith("/")) { if (arg.StartsWith("/reference:") || arg.StartsWith("/r:")) { // list of references passed from from project file. separator =';' string refstr = arg.Substring(arg.IndexOf(':') + 1); string[] references = refstr.Split(';'); foreach (string rp in references) { AssertWellFormed(rp, true); options.ReferencedAssemblies.Add(rp); } } else if (arg.StartsWith("/in:")) { var infile = arg.Substring(arg.IndexOf(':') + 1); AssertWellFormed(infile); options.InputLib = new FileInfo(infile); } else if (arg.StartsWith("/bootstrap") || arg.StartsWith("/boot")) { // special case for building circular dependecy in preprocessing: // Do not build the input assembly, assume that some other build step options.CodeGenFile = Path.GetFullPath(CodeGenFileRelativePathCSharp); if (GrainClientGeneratorFlags.Verbose) { Console.WriteLine( "Orleans-CodeGen - Set CodeGenFile={0} from bootstrap", options.CodeGenFile); } } else if (arg.StartsWith("/sources:") || arg.StartsWith("/src:")) { var sourcesStr = arg.Substring(arg.IndexOf(':') + 1); string[] sources = sourcesStr.Split(';'); foreach (var source in sources) { HandleSourceFile(source, options); } } } else { HandleSourceFile(arg, options); } } if (options.InvalidLanguage) { ConsoleText.WriteLine( "ERROR: Compile-time code generation is supported for C# only. " + "Remove code generation from your project in order to use run-time code generation."); return 2; } // STEP 2 : Validate and calculate unspecified parameters if (options.InputLib == null) { Console.WriteLine("ERROR: Orleans-CodeGen - no input file specified."); return 2; } #if !NETSTANDARD if (string.IsNullOrEmpty(options.CodeGenFile)) { Console.WriteLine( "ERROR: No codegen file. Add a file '{0}' to your project", Path.Combine("Properties", "orleans.codegen.cs")); return 2; } #endif options.SourcesDir = Path.Combine(options.InputLib.DirectoryName, "Generated"); // STEP 3 : Dump useful info for debugging Console.WriteLine( "Orleans-CodeGen - Options " + Environment.NewLine + "\tInputLib={0} " + Environment.NewLine + "\tCodeGenFile={1}", options.InputLib.FullName, options.CodeGenFile); if (options.ReferencedAssemblies != null) { Console.WriteLine("Orleans-CodeGen - Using referenced libraries:"); foreach (string assembly in options.ReferencedAssemblies) Console.WriteLine("\t{0} => {1}", Path.GetFileName(assembly), assembly); } // STEP 5 : Finally call code generation if (!CreateGrainClientAssembly(options)) return -1; // DONE! return 0; } catch (Exception ex) { Console.WriteLine("-- Code-gen FAILED -- \n{0}", LogFormatter.PrintException(ex)); return 3; } } private static void HandleSourceFile(string arg, CodeGenOptions options) { AssertWellFormed(arg, true); options.InvalidLanguage |= arg.EndsWith(".vb", StringComparison.InvariantCultureIgnoreCase) | arg.EndsWith(".fs", StringComparison.InvariantCultureIgnoreCase); if (arg.EndsWith(CodeGenFileRelativePathCSharp, StringComparison.InvariantCultureIgnoreCase)) { options.CodeGenFile = Path.GetFullPath(arg); if (GrainClientGeneratorFlags.Verbose) { Console.WriteLine("Orleans-CodeGen - Set CodeGenFile={0} from {1}", options.CodeGenFile, arg); } } } private static void AssertWellFormed(string path, bool mustExist = false) { CheckPathNotStartWith(path, ":"); CheckPathNotStartWith(path, "\""); CheckPathNotEndsWith(path, "\""); CheckPathNotEndsWith(path, "/"); CheckPath(path, p => !string.IsNullOrWhiteSpace(p), "Empty path string"); bool exists = FileExists(path); if (mustExist && GrainClientGeneratorFlags.FailOnPathNotFound) CheckPath(path, p => exists, "Path not exists"); } private static bool FileExists(string path) { bool exists = File.Exists(path) || Directory.Exists(path); if (!exists) Console.WriteLine("MISSING: Path not exists: {0}", path); return exists; } private static void CheckPathNotStartWith(string path, string str) { CheckPath(path, p => !p.StartsWith(str), string.Format("Cannot start with '{0}'", str)); } private static void CheckPathNotEndsWith(string path, string str) { CheckPath( path, p => !p.EndsWith(str, StringComparison.InvariantCultureIgnoreCase), string.Format("Cannot end with '{0}'", str)); } private static void CheckPath(string path, Func<string, bool> condition, string what) { if (condition(path)) return; var errMsg = string.Format("Bad path {0} Reason = {1}", path, what); Console.WriteLine("CODEGEN-ERROR: " + errMsg); throw new ArgumentException("FAILED: " + errMsg); } /// <summary> /// Simple class that loads the reference assemblies upon the AppDomain.AssemblyResolve /// </summary> [Serializable] internal class ReferenceResolver { /// <summary> /// Dictionary : Assembly file name without extension -> full path /// </summary> private Dictionary<string, string> referenceAssemblyPaths = new Dictionary<string, string>(); /// <summary> /// Needs to be public so can be serialized accross the the app domain. /// </summary> public Dictionary<string, string> ReferenceAssemblyPaths { get { return referenceAssemblyPaths; } set { referenceAssemblyPaths = value; } } /// <summary> /// Inits the resolver /// </summary> /// <param name="referencedAssemblies">Full paths of referenced assemblies</param> public ReferenceResolver(IEnumerable<string> referencedAssemblies) { if (null == referencedAssemblies) return; foreach (var assemblyPath in referencedAssemblies) referenceAssemblyPaths[Path.GetFileNameWithoutExtension(assemblyPath)] = assemblyPath; } /// <summary> /// Handles System.AppDomain.AssemblyResolve event of an System.AppDomain /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="args">The event data.</param> /// <returns>The assembly that resolves the type, assembly, or resource; /// or null if theassembly cannot be resolved. /// </returns> public Assembly ResolveAssembly(object sender, ResolveEventArgs args) { Assembly assembly = null; string path; var asmName = new AssemblyName(args.Name); if (referenceAssemblyPaths.TryGetValue(asmName.Name, out path)) assembly = Assembly.LoadFrom(path); else ConsoleText.WriteStatus("Could not resolve {0}:", asmName.Name); return assembly; } } } }
namespace Senzible.SDL { public enum SDL_Scancode { SDL_SCANCODE_UNKNOWN = 0, SDL_SCANCODE_A = 4, SDL_SCANCODE_B = 5, SDL_SCANCODE_C = 6, SDL_SCANCODE_D = 7, SDL_SCANCODE_E = 8, SDL_SCANCODE_F = 9, SDL_SCANCODE_G = 10, SDL_SCANCODE_H = 11, SDL_SCANCODE_I = 12, SDL_SCANCODE_J = 13, SDL_SCANCODE_K = 14, SDL_SCANCODE_L = 15, SDL_SCANCODE_M = 16, SDL_SCANCODE_N = 17, SDL_SCANCODE_O = 18, SDL_SCANCODE_P = 19, SDL_SCANCODE_Q = 20, SDL_SCANCODE_R = 21, SDL_SCANCODE_S = 22, SDL_SCANCODE_T = 23, SDL_SCANCODE_U = 24, SDL_SCANCODE_V = 25, SDL_SCANCODE_W = 26, SDL_SCANCODE_X = 27, SDL_SCANCODE_Y = 28, SDL_SCANCODE_Z = 29, SDL_SCANCODE_1 = 30, SDL_SCANCODE_2 = 31, SDL_SCANCODE_3 = 32, SDL_SCANCODE_4 = 33, SDL_SCANCODE_5 = 34, SDL_SCANCODE_6 = 35, SDL_SCANCODE_7 = 36, SDL_SCANCODE_8 = 37, SDL_SCANCODE_9 = 38, SDL_SCANCODE_0 = 39, SDL_SCANCODE_RETURN = 40, SDL_SCANCODE_ESCAPE = 41, SDL_SCANCODE_BACKSPACE = 42, SDL_SCANCODE_TAB = 43, SDL_SCANCODE_SPACE = 44, SDL_SCANCODE_MINUS = 45, SDL_SCANCODE_EQUALS = 46, SDL_SCANCODE_LEFTBRACKET = 47, SDL_SCANCODE_RIGHTBRACKET = 48, SDL_SCANCODE_BACKSLASH = 49, SDL_SCANCODE_NONUSHASH = 50, SDL_SCANCODE_SEMICOLON = 51, SDL_SCANCODE_APOSTROPHE = 52, SDL_SCANCODE_GRAVE = 53, SDL_SCANCODE_COMMA = 54, SDL_SCANCODE_PERIOD = 55, SDL_SCANCODE_SLASH = 56, SDL_SCANCODE_CAPSLOCK = 57, SDL_SCANCODE_F1 = 58, SDL_SCANCODE_F2 = 59, SDL_SCANCODE_F3 = 60, SDL_SCANCODE_F4 = 61, SDL_SCANCODE_F5 = 62, SDL_SCANCODE_F6 = 63, SDL_SCANCODE_F7 = 64, SDL_SCANCODE_F8 = 65, SDL_SCANCODE_F9 = 66, SDL_SCANCODE_F10 = 67, SDL_SCANCODE_F11 = 68, SDL_SCANCODE_F12 = 69, SDL_SCANCODE_PRINTSCREEN = 70, SDL_SCANCODE_SCROLLLOCK = 71, SDL_SCANCODE_PAUSE = 72, SDL_SCANCODE_INSERT = 73, SDL_SCANCODE_HOME = 74, SDL_SCANCODE_PAGEUP = 75, SDL_SCANCODE_DELETE = 76, SDL_SCANCODE_END = 77, SDL_SCANCODE_PAGEDOWN = 78, SDL_SCANCODE_RIGHT = 79, SDL_SCANCODE_LEFT = 80, SDL_SCANCODE_DOWN = 81, SDL_SCANCODE_UP = 82, SDL_SCANCODE_NUMLOCKCLEAR = 83, SDL_SCANCODE_KP_DIVIDE = 84, SDL_SCANCODE_KP_MULTIPLY = 85, SDL_SCANCODE_KP_MINUS = 86, SDL_SCANCODE_KP_PLUS = 87, SDL_SCANCODE_KP_ENTER = 88, SDL_SCANCODE_KP_1 = 89, SDL_SCANCODE_KP_2 = 90, SDL_SCANCODE_KP_3 = 91, SDL_SCANCODE_KP_4 = 92, SDL_SCANCODE_KP_5 = 93, SDL_SCANCODE_KP_6 = 94, SDL_SCANCODE_KP_7 = 95, SDL_SCANCODE_KP_8 = 96, SDL_SCANCODE_KP_9 = 97, SDL_SCANCODE_KP_0 = 98, SDL_SCANCODE_KP_PERIOD = 99, SDL_SCANCODE_NONUSBACKSLASH = 100, SDL_SCANCODE_APPLICATION = 101, SDL_SCANCODE_POWER = 102, SDL_SCANCODE_KP_EQUALS = 103, SDL_SCANCODE_F13 = 104, SDL_SCANCODE_F14 = 105, SDL_SCANCODE_F15 = 106, SDL_SCANCODE_F16 = 107, SDL_SCANCODE_F17 = 108, SDL_SCANCODE_F18 = 109, SDL_SCANCODE_F19 = 110, SDL_SCANCODE_F20 = 111, SDL_SCANCODE_F21 = 112, SDL_SCANCODE_F22 = 113, SDL_SCANCODE_F23 = 114, SDL_SCANCODE_F24 = 115, SDL_SCANCODE_EXECUTE = 116, SDL_SCANCODE_HELP = 117, SDL_SCANCODE_MENU = 118, SDL_SCANCODE_SELECT = 119, SDL_SCANCODE_STOP = 120, SDL_SCANCODE_AGAIN = 121, SDL_SCANCODE_UNDO = 122, SDL_SCANCODE_CUT = 123, SDL_SCANCODE_COPY = 124, SDL_SCANCODE_PASTE = 125, SDL_SCANCODE_FIND = 126, SDL_SCANCODE_MUTE = 127, SDL_SCANCODE_VOLUMEUP = 128, SDL_SCANCODE_VOLUMEDOWN = 129, SDL_SCANCODE_KP_COMMA = 133, SDL_SCANCODE_KP_EQUALSAS400 = 134, SDL_SCANCODE_INTERNATIONAL1 = 135, SDL_SCANCODE_INTERNATIONAL2 = 136, SDL_SCANCODE_INTERNATIONAL3 = 137, SDL_SCANCODE_INTERNATIONAL4 = 138, SDL_SCANCODE_INTERNATIONAL5 = 139, SDL_SCANCODE_INTERNATIONAL6 = 140, SDL_SCANCODE_INTERNATIONAL7 = 141, SDL_SCANCODE_INTERNATIONAL8 = 142, SDL_SCANCODE_INTERNATIONAL9 = 143, SDL_SCANCODE_LANG1 = 144, SDL_SCANCODE_LANG2 = 145, SDL_SCANCODE_LANG3 = 146, SDL_SCANCODE_LANG4 = 147, SDL_SCANCODE_LANG5 = 148, SDL_SCANCODE_LANG6 = 149, SDL_SCANCODE_LANG7 = 150, SDL_SCANCODE_LANG8 = 151, SDL_SCANCODE_LANG9 = 152, SDL_SCANCODE_ALTERASE = 153, SDL_SCANCODE_SYSREQ = 154, SDL_SCANCODE_CANCEL = 155, SDL_SCANCODE_CLEAR = 156, SDL_SCANCODE_PRIOR = 157, SDL_SCANCODE_RETURN2 = 158, SDL_SCANCODE_SEPARATOR = 159, SDL_SCANCODE_OUT = 160, SDL_SCANCODE_OPER = 161, SDL_SCANCODE_CLEARAGAIN = 162, SDL_SCANCODE_CRSEL = 163, SDL_SCANCODE_EXSEL = 164, SDL_SCANCODE_KP_00 = 176, SDL_SCANCODE_KP_000 = 177, SDL_SCANCODE_THOUSANDSSEPARATOR = 178, SDL_SCANCODE_DECIMALSEPARATOR = 179, SDL_SCANCODE_CURRENCYUNIT = 180, SDL_SCANCODE_CURRENCYSUBUNIT = 181, SDL_SCANCODE_KP_LEFTPAREN = 182, SDL_SCANCODE_KP_RIGHTPAREN = 183, SDL_SCANCODE_KP_LEFTBRACE = 184, SDL_SCANCODE_KP_RIGHTBRACE = 185, SDL_SCANCODE_KP_TAB = 186, SDL_SCANCODE_KP_BACKSPACE = 187, SDL_SCANCODE_KP_A = 188, SDL_SCANCODE_KP_B = 189, SDL_SCANCODE_KP_C = 190, SDL_SCANCODE_KP_D = 191, SDL_SCANCODE_KP_E = 192, SDL_SCANCODE_KP_F = 193, SDL_SCANCODE_KP_XOR = 194, SDL_SCANCODE_KP_POWER = 195, SDL_SCANCODE_KP_PERCENT = 196, SDL_SCANCODE_KP_LESS = 197, SDL_SCANCODE_KP_GREATER = 198, SDL_SCANCODE_KP_AMPERSAND = 199, SDL_SCANCODE_KP_DBLAMPERSAND = 200, SDL_SCANCODE_KP_VERTICALBAR = 201, SDL_SCANCODE_KP_DBLVERTICALBAR = 202, SDL_SCANCODE_KP_COLON = 203, SDL_SCANCODE_KP_HASH = 204, SDL_SCANCODE_KP_SPACE = 205, SDL_SCANCODE_KP_AT = 206, SDL_SCANCODE_KP_EXCLAM = 207, SDL_SCANCODE_KP_MEMSTORE = 208, SDL_SCANCODE_KP_MEMRECALL = 209, SDL_SCANCODE_KP_MEMCLEAR = 210, SDL_SCANCODE_KP_MEMADD = 211, SDL_SCANCODE_KP_MEMSUBTRACT = 212, SDL_SCANCODE_KP_MEMMULTIPLY = 213, SDL_SCANCODE_KP_MEMDIVIDE = 214, SDL_SCANCODE_KP_PLUSMINUS = 215, SDL_SCANCODE_KP_CLEAR = 216, SDL_SCANCODE_KP_CLEARENTRY = 217, SDL_SCANCODE_KP_BINARY = 218, SDL_SCANCODE_KP_OCTAL = 219, SDL_SCANCODE_KP_DECIMAL = 220, SDL_SCANCODE_KP_HEXADECIMAL = 221, SDL_SCANCODE_LCTRL = 224, SDL_SCANCODE_LSHIFT = 225, SDL_SCANCODE_LALT = 226, SDL_SCANCODE_LGUI = 227, SDL_SCANCODE_RCTRL = 228, SDL_SCANCODE_RSHIFT = 229, SDL_SCANCODE_RALT = 230, SDL_SCANCODE_RGUI = 231, SDL_SCANCODE_MODE = 257, SDL_SCANCODE_AUDIONEXT = 258, SDL_SCANCODE_AUDIOPREV = 259, SDL_SCANCODE_AUDIOSTOP = 260, SDL_SCANCODE_AUDIOPLAY = 261, SDL_SCANCODE_AUDIOMUTE = 262, SDL_SCANCODE_MEDIASELECT = 263, SDL_SCANCODE_WWW = 264, SDL_SCANCODE_MAIL = 265, SDL_SCANCODE_CALCULATOR = 266, SDL_SCANCODE_COMPUTER = 267, SDL_SCANCODE_AC_SEARCH = 268, SDL_SCANCODE_AC_HOME = 269, SDL_SCANCODE_AC_BACK = 270, SDL_SCANCODE_AC_FORWARD = 271, SDL_SCANCODE_AC_STOP = 272, SDL_SCANCODE_AC_REFRESH = 273, SDL_SCANCODE_AC_BOOKMARKS = 274, SDL_SCANCODE_BRIGHTNESSDOWN = 275, SDL_SCANCODE_BRIGHTNESSUP = 276, SDL_SCANCODE_DISPLAYSWITCH = 277, SDL_SCANCODE_KBDILLUMTOGGLE = 278, SDL_SCANCODE_KBDILLUMDOWN = 279, SDL_SCANCODE_KBDILLUMUP = 280, SDL_SCANCODE_EJECT = 281, SDL_SCANCODE_SLEEP = 282, SDL_SCANCODE_APP1 = 283, SDL_SCANCODE_APP2 = 284, SDL_NUM_SCANCODES = 512 } }
// // assign.cs: Assignments. // // Author: // Miguel de Icaza (miguel@ximian.com) // Martin Baulig (martin@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001, 2002, 2003 Ximian, Inc. // Copyright 2004-2008 Novell, Inc // Copyright 2011 Xamarin Inc // using System; #if STATIC using IKVM.Reflection.Emit; #else using System.Reflection.Emit; #endif namespace Mono.CSharp { /// <summary> /// This interface is implemented by expressions that can be assigned to. /// </summary> /// <remarks> /// This interface is implemented by Expressions whose values can not /// store the result on the top of the stack. /// /// Expressions implementing this (Properties, Indexers and Arrays) would /// perform an assignment of the Expression "source" into its final /// location. /// /// No values on the top of the stack are expected to be left by /// invoking this method. /// </remarks> public interface IAssignMethod { // // This is an extra version of Emit. If leave_copy is `true' // A copy of the expression will be left on the stack at the // end of the code generated for EmitAssign // void Emit (EmitContext ec, bool leave_copy); // // This method does the assignment // `source' will be stored into the location specified by `this' // if `leave_copy' is true, a copy of `source' will be left on the stack // if `prepare_for_load' is true, when `source' is emitted, there will // be data on the stack that it can use to compuatate its value. This is // for expressions like a [f ()] ++, where you can't call `f ()' twice. // void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound); /* For simple assignments, this interface is very simple, EmitAssign is called with source as the source expression and leave_copy and prepare_for_load false. For compound assignments it gets complicated. EmitAssign will be called as before, however, prepare_for_load will be true. The @source expression will contain an expression which calls Emit. So, the calls look like: this.EmitAssign (ec, source, false, true) -> source.Emit (ec); -> [...] -> this.Emit (ec, false); -> end this.Emit (ec, false); -> end [...] end source.Emit (ec); end this.EmitAssign (ec, source, false, true) When prepare_for_load is true, EmitAssign emits a `token' on the stack that Emit will use for its state. Let's take FieldExpr as an example. assume we are emitting f ().y += 1; Here is the call tree again. This time, each call is annotated with the IL it produces: this.EmitAssign (ec, source, false, true) call f dup Binary.Emit () this.Emit (ec, false); ldfld y end this.Emit (ec, false); IntConstant.Emit () ldc.i4.1 end IntConstant.Emit add end Binary.Emit () stfld end this.EmitAssign (ec, source, false, true) Observe two things: 1) EmitAssign left a token on the stack. It was the result of f (). 2) This token was used by Emit leave_copy (in both EmitAssign and Emit) tells the compiler to leave a copy of the expression at that point in evaluation. This is used for pre/post inc/dec and for a = x += y. Let's do the above example with leave_copy true in EmitAssign this.EmitAssign (ec, source, true, true) call f dup Binary.Emit () this.Emit (ec, false); ldfld y end this.Emit (ec, false); IntConstant.Emit () ldc.i4.1 end IntConstant.Emit add end Binary.Emit () dup stloc temp stfld ldloc temp end this.EmitAssign (ec, source, true, true) And with it true in Emit this.EmitAssign (ec, source, false, true) call f dup Binary.Emit () this.Emit (ec, true); ldfld y dup stloc temp end this.Emit (ec, true); IntConstant.Emit () ldc.i4.1 end IntConstant.Emit add end Binary.Emit () stfld ldloc temp end this.EmitAssign (ec, source, false, true) Note that these two examples are what happens for ++x and x++, respectively. */ } /// <summary> /// An Expression to hold a temporary value. /// </summary> /// <remarks> /// The LocalTemporary class is used to hold temporary values of a given /// type to "simulate" the expression semantics. The local variable is /// never captured. /// /// The local temporary is used to alter the normal flow of code generation /// basically it creates a local variable, and its emit instruction generates /// code to access this value, return its address or save its value. /// /// If `is_address' is true, then the value that we store is the address to the /// real value, and not the value itself. /// /// This is needed for a value type, because otherwise you just end up making a /// copy of the value on the stack and modifying it. You really need a pointer /// to the origional value so that you can modify it in that location. This /// Does not happen with a class because a class is a pointer -- so you always /// get the indirection. /// /// </remarks> public class LocalTemporary : Expression, IMemoryLocation, IAssignMethod { LocalBuilder builder; public LocalTemporary (TypeSpec t) { type = t; eclass = ExprClass.Value; } public LocalTemporary (LocalBuilder b, TypeSpec t) : this (t) { builder = b; } public void Release (EmitContext ec) { ec.FreeTemporaryLocal (builder, type); builder = null; } public override bool ContainsEmitWithAwait () { return false; } public override Expression CreateExpressionTree (ResolveContext ec) { Arguments args = new Arguments (1); args.Add (new Argument (this)); return CreateExpressionFactoryCall (ec, "Constant", args); } protected override Expression DoResolve (ResolveContext ec) { return this; } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { return this; } public override void Emit (EmitContext ec) { if (builder == null) throw new InternalErrorException ("Emit without Store, or after Release"); ec.Emit (OpCodes.Ldloc, builder); } #region IAssignMethod Members public void Emit (EmitContext ec, bool leave_copy) { Emit (ec); if (leave_copy) Emit (ec); } public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound) { if (isCompound) throw new NotImplementedException (); source.Emit (ec); Store (ec); if (leave_copy) Emit (ec); } #endregion public LocalBuilder Builder { get { return builder; } } public void Store (EmitContext ec) { if (builder == null) builder = ec.GetTemporaryLocal (type); ec.Emit (OpCodes.Stloc, builder); } public void AddressOf (EmitContext ec, AddressOp mode) { if (builder == null) builder = ec.GetTemporaryLocal (type); if (builder.LocalType.IsByRef) { // // if is_address, than this is just the address anyways, // so we just return this. // ec.Emit (OpCodes.Ldloc, builder); } else { ec.Emit (OpCodes.Ldloca, builder); } } } /// <summary> /// The Assign node takes care of assigning the value of source into /// the expression represented by target. /// </summary> public abstract class Assign : ExpressionStatement { protected Expression target, source; protected Assign (Expression target, Expression source, Location loc) { this.target = target; this.source = source; this.loc = loc; } public Expression Target { get { return target; } } public Expression Source { get { return source; } } public override Location StartLocation { get { return target.StartLocation; } } public override bool ContainsEmitWithAwait () { return target.ContainsEmitWithAwait () || source.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext ec) { ec.Report.Error (832, loc, "An expression tree cannot contain an assignment operator"); return null; } protected override Expression DoResolve (ResolveContext ec) { bool ok = true; source = source.Resolve (ec); if (source == null) { ok = false; source = ErrorExpression.Instance; } target = target.ResolveLValue (ec, source); if (target == null || !ok) return null; TypeSpec target_type = target.Type; TypeSpec source_type = source.Type; eclass = ExprClass.Value; type = target_type; if (!(target is IAssignMethod)) { target.Error_ValueAssignment (ec, source); return null; } if (target_type != source_type) { Expression resolved = ResolveConversions (ec); if (resolved != this) return resolved; } return this; } public override System.Linq.Expressions.Expression MakeExpression (BuilderContext ctx) { var tassign = target as IDynamicAssign; if (tassign == null) throw new InternalErrorException (target.GetType () + " does not support dynamic assignment"); var target_object = tassign.MakeAssignExpression (ctx, source); // // Some hacking is needed as DLR does not support void type and requires // always have object convertible return type to support caching and chaining // // We do this by introducing an explicit block which returns RHS value when // available or null // if (target_object.NodeType == System.Linq.Expressions.ExpressionType.Block) return target_object; System.Linq.Expressions.UnaryExpression source_object; if (ctx.HasSet (BuilderContext.Options.CheckedScope)) { source_object = System.Linq.Expressions.Expression.ConvertChecked (source.MakeExpression (ctx), target_object.Type); } else { source_object = System.Linq.Expressions.Expression.Convert (source.MakeExpression (ctx), target_object.Type); } return System.Linq.Expressions.Expression.Assign (target_object, source_object); } protected virtual Expression ResolveConversions (ResolveContext ec) { source = Convert.ImplicitConversionRequired (ec, source, target.Type, source.Location); if (source == null) return null; return this; } void Emit (EmitContext ec, bool is_statement) { IAssignMethod t = (IAssignMethod) target; t.EmitAssign (ec, source, !is_statement, this is CompoundAssign); } public override void Emit (EmitContext ec) { Emit (ec, false); } public override void EmitStatement (EmitContext ec) { Emit (ec, true); } public override void FlowAnalysis (FlowAnalysisContext fc) { source.FlowAnalysis (fc); if (target is ArrayAccess || target is IndexerExpr) { target.FlowAnalysis (fc); return; } var pe = target as PropertyExpr; if (pe != null && !pe.IsAutoPropertyAccess) target.FlowAnalysis (fc); } protected override void CloneTo (CloneContext clonectx, Expression t) { Assign _target = (Assign) t; _target.target = target.Clone (clonectx); _target.source = source.Clone (clonectx); } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } public class SimpleAssign : Assign { public SimpleAssign (Expression target, Expression source) : this (target, source, target.Location) { } public SimpleAssign (Expression target, Expression source, Location loc) : base (target, source, loc) { } bool CheckEqualAssign (Expression t) { if (source is Assign) { Assign a = (Assign) source; if (t.Equals (a.Target)) return true; return a is SimpleAssign && ((SimpleAssign) a).CheckEqualAssign (t); } return t.Equals (source); } protected override Expression DoResolve (ResolveContext ec) { Expression e = base.DoResolve (ec); if (e == null || e != this) return e; if (CheckEqualAssign (target)) ec.Report.Warning (1717, 3, loc, "Assignment made to same variable; did you mean to assign something else?"); return this; } public override void FlowAnalysis (FlowAnalysisContext fc) { base.FlowAnalysis (fc); var vr = target as VariableReference; if (vr != null) { if (vr.VariableInfo != null) fc.SetVariableAssigned (vr.VariableInfo); return; } var fe = target as FieldExpr; if (fe != null) { fe.SetFieldAssigned (fc); return; } var pe = target as PropertyExpr; if (pe != null) { pe.SetBackingFieldAssigned (fc); return; } var td = target as TupleDeconstruct; if (td != null) { td.SetGeneratedFieldAssigned (fc); return; } } public override Reachability MarkReachable (Reachability rc) { return source.MarkReachable (rc); } } public class RuntimeExplicitAssign : Assign { public RuntimeExplicitAssign (Expression target, Expression source) : base (target, source, target.Location) { } protected override Expression ResolveConversions (ResolveContext ec) { source = EmptyCast.Create (source, target.Type); return this; } } // // Compiler generated assign // class CompilerAssign : Assign { public CompilerAssign (Expression target, Expression source, Location loc) : base (target, source, loc) { if (target.Type != null) { type = target.Type; eclass = ExprClass.Value; } } protected override Expression DoResolve (ResolveContext ec) { var expr = base.DoResolve (ec); var vr = target as VariableReference; if (vr != null && vr.VariableInfo != null) vr.VariableInfo.IsEverAssigned = false; return expr; } public void UpdateSource (Expression source) { base.source = source; } } // // Implements fields and events class initializers // public class FieldInitializer : Assign { // // Field initializers are tricky for partial classes. They have to // share same constructor (block) for expression trees resolve but // they have they own resolve scope // sealed class FieldInitializerContext : BlockContext { readonly ExplicitBlock ctor_block; public FieldInitializerContext (IMemberContext mc, BlockContext constructorContext) : base (mc, null, constructorContext.ReturnType) { flags |= Options.FieldInitializerScope | Options.ConstructorScope; this.ctor_block = constructorContext.CurrentBlock.Explicit; if (ctor_block.IsCompilerGenerated) CurrentBlock = ctor_block; } public override ExplicitBlock ConstructorBlock { get { return ctor_block; } } } // // Keep resolved value because field initializers have their own rules // ExpressionStatement resolved; FieldBase mc; public FieldInitializer (FieldBase mc, Expression expression, Location loc) : base (new FieldExpr (mc.Spec, expression.Location), expression, loc) { this.mc = mc; if (!mc.IsStatic) ((FieldExpr)target).InstanceExpression = new CompilerGeneratedThis (mc.CurrentType, expression.Location); } public int AssignmentOffset { get; private set; } public FieldBase Field { get { return mc; } } public override Location StartLocation { get { return loc; } } protected override Expression DoResolve (ResolveContext rc) { // Field initializer can be resolved (fail) many times if (source == null) return null; if (resolved == null) { var bc = (BlockContext) rc; var ctx = new FieldInitializerContext (mc, bc); resolved = base.DoResolve (ctx) as ExpressionStatement; AssignmentOffset = ctx.AssignmentInfoOffset - bc.AssignmentInfoOffset; } return resolved; } public override void EmitStatement (EmitContext ec) { if (resolved == null) return; // // Emit sequence symbol info even if we are in compiler generated // block to allow debugging field initializers when constructor is // compiler generated // if (ec.HasSet (BuilderContext.Options.OmitDebugInfo) && ec.HasMethodSymbolBuilder) { using (ec.With (BuilderContext.Options.OmitDebugInfo, false)) { ec.Mark (loc); } } if (resolved != this) resolved.EmitStatement (ec); else base.EmitStatement (ec); } public override void FlowAnalysis (FlowAnalysisContext fc) { source.FlowAnalysis (fc); ((FieldExpr) target).SetFieldAssigned (fc); } public bool IsDefaultInitializer { get { Constant c = source as Constant; if (c == null) return false; FieldExpr fe = (FieldExpr)target; return c.IsDefaultInitializer (fe.Type); } } public override bool IsSideEffectFree { get { return source.IsSideEffectFree; } } } class PrimaryConstructorAssign : SimpleAssign { readonly Field field; readonly Parameter parameter; public PrimaryConstructorAssign (Field field, Parameter parameter) : base (null, null, parameter.Location) { this.field = field; this.parameter = parameter; } protected override Expression DoResolve (ResolveContext rc) { target = new FieldExpr (field, loc); source = rc.CurrentBlock.ParametersBlock.GetParameterInfo (parameter).CreateReferenceExpression (rc, loc); return base.DoResolve (rc); } public override void EmitStatement (EmitContext ec) { using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) { base.EmitStatement (ec); } } } // // This class is used for compound assignments. // public class CompoundAssign : Assign { // This is just a hack implemented for arrays only public sealed class TargetExpression : Expression { readonly Expression child; public TargetExpression (Expression child) { this.child = child; this.loc = child.Location; } public bool RequiresEmitWithAwait { get; set; } public override bool ContainsEmitWithAwait () { return RequiresEmitWithAwait || child.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("ET"); } protected override Expression DoResolve (ResolveContext ec) { type = child.Type; eclass = ExprClass.Value; return this; } public override void Emit (EmitContext ec) { child.Emit (ec); } public override Expression EmitToField (EmitContext ec) { return child.EmitToField (ec); } } // Used for underlying binary operator readonly Binary.Operator op; Expression right; Expression left; public CompoundAssign (Binary.Operator op, Expression target, Expression source) : base (target, source, target.Location) { right = source; this.op = op; } public CompoundAssign (Binary.Operator op, Expression target, Expression source, Expression left) : this (op, target, source) { this.left = left; } public Binary.Operator Operator { get { return op; } } protected override Expression DoResolve (ResolveContext ec) { right = right.Resolve (ec); if (right == null) return null; MemberAccess ma = target as MemberAccess; using (ec.Set (ResolveContext.Options.CompoundAssignmentScope)) { target = target.Resolve (ec); } if (target == null) return null; if (target is MethodGroupExpr){ ec.Report.Error (1656, loc, "Cannot assign to `{0}' because it is a `{1}'", ((MethodGroupExpr)target).Name, target.ExprClassName); return null; } var event_expr = target as EventExpr; if (event_expr != null) { source = Convert.ImplicitConversionRequired (ec, right, target.Type, loc); if (source == null) return null; Expression rside; if (op == Binary.Operator.Addition) rside = EmptyExpression.EventAddition; else if (op == Binary.Operator.Subtraction) rside = EmptyExpression.EventSubtraction; else rside = null; target = target.ResolveLValue (ec, rside); if (target == null) return null; eclass = ExprClass.Value; type = event_expr.Operator.ReturnType; return this; } // // Only now we can decouple the original source/target // into a tree, to guarantee that we do not have side // effects. // if (left == null) left = new TargetExpression (target); source = new Binary (op, left, right, true); if (target is DynamicMemberAssignable) { Arguments targs = ((DynamicMemberAssignable) target).Arguments; source = source.Resolve (ec); Arguments args = new Arguments (targs.Count + 1); args.AddRange (targs); args.Add (new Argument (source)); var binder_flags = CSharpBinderFlags.ValueFromCompoundAssignment; // // Compound assignment does target conversion using additional method // call, set checked context as the binary operation can overflow // if (ec.HasSet (ResolveContext.Options.CheckedScope)) binder_flags |= CSharpBinderFlags.CheckedContext; if (target is DynamicMemberBinder) { source = new DynamicMemberBinder (ma.Name, binder_flags, args, loc).Resolve (ec); // Handles possible event addition/subtraction if (op == Binary.Operator.Addition || op == Binary.Operator.Subtraction) { args = new Arguments (targs.Count + 1); args.AddRange (targs); args.Add (new Argument (right)); string method_prefix = op == Binary.Operator.Addition ? Event.AEventAccessor.AddPrefix : Event.AEventAccessor.RemovePrefix; var invoke = DynamicInvocation.CreateSpecialNameInvoke ( new MemberAccess (right, method_prefix + ma.Name, loc), args, loc).Resolve (ec); args = new Arguments (targs.Count); args.AddRange (targs); source = new DynamicEventCompoundAssign (ma.Name, args, (ExpressionStatement) source, (ExpressionStatement) invoke, loc).Resolve (ec); } } else { source = new DynamicIndexBinder (binder_flags, args, loc).Resolve (ec); } return source; } return base.DoResolve (ec); } public override void FlowAnalysis (FlowAnalysisContext fc) { target.FlowAnalysis (fc); source.FlowAnalysis (fc); } protected override Expression ResolveConversions (ResolveContext ec) { // // LAMESPEC: Under dynamic context no target conversion is happening // This allows more natual dynamic behaviour but breaks compatibility // with static binding // if (target is RuntimeValueExpression) return this; TypeSpec target_type = target.Type; // // 1. the return type is implicitly convertible to the type of target // if (Convert.ImplicitConversionExists (ec, source, target_type)) { source = Convert.ImplicitConversion (ec, source, target_type, loc); return this; } // // Otherwise, if the selected operator is a predefined operator // Binary b = source as Binary; if (b == null) { if (source is ReducedExpression) b = ((ReducedExpression) source).OriginalExpression as Binary; else if (source is ReducedExpression.ReducedConstantExpression) { b = ((ReducedExpression.ReducedConstantExpression) source).OriginalExpression as Binary; } else if (source is Nullable.LiftedBinaryOperator) { var po = ((Nullable.LiftedBinaryOperator) source); if (po.UserOperator == null) b = po.Binary; } else if (source is TypeCast) { b = ((TypeCast) source).Child as Binary; } } if (b != null) { // // 2a. the operator is a shift operator // // 2b. the return type is explicitly convertible to the type of x, and // y is implicitly convertible to the type of x // if ((b.Oper & Binary.Operator.ShiftMask) != 0 || Convert.ImplicitConversionExists (ec, right, target_type)) { source = Convert.ExplicitConversion (ec, source, target_type, loc); return this; } } if (source.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { Arguments arg = new Arguments (1); arg.Add (new Argument (source)); return new SimpleAssign (target, new DynamicConversion (target_type, CSharpBinderFlags.ConvertExplicit, arg, loc), loc).Resolve (ec); } right.Error_ValueCannotBeConverted (ec, target_type, false); return null; } protected override void CloneTo (CloneContext clonectx, Expression t) { CompoundAssign ctarget = (CompoundAssign) t; ctarget.right = ctarget.source = source.Clone (clonectx); ctarget.target = target.Clone (clonectx); } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } }
// 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.Compute { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Composite Swagger for Compute Client /// </summary> public partial class ComputeManagementClient : ServiceClient<ComputeManagementClient>, IComputeManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IAvailabilitySetsOperations. /// </summary> public virtual IAvailabilitySetsOperations AvailabilitySets { get; private set; } /// <summary> /// Gets the IVirtualMachineExtensionImagesOperations. /// </summary> public virtual IVirtualMachineExtensionImagesOperations VirtualMachineExtensionImages { get; private set; } /// <summary> /// Gets the IVirtualMachineExtensionsOperations. /// </summary> public virtual IVirtualMachineExtensionsOperations VirtualMachineExtensions { get; private set; } /// <summary> /// Gets the IVirtualMachineImagesOperations. /// </summary> public virtual IVirtualMachineImagesOperations VirtualMachineImages { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Gets the IVirtualMachineSizesOperations. /// </summary> public virtual IVirtualMachineSizesOperations VirtualMachineSizes { get; private set; } /// <summary> /// Gets the IImagesOperations. /// </summary> public virtual IImagesOperations Images { get; private set; } /// <summary> /// Gets the IVirtualMachinesOperations. /// </summary> public virtual IVirtualMachinesOperations VirtualMachines { get; private set; } /// <summary> /// Gets the IVirtualMachineScaleSetsOperations. /// </summary> public virtual IVirtualMachineScaleSetsOperations VirtualMachineScaleSets { get; private set; } /// <summary> /// Gets the IVirtualMachineScaleSetVMsOperations. /// </summary> public virtual IVirtualMachineScaleSetVMsOperations VirtualMachineScaleSetVMs { get; private set; } /// <summary> /// Gets the IContainerServicesOperations. /// </summary> public virtual IContainerServicesOperations ContainerServices { get; private set; } /// <summary> /// Gets the IDisksOperations. /// </summary> public virtual IDisksOperations Disks { get; private set; } /// <summary> /// Gets the ISnapshotsOperations. /// </summary> public virtual ISnapshotsOperations Snapshots { get; private set; } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ComputeManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ComputeManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected ComputeManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected ComputeManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public ComputeManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { AvailabilitySets = new AvailabilitySetsOperations(this); VirtualMachineExtensionImages = new VirtualMachineExtensionImagesOperations(this); VirtualMachineExtensions = new VirtualMachineExtensionsOperations(this); VirtualMachineImages = new VirtualMachineImagesOperations(this); Usage = new UsageOperations(this); VirtualMachineSizes = new VirtualMachineSizesOperations(this); Images = new ImagesOperations(this); VirtualMachines = new VirtualMachinesOperations(this); VirtualMachineScaleSets = new VirtualMachineScaleSetsOperations(this); VirtualMachineScaleSetVMs = new VirtualMachineScaleSetVMsOperations(this); ContainerServices = new ContainerServicesOperations(this); Disks = new DisksOperations(this); Snapshots = new SnapshotsOperations(this); BaseUri = new System.Uri("https://management.azure.com"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// SampSharp // Copyright 2017 Tim Potze // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using SampSharp.Core.Logging; using SampSharp.GameMode.SAMP.Commands.PermissionCheckers; using SampSharp.GameMode.World; namespace SampSharp.GameMode.SAMP.Commands { /// <summary> /// Represents the default commands manager. /// </summary> public class CommandsManager : ICommandsManager { private static readonly Type[] SupportedReturnTypes = {typeof (bool), typeof (void)}; private readonly List<ICommand> _commands = new List<ICommand>(); /// <summary> /// Initializes a new instance of the <see cref="CommandsManager"/> class. /// </summary> /// <param name="gameMode">The game mode.</param> /// <exception cref="ArgumentNullException"></exception> public CommandsManager(BaseMode gameMode) { GameMode = gameMode ?? throw new ArgumentNullException(nameof(gameMode)); } #region Implementation of IService /// <summary> /// Gets the game mode. /// </summary> public BaseMode GameMode { get; } #endregion /// <summary> /// Registers the specified command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case of the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> public virtual void Register(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { Register(CreateCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage)); } /// <summary> /// Creates a command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> /// <returns>The created command</returns> protected virtual ICommand CreateCommand(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { return new DefaultCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage); } /// <summary> /// Creates a help command. /// </summary> /// <param name="commandPaths">The command paths.</param> /// <param name="displayName">The display name.</param> /// <param name="ignoreCase">if set to <c>true</c> ignore the case the command.</param> /// <param name="permissionCheckers">The permission checkers.</param> /// <param name="method">The method.</param> /// <param name="usageMessage">The usage message.</param> /// <returns>The created command</returns> protected virtual ICommand CreateHelpCommand(CommandPath[] commandPaths, string displayName, bool ignoreCase, IPermissionChecker[] permissionCheckers, MethodInfo method, string usageMessage) { return new DefaultHelpCommand(commandPaths, displayName, ignoreCase, permissionCheckers, method, usageMessage); } private static IPermissionChecker CreatePermissionChecker(Type type) { if (type == null || !typeof(IPermissionChecker).GetTypeInfo().IsAssignableFrom(type)) return null; return Activator.CreateInstance(type) as IPermissionChecker; } private static IEnumerable<IPermissionChecker> GetCommandPermissionCheckers(Type type) { if (type == null || type == typeof(object)) yield break; foreach (var permissionChecker in GetCommandPermissionCheckers(type.DeclaringType)) yield return permissionChecker; foreach ( var permissionChecker in type.GetTypeInfo() .GetCustomAttributes<CommandGroupAttribute>() .Select(a => a.PermissionChecker) .Distinct() .Select(CreatePermissionChecker) .Where(c => c != null)) yield return permissionChecker; } private static IEnumerable<IPermissionChecker> GetCommandPermissionCheckers(MethodInfo method) { foreach (var permissionChecker in GetCommandPermissionCheckers(method.DeclaringType)) yield return permissionChecker; foreach ( var permissionChecker in method.GetCustomAttributes<CommandGroupAttribute>() .Select(a => a.PermissionChecker) .Concat(method.GetCustomAttributes<CommandAttribute>() .Select(a => a.PermissionChecker)) .Distinct() .Select(CreatePermissionChecker) .Where(c => c != null)) yield return permissionChecker; } private static IEnumerable<string> GetCommandGroupPaths(Type type) { if (type == null || type == typeof (object)) yield break; var count = 0; var groups = type.GetTypeInfo() .GetCustomAttributes<CommandGroupAttribute>() .SelectMany(a => { var paths = a.Paths; if (paths.Length == 0) { var name = type.Name.ToLower(); if (name.EndsWith("commandgroup")) name = name.Substring(0, name.Length - 12); paths = new[] {name}; } return paths; }) .Select(g => g.Trim()) .Where(g => !string.IsNullOrEmpty(g)).ToArray(); foreach (var group in GetCommandGroupPaths(type.DeclaringType)) { if (groups.Length == 0) yield return group; else foreach (var g in groups) yield return $"{group} {g}"; count++; } if (count == 0) foreach (var g in groups) yield return g; } private static IEnumerable<string> GetCommandGroupPaths(MethodInfo method) { var count = 0; var groups = method.GetCustomAttributes<CommandGroupAttribute>() .SelectMany(a => a.Paths) .Select(g => g.Trim()) .Where(g => !string.IsNullOrEmpty(g)).ToArray(); foreach (var path in GetCommandGroupPaths(method.DeclaringType)) { if (groups.Length == 0) yield return path; else foreach (var g in groups) yield return $"{path} {g}"; count++; } if (count == 0) foreach (var g in groups) yield return g; } /// <summary> /// Gets the command for the specified command text. /// </summary> /// <param name="player">The player.</param> /// <param name="commandText">The command text.</param> /// <returns>The found command.</returns> public ICommand GetCommandForText(BasePlayer player, string commandText) { ICommand candidate = null; var isFullMath = false; var candidateLength = 0; foreach (var command in _commands) { switch (command.CanInvoke(player, commandText, out var matchedNameLength)) { case CommandCallableResponse.True: if (candidateLength < matchedNameLength || candidateLength == matchedNameLength && !isFullMath) { isFullMath = true; candidateLength = matchedNameLength; candidate = command; } break; case CommandCallableResponse.Optional: if (candidateLength < matchedNameLength) { candidate = command; candidateLength = matchedNameLength; } break; } } return candidate; } #region Implementation of ICommandsManager /// <summary> /// Gets a read-only collection of all registered commands. /// </summary> public virtual IReadOnlyCollection<ICommand> Commands => _commands.AsReadOnly(); /// <summary> /// Loads all tagged commands from the assembly containing the specified type. /// </summary> /// <typeparam name="T">A type inside the assembly to load the commands form.</typeparam> public virtual void RegisterCommands<T>() where T : class { RegisterCommands(typeof (T)); } /// <summary> /// Loads all tagged commands from the assembly containing the specified type. /// </summary> /// <param name="typeInAssembly">A type inside the assembly to load the commands form.</param> public virtual void RegisterCommands(Type typeInAssembly) { if (typeInAssembly == null) throw new ArgumentNullException(nameof(typeInAssembly)); RegisterCommands(typeInAssembly.GetTypeInfo().Assembly); } /// <summary> /// Loads all tagged commands from the specified <paramref name="assembly" />. /// </summary> /// <param name="assembly">The assembly to load the commands from.</param> public virtual void RegisterCommands(Assembly assembly) { foreach ( var method in assembly.GetTypes() // Get all classes in the specified assembly. .Where(type => !type.GetTypeInfo().IsInterface && type.GetTypeInfo().IsClass) // Select the methods in the type. .SelectMany( type => type.GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) // Exclude abstract methods. (none should be since abstract types are excluded) .Where(method => !method.IsAbstract) // Only include methods with a return type of bool or void. .Where(method => SupportedReturnTypes.Contains(method.ReturnType)) // Only include methods which have a command attribute. .Where(method => method.GetCustomAttribute<CommandAttribute>() != null) // Only include methods which are static and have a player as first argument -or- are a non-static member of a player derived class. .Where(DefaultCommand.IsValidCommandMethod) ) { var attribute = method.GetCustomAttribute<CommandAttribute>(); var names = attribute.Names; if (attribute.IsGroupHelp) { var helpCommandPaths = GetCommandGroupPaths(method) .Select(g => new CommandPath(g)) .ToArray(); if (helpCommandPaths.Length > 0) { Register(CreateHelpCommand(helpCommandPaths, attribute.DisplayName, attribute.IgnoreCase, GetCommandPermissionCheckers(method).ToArray(), method, attribute.UsageMessage)); } continue; } if (names.Length == 0) { var name = attribute.IgnoreCase ? method.Name.ToLower() : method.Name; names = new[] { name.EndsWith("command") || name.EndsWith("Command") ? name.Substring(0, name.Length - 7) : name }; } var commandPaths = GetCommandGroupPaths(method) .SelectMany(g => names.Select(n => new CommandPath(g, n))) .ToList(); if (commandPaths.Count == 0) commandPaths.AddRange(names.Select(n => new CommandPath(n))); if (!string.IsNullOrWhiteSpace(attribute.Shortcut)) commandPaths.Add(new CommandPath(attribute.Shortcut)); Register(commandPaths.ToArray(), attribute.DisplayName, attribute.IgnoreCase, GetCommandPermissionCheckers(method).ToArray(), method, attribute.UsageMessage); } } /// <summary> /// Registers the specified command. /// </summary> /// <param name="command">The command.</param> public virtual void Register(ICommand command) { if (command == null) throw new ArgumentNullException(nameof(command)); CoreLog.Log(CoreLogLevel.Debug, $"Registering command {command}"); _commands.Add(command); } /// <summary> /// Processes the specified player. /// </summary> /// <param name="commandText">The command text.</param> /// <param name="player">The player.</param> /// <returns>true if processed; false otherwise.</returns> public virtual bool Process(string commandText, BasePlayer player) { var command = GetCommandForText(player, commandText); return command != null && command.Invoke(player, commandText); } #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright 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. // ---------------------------------------------------------------------------------- using System.Collections; using System.Collections.Generic; using System.Management.Automation; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using StorageModels = Microsoft.Azure.Management.Storage.Models; using Microsoft.Azure.Commands.Management.Storage.Models; namespace Microsoft.Azure.Commands.Management.Storage { /// <summary> /// Lists all storage services underneath the subscription. /// </summary> [Cmdlet(VerbsCommon.Set, StorageAccountNounStr, SupportsShouldProcess = true, DefaultParameterSetName = StorageEncryptionParameterSet), OutputType(typeof(StorageModels.StorageAccount))] public class SetAzureStorageAccountCommand : StorageAccountBaseCmdlet { /// <summary> /// Storage Encryption parameter set name /// </summary> private const string StorageEncryptionParameterSet = "StorageEncryption"; /// <summary> /// Keyvault Encryption parameter set name /// </summary> private const string KeyvaultEncryptionParameterSet = "KeyvaultEncryption"; [Parameter( Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Resource Group Name.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Name.")] [Alias(StorageAccountNameAlias, AccountNameAlias)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(HelpMessage = "Force to Set the Account")] public SwitchParameter Force { get { return force; } set { force = value; } } private bool force = false; [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Sku Name.")] [Alias(StorageAccountTypeAlias, AccountTypeAlias, Account_TypeAlias)] [ValidateSet(AccountTypeString.StandardLRS, AccountTypeString.StandardZRS, AccountTypeString.StandardGRS, AccountTypeString.StandardRAGRS, AccountTypeString.PremiumLRS, IgnoreCase = true)] public string SkuName { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Access Tier.")] [ValidateSet(AccountAccessTier.Hot, AccountAccessTier.Cool, IgnoreCase = true)] public string AccessTier { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Account Custom Domain.")] [ValidateNotNull] public string CustomDomainName { get; set; } [Parameter( Mandatory = false, HelpMessage = "To Use Sub Domain.")] [ValidateNotNullOrEmpty] public bool? UseSubDomain { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Service that will enable encryption.")] public EncryptionSupportServiceEnum? EnableEncryptionService { get; set; } [Parameter( Mandatory = false, HelpMessage = "Storage Service that will disable encryption.")] public EncryptionSupportServiceEnum? DisableEncryptionService { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account Tags.")] [AllowEmptyCollection] [ValidateNotNull] [Alias(TagsAlias)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage Account EnableHttpsTrafficOnly.")] public bool EnableHttpsTrafficOnly { get { return enableHttpsTrafficOnly.Value; } set { enableHttpsTrafficOnly = value; } } private bool? enableHttpsTrafficOnly = null; [Parameter(HelpMessage = "Whether to set Storage Account Encryption KeySource to Microsoft.Storage or not.", Mandatory = false, ParameterSetName = StorageEncryptionParameterSet)] public SwitchParameter StorageEncryption { get { return storageEncryption; } set { storageEncryption = value; } } private bool storageEncryption = false; [Parameter(HelpMessage = "Whether to set Storage Account encryption keySource to Microsoft.Keyvault or not. " + "If you specify KeyName, KeyVersion and KeyvaultUri, Storage Account Encryption KeySource will also be set to Microsoft.Keyvault weather this parameter is set or not.", Mandatory = false, ParameterSetName = KeyvaultEncryptionParameterSet)] public SwitchParameter KeyvaultEncryption { get { return keyvaultEncryption; } set { keyvaultEncryption = value; } } private bool keyvaultEncryption = false; [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyName", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyName { get; set; } [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyVersion", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyVersion { get; set; } [Parameter(HelpMessage = "Storage Account encryption keySource KeyVault KeyVaultUri", Mandatory = true, ParameterSetName = KeyvaultEncryptionParameterSet)] [ValidateNotNullOrEmpty] public string KeyVaultUri { get; set; } [Parameter( Mandatory = false, HelpMessage = "Generate and assign a new Storage Account Identity for this storage account for use with key management services like Azure KeyVault.")] public SwitchParameter AssignIdentity { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); if (ShouldProcess(this.Name, "Set Storage Account")) { if (this.force || this.AccessTier == null || ShouldContinue("Changing the access tier may result in additional charges. See (http://go.microsoft.com/fwlink/?LinkId=786482) to learn more.", "")) { StorageAccountUpdateParameters updateParameters = new StorageAccountUpdateParameters(); if (this.SkuName != null) { updateParameters.Sku = new Sku(ParseSkuName(this.SkuName)); } if (this.Tag != null) { Dictionary<string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(Tag, validate: true); updateParameters.Tags = tagDictionary ?? new Dictionary<string, string>(); } if (this.CustomDomainName != null) { updateParameters.CustomDomain = new CustomDomain() { Name = CustomDomainName, UseSubDomain = UseSubDomain }; } else if (UseSubDomain != null) { throw new System.ArgumentException(string.Format("UseSubDomain must be set together with CustomDomainName.")); } if (this.AccessTier != null) { updateParameters.AccessTier = ParseAccessTier(AccessTier); } if (enableHttpsTrafficOnly != null) { updateParameters.EnableHttpsTrafficOnly = enableHttpsTrafficOnly; } if (AssignIdentity.IsPresent) { updateParameters.Identity = new Identity(); } if (this.EnableEncryptionService != null || this.DisableEncryptionService != null || StorageEncryption || (ParameterSetName == KeyvaultEncryptionParameterSet)) { if (ParameterSetName == KeyvaultEncryptionParameterSet) { keyvaultEncryption = true; } updateParameters.Encryption = ParseEncryption(EnableEncryptionService, DisableEncryptionService, StorageEncryption, keyvaultEncryption, KeyName, KeyVersion, KeyVaultUri); } var updatedAccountResponse = this.StorageClient.StorageAccounts.Update( this.ResourceGroupName, this.Name, updateParameters); var storageAccount = this.StorageClient.StorageAccounts.GetProperties(this.ResourceGroupName, this.Name); WriteStorageAccount(storageAccount); } } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if !CLR2 using System.Linq.Expressions; #endif using System.Diagnostics; using System.Runtime.CompilerServices; //using Microsoft.Scripting.Generation; namespace System.Management.Automation.Interpreter { /// <summary> /// Manages creation of interpreted delegates. These delegates will get /// compiled if they are executed often enough. /// </summary> internal sealed class LightDelegateCreator { // null if we are forced to compile private readonly Interpreter _interpreter; private readonly Expression _lambda; // Adaptive compilation support: private Type _compiledDelegateType; private Delegate _compiled; private readonly object _compileLock = new object(); internal LightDelegateCreator(Interpreter interpreter, LambdaExpression lambda) { Assert.NotNull(lambda); _interpreter = interpreter; _lambda = lambda; } // internal LightDelegateCreator(Interpreter interpreter, LightLambdaExpression lambda) { // Assert.NotNull(lambda); // _interpreter = interpreter; // _lambda = lambda; // } internal Interpreter Interpreter { get { return _interpreter; } } private bool HasClosure { get { return _interpreter != null && _interpreter.ClosureSize > 0; } } internal bool HasCompiled { get { return _compiled != null; } } /// <summary> /// True if the compiled delegate has the same type as the lambda; /// false if the type was changed for interpretation. /// </summary> internal bool SameDelegateType { get { return _compiledDelegateType == DelegateType; } } public Delegate CreateDelegate() { return CreateDelegate(null); } internal Delegate CreateDelegate(StrongBox<object>[] closure) { if (_compiled != null) { // If the delegate type we want is not a Func/Action, we can't // use the compiled code directly. So instead just fall through // and create an interpreted LightLambda, which will pick up // the compiled delegate on its first run. // // Ideally, we would just rebind the compiled delegate using // Delegate.CreateDelegate. Unfortunately, it doesn't work on // dynamic methods. if (SameDelegateType) { return CreateCompiledDelegate(closure); } } if (_interpreter == null) { // We can't interpret, so force a compile Compile(null); Delegate compiled = CreateCompiledDelegate(closure); Debug.Assert(compiled.GetType() == DelegateType); return compiled; } // Otherwise, we'll create an interpreted LightLambda return new LightLambda(this, closure, _interpreter._compilationThreshold).MakeDelegate(DelegateType); } private Type DelegateType { get { LambdaExpression le = _lambda as LambdaExpression; if (le != null) { return le.Type; } return null; // return ((LightLambdaExpression)_lambda).Type; } } /// <summary> /// Used by LightLambda to get the compiled delegate. /// </summary> internal Delegate CreateCompiledDelegate(StrongBox<object>[] closure) { Debug.Assert(HasClosure == (closure != null)); if (HasClosure) { // We need to apply the closure to get the actual delegate. var applyClosure = (Func<StrongBox<object>[], Delegate>)_compiled; return applyClosure(closure); } return _compiled; } /// <summary> /// Create a compiled delegate for the LightLambda, and saves it so /// future calls to Run will execute the compiled code instead of /// interpreting. /// </summary> internal void Compile(object state) { if (_compiled != null) { return; } // Compilation is expensive, we only want to do it once. lock (_compileLock) { if (_compiled != null) { return; } // PerfTrack.NoteEvent(PerfTrack.Categories.Compiler, "Interpreted lambda compiled"); // Interpreter needs a standard delegate type. // So change the lambda's delegate type to Func<...> or // Action<...> so it can be called from the LightLambda.Run // methods. LambdaExpression lambda = (_lambda as LambdaExpression); // ?? (LambdaExpression)((LightLambdaExpression)_lambda).Reduce(); if (_interpreter != null) { _compiledDelegateType = GetFuncOrAction(lambda); lambda = Expression.Lambda(_compiledDelegateType, lambda.Body, lambda.Name, lambda.Parameters); } if (HasClosure) { _compiled = LightLambdaClosureVisitor.BindLambda(lambda, _interpreter.ClosureVariables); } else { _compiled = lambda.Compile(); } } } private static Type GetFuncOrAction(LambdaExpression lambda) { Type delegateType; bool isVoid = lambda.ReturnType == typeof(void); // if (isVoid && lambda.Parameters.Count == 2 && // lambda.Parameters[0].IsByRef && lambda.Parameters[1].IsByRef) { // return typeof(ActionRef<,>).MakeGenericType(lambda.Parameters.Map(p => p.Type)); // } else { Type[] types = lambda.Parameters.Map(static p => p.IsByRef ? p.Type.MakeByRefType() : p.Type); if (isVoid) { if (Expression.TryGetActionType(types, out delegateType)) { return delegateType; } } else { types = types.AddLast(lambda.ReturnType); if (Expression.TryGetFuncType(types, out delegateType)) { return delegateType; } } return lambda.Type; // } } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; using UnityEngine.VR; using System; using System.Collections; using System.Collections.Generic; using Leap.Unity.Attributes; namespace Leap.Unity { /// <summary> /// Implements spatial alignment of cameras and synchronization with images. /// </summary> public class LeapVRTemporalWarping : MonoBehaviour { private const int DEFAULT_WARP_ADJUSTMENT = 17; private const long MAX_LATENCY = 200000; #region Inspector [SerializeField] private LeapServiceProvider provider; [Tooltip("The transform that represents the head object.")] [SerializeField] private Transform _headTransform; [Tooltip("The transform that is the anchor that tracking movement is relative to. Can be null if head motion is in world space.")] [SerializeField] private Transform _trackingAnchor; // Spatial recalibration [Tooltip("Key to recenter the VR tracking space.")] [SerializeField] private KeyCode _recenter = KeyCode.R; [Tooltip("Allows smooth enabling or disabling of the Image-Warping feature. Usually should match rotation warping.")] [Range(0, 1)] [SerializeField] private float _tweenImageWarping = 0f; public float tweenImageWarping { get { return _tweenImageWarping; } set { _tweenImageWarping = Mathf.Clamp01(value); } } [Tooltip("Allows smooth enabling or disabling of the Rotational warping of Leap Space. Usually should match image warping.")] [Range(0, 1)] [SerializeField] private float _tweenRotationalWarping = 0f; public float tweenRotationalWarping { get { return _tweenRotationalWarping; } set { _tweenRotationalWarping = Mathf.Clamp01(value); } } [Tooltip("Allows smooth enabling or disabling of the Positional warping of Leap Space. Usually should be disabled when using image warping.")] [Range(0, 1)] [SerializeField] private float _tweenPositionalWarping = 0f; public float tweenPositionalWarping { get { return _tweenPositionalWarping; } set { _tweenPositionalWarping = Mathf.Clamp01(value); } } [Tooltip("Controls when this script synchronizes the time warp of images. Use LowLatency for VR, and SyncWithImages for AR.")] [SerializeField] private SyncMode _syncMode = SyncMode.LOW_LATENCY; public SyncMode temporalSyncMode { get { return _syncMode; } set { _syncMode = value; } } [Header("Advanced")] [Tooltip("Forces an update of the temporal warping to happen in Late Update using the existing head transform. Should not be enabled if you " + "are using the default Unity VR integration!")] [SerializeField] private bool _forceCustomUpdate = false; // Manual Time Alignment [Tooltip("Allow manual adjustment of the rewind time.")] [SerializeField] private bool _allowManualTimeAlignment; [Tooltip("Time in milliseconds between the current frame's Leap position (offset from " + "the headset) and the time at which the Leap frame was captured. This " + "prevents 'swimming' behavior when the headset moves and the user's hands " + "don't. This value can be tuned if using a non-standard VR headset.")] [SerializeField] private int _customWarpAdjustment = DEFAULT_WARP_ADJUSTMENT; //Milliseconds public int warpingAdjustment { get { if (_allowManualTimeAlignment) { return _customWarpAdjustment; } else { return DEFAULT_WARP_ADJUSTMENT; } } } [SerializeField] private KeyCode _unlockHold = KeyCode.RightShift; [SerializeField] private KeyCode _moreRewind = KeyCode.LeftArrow; [SerializeField] private KeyCode _lessRewind = KeyCode.RightArrow; // Manual Device Offset private const float DEFAULT_DEVICE_OFFSET_Y_AXIS = 0f; private const float DEFAULT_DEVICE_OFFSET_Z_AXIS = 0.12f; private const float DEFAULT_DEVICE_TILT_X_AXIS = 5f; [Tooltip("Allow manual adjustment of the Leap device's virtual offset and tilt. These " + "settings can be used to match the physical position and orientation of the " + "Leap Motion sensor on a tracked device it is mounted on (such as a VR " + "headset.)")] [SerializeField, OnEditorChange("allowManualDeviceOffset")] private bool _allowManualDeviceOffset; public bool allowManualDeviceOffset { get { return _allowManualDeviceOffset; } set { _allowManualDeviceOffset = value; if (!_allowManualDeviceOffset) { deviceOffsetYAxis = DEFAULT_DEVICE_OFFSET_Y_AXIS; deviceOffsetZAxis = DEFAULT_DEVICE_OFFSET_Z_AXIS; deviceTiltXAxis = DEFAULT_DEVICE_TILT_X_AXIS; } } } [Tooltip("Adjusts the Leap Motion device's virtual height offset from the tracked " + "headset position.")] [SerializeField] [Range(-0.5F, 0.5F)] private float _deviceOffsetYAxis = DEFAULT_DEVICE_OFFSET_Y_AXIS; public float deviceOffsetYAxis { get { return _deviceOffsetYAxis; } set { _deviceOffsetYAxis = value; } } [Tooltip("Adjusts the Leap Motion device's virtual depth offset from the tracked " + "headset position.")] [SerializeField] [Range(-0.5F, 0.5F)] private float _deviceOffsetZAxis = DEFAULT_DEVICE_OFFSET_Z_AXIS; public float deviceOffsetZAxis { get { return _deviceOffsetZAxis; } set { _deviceOffsetZAxis = value; } } [Tooltip("Adjusts the Leap Motion device's virtual X axis tilt.")] [SerializeField] [Range(-90.0F, 90.0F)] private float _deviceTiltXAxis = DEFAULT_DEVICE_TILT_X_AXIS; public float deviceTiltXAxis { get { return _deviceTiltXAxis; } set { _deviceTiltXAxis = value; } } #endregion #region Public API /// <summary> /// Provides the position of a Leap Anchor at a given Leap Time. Cannot extrapolate. /// </summary> public bool TryGetWarpedTransform(WarpedAnchor anchor, out Vector3 rewoundPosition, out Quaternion rewoundRotation, long leapTime) { // Operation is only valid if we have a head transform. if (_headTransform == null) { rewoundPosition = Vector3.one; rewoundRotation = Quaternion.identity; return false; } // Prepare past transform data. TransformData past = transformAtTime((leapTime - warpingAdjustment * 1000) + (_syncMode == SyncMode.SYNC_WITH_IMAGES ? 20000 : 0)); // Prepare device offset parameters. Quaternion deviceTilt = Quaternion.Euler(deviceTiltXAxis, 0f, 0f); Vector3 deviceOffset = new Vector3(0f, deviceOffsetYAxis, deviceOffsetZAxis).CompMul(this.transform.lossyScale); // TODO: We no longer use deviceInfo.forwardOffset. We should consider removing it // entirely or more approrpriately when we collapse the rig hierarchy. 9/1/17 // Rewind position and rotation. if (_trackingAnchor == null) { rewoundRotation = past.localRotation * deviceTilt; rewoundPosition = past.localPosition + rewoundRotation * deviceOffset; } else { rewoundRotation = _trackingAnchor.rotation * past.localRotation * deviceTilt; rewoundPosition = _trackingAnchor.TransformPoint(past.localPosition) + rewoundRotation * deviceOffset; } // Move position if we are left-eye-only or right-eye-only. switch (anchor) { case WarpedAnchor.CENTER: break; case WarpedAnchor.LEFT: rewoundPosition += rewoundRotation * Vector3.left * _deviceInfo.baseline * 0.5f; break; case WarpedAnchor.RIGHT: rewoundPosition += rewoundRotation * Vector3.right * _deviceInfo.baseline * 0.5f; break; default: throw new Exception("Unexpected Rewind Type " + anchor); } return true; } public bool TryGetWarpedTransform(WarpedAnchor anchor, out Vector3 rewoundPosition, out Quaternion rewoundRotation) { long timestamp = provider.imageTimeStamp; if (TryGetWarpedTransform(anchor, out rewoundPosition, out rewoundRotation, timestamp)) { return true; } rewoundPosition = Vector3.zero; rewoundRotation = Quaternion.identity; return false; } /// <summary> /// Use this method when not using Unity default VR integration. This method should be called directly after /// the head transform has been updated using your input tracking solution. /// </summary> public void ManuallyUpdateTemporalWarping() { if (_trackingAnchor == null) { updateHistory(_headTransform.position, _headTransform.rotation); updateTemporalWarping(_headTransform.position, _headTransform.rotation); } else { updateHistory(_trackingAnchor.InverseTransformPoint(_headTransform.position), Quaternion.Inverse(_trackingAnchor.rotation) * _headTransform.rotation); } } #endregion #region Unity Events protected void Reset() { _headTransform = transform.parent; if (_headTransform != null) { _trackingAnchor = _headTransform.parent; } } protected void OnValidate() { if (_headTransform == null) { _headTransform = transform.parent; } if (!_allowManualTimeAlignment) { _customWarpAdjustment = DEFAULT_WARP_ADJUSTMENT; } #if UNITY_EDITOR if (_headTransform != null && UnityEditor.PlayerSettings.virtualRealitySupported) { _trackingAnchor = _headTransform.parent; } #endif } protected void OnEnable() { LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams; //avoid multiple subscription LeapVRCameraControl.OnValidCameraParams += onValidCameraParams; } protected void OnDisable() { LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams; } protected void Start() { if (provider.IsConnected()) { _deviceInfo = provider.GetDeviceInfo(); _shouldSetLocalPosition = true; LeapVRCameraControl.OnValidCameraParams += onValidCameraParams; } else { StartCoroutine(waitForConnection()); Controller controller = provider.GetLeapController(); controller.Device += OnDevice; } } private IEnumerator waitForConnection() { while (!provider.IsConnected()) { yield return null; } LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams; //avoid multiple subscription LeapVRCameraControl.OnValidCameraParams += onValidCameraParams; } private bool _shouldSetLocalPosition = false; protected void OnDevice(object sender, DeviceEventArgs args) { _deviceInfo = provider.GetDeviceInfo(); _shouldSetLocalPosition = true; //Get a callback right as rendering begins for this frame so we can update the history and warping. LeapVRCameraControl.OnValidCameraParams -= onValidCameraParams; //avoid multiple subscription LeapVRCameraControl.OnValidCameraParams += onValidCameraParams; } protected void Update() { if (_shouldSetLocalPosition) { transform.localPosition = transform.forward * _deviceInfo.forwardOffset; _shouldSetLocalPosition = false; } if (Input.GetKeyDown(_recenter) && UnityEngine.XR.XRSettings.enabled && UnityEngine.XR.XRDevice.isPresent) { UnityEngine.XR.InputTracking.Recenter(); } // Manual Time Alignment if (_allowManualTimeAlignment) { if (_unlockHold == KeyCode.None || Input.GetKey(_unlockHold)) { if (Input.GetKeyDown(_moreRewind)) { _customWarpAdjustment += 1; } if (Input.GetKeyDown(_lessRewind)) { _customWarpAdjustment -= 1; } } } } protected void LateUpdate() { if (_forceCustomUpdate) { ManuallyUpdateTemporalWarping(); } else if (UnityEngine.XR.XRSettings.enabled) { updateTemporalWarping(UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.CenterEye), UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.CenterEye)); } } private void onValidCameraParams(LeapVRCameraControl.CameraParams cameraParams) { _projectionMatrix = cameraParams.ProjectionMatrix; if (UnityEngine.XR.XRSettings.enabled) { if (provider != null) { updateHistory(UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.CenterEye), UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.CenterEye)); } if (_syncMode == SyncMode.LOW_LATENCY) { updateTemporalWarping(UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.CenterEye), UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.CenterEye)); } } } #endregion #region Temporal Warping private LeapDeviceInfo _deviceInfo; private Matrix4x4 _projectionMatrix; private List<TransformData> _history = new List<TransformData>(); private void updateHistory(Vector3 currLocalPosition, Quaternion currLocalRotation) { long leapNow = provider.GetLeapController().Now(); _history.Add(new TransformData() { leapTime = leapNow, localPosition = currLocalPosition, localRotation = currLocalRotation }); // Reduce history length while (_history.Count > 0 && MAX_LATENCY < leapNow - _history[0].leapTime) { _history.RemoveAt(0); } } private void updateTemporalWarping(Vector3 currLocalPosition, Quaternion currLocalRotation) { if (_trackingAnchor == null || provider.GetLeapController() == null) { return; } Vector3 currCenterPos = _trackingAnchor.TransformPoint(currLocalPosition); Quaternion currCenterRot = _trackingAnchor.rotation * currLocalRotation; //Get the transform at the time when the latest frame was captured long rewindTime = provider.CurrentFrame.Timestamp - warpingAdjustment * 1000; long imageRewindTime = provider.imageTimeStamp - warpingAdjustment * 1000; TransformData imagePast = transformAtTime(imageRewindTime); Quaternion imagePastCenterRot = _trackingAnchor.rotation * imagePast.localRotation; //Apply only a rotation ~ assume all objects are infinitely distant Quaternion imageReferenceRotation = Quaternion.Slerp(currCenterRot, imagePastCenterRot, _tweenImageWarping); Quaternion imageQuatWarp = Quaternion.Inverse(currCenterRot) * imageReferenceRotation; imageQuatWarp = Quaternion.Euler(imageQuatWarp.eulerAngles.x, imageQuatWarp.eulerAngles.y, -imageQuatWarp.eulerAngles.z); Matrix4x4 imageMatWarp = _projectionMatrix * Matrix4x4.TRS(Vector3.zero, imageQuatWarp, Vector3.one) * _projectionMatrix.inverse; Shader.SetGlobalMatrix("_LeapGlobalWarpedOffset", imageMatWarp); TransformData past = transformAtTime(rewindTime); Vector3 pastCenterPos = _trackingAnchor.TransformPoint(past.localPosition); Quaternion pastCenterRot = _trackingAnchor.rotation * past.localRotation; transform.position = Vector3.Lerp(currCenterPos, pastCenterPos, _tweenPositionalWarping); transform.rotation = Quaternion.Slerp(currCenterRot, pastCenterRot, _tweenRotationalWarping); transform.position += transform.forward * deviceOffsetZAxis; } /* Returns the VR Center Eye Transform information interpolated to the given leap timestamp. If the desired * timestamp is outside of the recorded range, interpolation will fail and the returned transform will not * have the desired time. */ private TransformData transformAtTime(long time) { if (_history.Count == 0) { return new TransformData() { leapTime = 0, localPosition = Vector3.zero, localRotation = Quaternion.identity }; } if (_history[0].leapTime >= time) { // Expect this when using LOW LATENCY image retrieval, which can yield negative latency estimates due to incorrect clock synchronization return _history[0]; } int t = 1; while (t < _history.Count && _history[t].leapTime <= time) { t++; } if (!(t < _history.Count)) { // Expect this for initial frames which will have a very low frame rate return _history[_history.Count - 1]; } return TransformData.Lerp(_history[t - 1], _history[t], time); } #endregion #region Support public enum WarpedAnchor { CENTER, LEFT, RIGHT, } public enum SyncMode { /* SyncWithImages causes both Images and the Transform to be updated at the same time during LateUpdate. This causes * the images to line up properly, but the images will lag behind the virtual world, causing drift. */ SYNC_WITH_IMAGES, /* LowLatency causes the Images to be warped directly prior to rendering, causing them to line up better with virtual * objects. Since transforms cannot be modified at this point in the update step, the Transform will still be updated * during LateUpdate, causing a misalignment between images and leap space. */ LOW_LATENCY } protected struct TransformData { public long leapTime; // microseconds public Vector3 localPosition; //meters public Quaternion localRotation; //magic public static TransformData Lerp(TransformData from, TransformData to, long time) { if (from.leapTime == to.leapTime) { return from; } float fraction = (float)(time - from.leapTime) / (float)(to.leapTime - from.leapTime); return new TransformData() { leapTime = time, localPosition = Vector3.Lerp(from.localPosition, to.localPosition, fraction), localRotation = Quaternion.Slerp(from.localRotation, to.localRotation, fraction) }; } } #endregion } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: Section.cs // // Description: Section is representing a portion of a document in which // certain page formatting properties can be changed, such as line numbering, // number of columns, headers and footers. // // History: // 05/05/2003 : [....] - moving from Avalon branch. // //--------------------------------------------------------------------------- using System; using System.Windows; using System.Security; using System.Windows.Documents; using System.Windows.Media; using MS.Internal.Text; using MS.Internal.PtsHost.UnsafeNativeMethods; namespace MS.Internal.PtsHost { /// <summary> /// Section is representing a portion of a document in which certain page /// formatting properties can be changed, such as line numbering, /// number of columns, headers and footers. /// </summary> internal sealed class Section : UnmanagedHandle { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="structuralCache"> /// Content's structural cache /// </param> internal Section(StructuralCache structuralCache) : base(structuralCache.PtsContext) { _structuralCache = structuralCache; } /// <summary> /// Dispose unmanaged resources. /// </summary> public override void Dispose() { DestroyStructure(); base.Dispose(); } #endregion Constructors // ------------------------------------------------------------------ // // PTS callbacks // // ------------------------------------------------------------------ #region PTS callbacks /// <summary> /// Indicates whether to skip a page /// </summary> /// <param name="fSkip"> /// OUT: skip page due to odd/even page issue /// </param> internal void FSkipPage( out int fSkip) { // Never skip a page fSkip = PTS.False; } // ------------------------------------------------------------------ // GetPageDimensions // ------------------------------------------------------------------ /// <summary> /// Get page dimensions /// </summary> /// <param name="fswdir"> /// OUT: direction of main text /// </param> /// <param name="fHeaderFooterAtTopBottom"> /// OUT: header/footer position on the page /// </param> /// <param name="durPage"> /// OUT: page width /// </param> /// <param name="dvrPage"> /// OUT: page height /// </param> /// <param name="fsrcMargin"> /// OUT: rectangle within page margins /// </param> internal void GetPageDimensions( out uint fswdir, out int fHeaderFooterAtTopBottom, out int durPage, out int dvrPage, ref PTS.FSRECT fsrcMargin) { // Set page dimentions Size pageSize = _structuralCache.CurrentFormatContext.PageSize; durPage = TextDpi.ToTextDpi(pageSize.Width); dvrPage = TextDpi.ToTextDpi(pageSize.Height); // Set page margin Thickness pageMargin = _structuralCache.CurrentFormatContext.PageMargin; TextDpi.EnsureValidPageMargin(ref pageMargin, pageSize); fsrcMargin.u = TextDpi.ToTextDpi(pageMargin.Left); fsrcMargin.v = TextDpi.ToTextDpi(pageMargin.Top); fsrcMargin.du = durPage - TextDpi.ToTextDpi(pageMargin.Left + pageMargin.Right); fsrcMargin.dv = dvrPage - TextDpi.ToTextDpi(pageMargin.Top + pageMargin.Bottom); StructuralCache.PageFlowDirection = (FlowDirection)_structuralCache.PropertyOwner.GetValue(FrameworkElement.FlowDirectionProperty); fswdir = PTS.FlowDirectionToFswdir(StructuralCache.PageFlowDirection); // fHeaderFooterAtTopBottom = PTS.False; } /// <summary> /// Get justification properties /// </summary> /// <param name="rgnms"> /// IN: array of the section names on the page /// </param> /// <param name="cnms"> /// IN: number of sections on the page /// </param> /// <param name="fLastSectionNotBroken"> /// IN: is last section on the page broken? /// </param> /// <param name="fJustify"> /// OUT: apply justification/alignment to the page? /// </param> /// <param name="fskal"> /// OUT: kind of vertical alignment for the page /// </param> /// <param name="fCancelAtLastColumn"> /// OUT: cancel justification for the last column of the page? /// </param> /// <SecurityNote> /// Critical, because it is unsafe method. /// </SecurityNote> [SecurityCritical] internal unsafe void GetJustificationProperties( IntPtr* rgnms, int cnms, int fLastSectionNotBroken, out int fJustify, out PTS.FSKALIGNPAGE fskal, out int fCancelAtLastColumn) { // NOTE: use the first section to report values (array is only for word compat). fJustify = PTS.False; fCancelAtLastColumn = PTS.False; fskal = PTS.FSKALIGNPAGE.fskalpgTop; } /// <summary> /// Get next section /// </summary> /// <param name="fSuccess"> /// OUT: next section exists /// </param> /// <param name="nmsNext"> /// OUT: name of the next section /// </param> internal void GetNextSection( out int fSuccess, out IntPtr nmsNext) { fSuccess = PTS.False; nmsNext = IntPtr.Zero; } // ------------------------------------------------------------------ // GetSectionProperties // ------------------------------------------------------------------ /// <summary> /// Get section properties /// </summary> /// <param name="fNewPage"> /// OUT: stop page before this section? /// </param> /// <param name="fswdir"> /// OUT: direction of this section /// </param> /// <param name="fApplyColumnBalancing"> /// OUT: apply column balancing to this section? /// </param> /// <param name="ccol"> /// OUT: number of columns in the main text segment /// </param> /// <param name="cSegmentDefinedColumnSpanAreas"> /// OUT: number of segment-defined columnspan areas /// </param> /// <param name="cHeightDefinedColumnSpanAreas"> /// OUT: number of height-defined columnsapn areas /// </param> internal void GetSectionProperties( out int fNewPage, out uint fswdir, out int fApplyColumnBalancing, out int ccol, out int cSegmentDefinedColumnSpanAreas, out int cHeightDefinedColumnSpanAreas) { ColumnPropertiesGroup columnProperties = new ColumnPropertiesGroup(Element); Size pageSize = _structuralCache.CurrentFormatContext.PageSize; double lineHeight = DynamicPropertyReader.GetLineHeightValue(Element); Thickness pageMargin = _structuralCache.CurrentFormatContext.PageMargin; double pageFontSize = (double)_structuralCache.PropertyOwner.GetValue(Block.FontSizeProperty); FontFamily pageFontFamily = (FontFamily)_structuralCache.PropertyOwner.GetValue(Block.FontFamilyProperty); bool enableColumns = _structuralCache.CurrentFormatContext.FinitePage; fNewPage = PTS.False; // Since only one section is supported, don't force page break before. fswdir = PTS.FlowDirectionToFswdir((FlowDirection)_structuralCache.PropertyOwner.GetValue(FrameworkElement.FlowDirectionProperty)); fApplyColumnBalancing = PTS.False; ccol = PtsHelper.CalculateColumnCount(columnProperties, lineHeight, pageSize.Width - (pageMargin.Left + pageMargin.Right), pageFontSize, pageFontFamily, enableColumns); cSegmentDefinedColumnSpanAreas = 0; cHeightDefinedColumnSpanAreas = 0; } /// <summary> /// Get main TextSegment /// </summary> /// <param name="nmSegment"> /// OUT: name of the main text segment for this section /// </param> internal void GetMainTextSegment( out IntPtr nmSegment) { if (_mainTextSegment == null) { // Create the main text segment _mainTextSegment = new ContainerParagraph(Element, _structuralCache); } nmSegment = _mainTextSegment.Handle; } /// <summary> /// Get header segment /// </summary> /// <param name="pfsbrpagePrelim"> /// IN: ptr to page break record of main page /// </param> /// <param name="fswdir"> /// IN: direction for dvrMaxHeight/dvrFromEdge /// </param> /// <param name="fHeaderPresent"> /// OUT: is there header on this page? /// </param> /// <param name="fHardMargin"> /// OUT: does margin increase with header? /// </param> /// <param name="dvrMaxHeight"> /// OUT: maximum size of header /// </param> /// <param name="dvrFromEdge"> /// OUT: distance from top edge of the paper /// </param> /// <param name="fswdirHeader"> /// OUT: direction for header /// </param> /// <param name="nmsHeader"> /// OUT: name of header segment /// </param> internal void GetHeaderSegment( IntPtr pfsbrpagePrelim, uint fswdir, out int fHeaderPresent, out int fHardMargin, out int dvrMaxHeight, out int dvrFromEdge, out uint fswdirHeader, out IntPtr nmsHeader) { fHeaderPresent = PTS.False; fHardMargin = PTS.False; dvrMaxHeight = dvrFromEdge = 0; fswdirHeader = fswdir; nmsHeader = IntPtr.Zero; } /// <summary> /// Get footer segment /// </summary> /// <param name="pfsbrpagePrelim"> /// IN: ptr to page break record of main page /// </param> /// <param name="fswdir"> /// IN: direction for dvrMaxHeight/dvrFromEdge /// </param> /// <param name="fFooterPresent"> /// OUT: is there footer on this page? /// </param> /// <param name="fHardMargin"> /// OUT: does margin increase with footer? /// </param> /// <param name="dvrMaxHeight"> /// OUT: maximum size of footer /// </param> /// <param name="dvrFromEdge"> /// OUT: distance from bottom edge of the paper /// </param> /// <param name="fswdirFooter"> /// OUT: direction for footer /// </param> /// <param name="nmsFooter"> /// OUT: name of footer segment /// </param> internal void GetFooterSegment( IntPtr pfsbrpagePrelim, uint fswdir, out int fFooterPresent, out int fHardMargin, out int dvrMaxHeight, out int dvrFromEdge, out uint fswdirFooter, out IntPtr nmsFooter) { fFooterPresent = PTS.False; fHardMargin = PTS.False; dvrMaxHeight = dvrFromEdge = 0; fswdirFooter = fswdir; nmsFooter = IntPtr.Zero; } /// <summary> /// Get section column info /// </summary> /// <param name="fswdir"> /// IN: direction of section /// </param> /// <param name="ncol"> /// IN: size of the preallocated fscolinfo array /// </param> /// <param name="pfscolinfo"> /// OUT: array of the colinfo structures /// </param> /// <param name="ccol"> /// OUT: actual number of the columns in the segment /// </param> /// <SecurityNote> /// Critical, because: /// a) calls Critical function GetColumnsInfo, /// b) it is unsafe method. /// </SecurityNote> [SecurityCritical] internal unsafe void GetSectionColumnInfo( uint fswdir, int ncol, PTS.FSCOLUMNINFO* pfscolinfo, out int ccol) { ColumnPropertiesGroup columnProperties = new ColumnPropertiesGroup(Element); Size pageSize = _structuralCache.CurrentFormatContext.PageSize; double lineHeight = DynamicPropertyReader.GetLineHeightValue(Element); Thickness pageMargin = _structuralCache.CurrentFormatContext.PageMargin; double pageFontSize = (double)_structuralCache.PropertyOwner.GetValue(Block.FontSizeProperty); FontFamily pageFontFamily = (FontFamily)_structuralCache.PropertyOwner.GetValue(Block.FontFamilyProperty); bool enableColumns = _structuralCache.CurrentFormatContext.FinitePage; ccol = ncol; PtsHelper.GetColumnsInfo(columnProperties, lineHeight, pageSize.Width - (pageMargin.Left + pageMargin.Right), pageFontSize, pageFontFamily, ncol, pfscolinfo, enableColumns); } /// <summary> /// Get end note segment /// </summary> /// <param name="fEndnotesPresent"> /// OUT: are there endnotes for this segment? /// </param> /// <param name="nmsEndnotes"> /// OUT: name of endnote segment /// </param> internal void GetEndnoteSegment( out int fEndnotesPresent, out IntPtr nmsEndnotes) { fEndnotesPresent = PTS.False; nmsEndnotes = IntPtr.Zero; } /// <summary> /// Get end note separators /// </summary> /// <param name="nmsEndnoteSeparator"> /// OUT: name of the endnote separator segment /// </param> /// <param name="nmsEndnoteContSeparator"> /// OUT: name of endnote cont separator segment /// </param> /// <param name="nmsEndnoteContNotice"> /// OUT: name of the endnote cont notice segment /// </param> internal void GetEndnoteSeparators( out IntPtr nmsEndnoteSeparator, out IntPtr nmsEndnoteContSeparator, out IntPtr nmsEndnoteContNotice) { nmsEndnoteSeparator = IntPtr.Zero; nmsEndnoteContSeparator = IntPtr.Zero; nmsEndnoteContNotice = IntPtr.Zero; } #endregion PTS callbacks // ------------------------------------------------------------------ // // Internal Methods // // ------------------------------------------------------------------ #region Internal Methods /// <summary> /// Invalidate format caches accumulated in the section. /// </summary> internal void InvalidateFormatCache() { if (_mainTextSegment != null) { _mainTextSegment.InvalidateFormatCache(); } } /// <summary> /// Clear previously accumulated update info. /// </summary> internal void ClearUpdateInfo() { if (_mainTextSegment != null) { _mainTextSegment.ClearUpdateInfo(); } } /// <summary> /// Invalidate content's structural cache. /// </summary> internal void InvalidateStructure() { if (_mainTextSegment != null) { DtrList dtrs = _structuralCache.DtrList; if (dtrs != null) { _mainTextSegment.InvalidateStructure(dtrs[0].StartIndex); } } } /// <summary> /// Destroy content's structural cache. /// </summary> internal void DestroyStructure() { if (_mainTextSegment != null) { _mainTextSegment.Dispose(); _mainTextSegment = null; } } /// <summary> /// Update number of characters consumed by the main text segment. /// </summary> internal void UpdateSegmentLastFormatPositions() { if(_mainTextSegment != null) { _mainTextSegment.UpdateLastFormatPositions(); } } /// <summary> /// Can update section? /// </summary> internal bool CanUpdate { get { return _mainTextSegment != null; } } /// <summary> /// StructuralCache. /// </summary> internal StructuralCache StructuralCache { get { return _structuralCache; } } /// <summary> /// Element owner. /// </summary> internal DependencyObject Element { get { return _structuralCache.PropertyOwner; } } #endregion Internal Methods //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields /// <summary> /// Main text segment. /// </summary> private BaseParagraph _mainTextSegment; /// <summary> /// Structural cache. /// </summary> private readonly StructuralCache _structuralCache; #endregion Private Fields } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using FluentAssertions; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ToolPackage; using Microsoft.DotNet.Tools; using Microsoft.DotNet.Tools.Tool.Install; using Microsoft.DotNet.Tools.Tool.Uninstall; using Microsoft.DotNet.Tools.Tests.ComponentMocks; using Microsoft.DotNet.Tools.Test.Utilities; using Microsoft.Extensions.DependencyModel.Tests; using Microsoft.Extensions.EnvironmentAbstractions; using Xunit; using Parser = Microsoft.DotNet.Cli.Parser; using LocalizableStrings = Microsoft.DotNet.Tools.Tool.Uninstall.LocalizableStrings; using InstallLocalizableStrings = Microsoft.DotNet.Tools.Tool.Install.LocalizableStrings; using Microsoft.DotNet.ShellShim; namespace Microsoft.DotNet.Tests.Commands { public class ToolUninstallCommandTests { private readonly BufferedReporter _reporter; private readonly IFileSystem _fileSystem; private readonly EnvironmentPathInstructionMock _environmentPathInstructionMock; private const string PackageId = "global.tool.console.demo"; private const string PackageVersion = "1.0.4"; private const string ShimsDirectory = "shims"; private const string ToolsDirectory = "tools"; public ToolUninstallCommandTests() { _reporter = new BufferedReporter(); _fileSystem = new FileSystemMockBuilder().Build(); _environmentPathInstructionMock = new EnvironmentPathInstructionMock(_reporter, ShimsDirectory); } [Fact] public void GivenANonExistentPackageItErrors() { var packageId = "does.not.exist"; var command = CreateUninstallCommand($"-g {packageId}"); Action a = () => command.Execute(); a.ShouldThrow<GracefulException>() .And .Message .Should() .Be(string.Format(LocalizableStrings.ToolNotInstalled, packageId)); } [Fact] public void GivenAPackageItUninstalls() { CreateInstallCommand($"-g {PackageId}").Execute().Should().Be(0); _reporter .Lines .Last() .Should() .Contain(string.Format( InstallLocalizableStrings.InstallationSucceeded, ProjectRestorerMock.FakeCommandName, PackageId, PackageVersion)); var packageDirectory = new DirectoryPath(Path.GetFullPath(ToolsDirectory)) .WithSubDirectories(PackageId, PackageVersion); var shimPath = Path.Combine( ShimsDirectory, ProjectRestorerMock.FakeCommandName + (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : "")); _fileSystem.Directory.Exists(packageDirectory.Value).Should().BeTrue(); _fileSystem.File.Exists(shimPath).Should().BeTrue(); _reporter.Lines.Clear(); CreateUninstallCommand($"-g {PackageId}").Execute().Should().Be(0); _reporter .Lines .Single() .Should() .Contain(string.Format( LocalizableStrings.UninstallSucceeded, PackageId, PackageVersion)); _fileSystem.Directory.Exists(packageDirectory.Value).Should().BeFalse(); _fileSystem.File.Exists(shimPath).Should().BeFalse(); } [Fact] public void GivenAFailureToUninstallItLeavesItInstalled() { CreateInstallCommand($"-g {PackageId}").Execute().Should().Be(0); _reporter .Lines .Last() .Should() .Contain(string.Format( InstallLocalizableStrings.InstallationSucceeded, ProjectRestorerMock.FakeCommandName, PackageId, PackageVersion)); var packageDirectory = new DirectoryPath(Path.GetFullPath(ToolsDirectory)) .WithSubDirectories(PackageId, PackageVersion); var shimPath = Path.Combine( ShimsDirectory, ProjectRestorerMock.FakeCommandName + (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ".exe" : "")); _fileSystem.Directory.Exists(packageDirectory.Value).Should().BeTrue(); _fileSystem.File.Exists(shimPath).Should().BeTrue(); Action a = () => CreateUninstallCommand( options: $"-g {PackageId}", uninstallCallback: () => throw new IOException("simulated error")) .Execute(); a.ShouldThrow<GracefulException>() .And .Message .Should() .Be(string.Format( CommonLocalizableStrings.FailedToUninstallToolPackage, PackageId, "simulated error")); _fileSystem.Directory.Exists(packageDirectory.Value).Should().BeTrue(); _fileSystem.File.Exists(shimPath).Should().BeTrue(); } [Fact] public void WhenRunWithBothGlobalAndToolPathShowErrorMessage() { var uninstallCommand = CreateUninstallCommand($"-g --tool-path {Path.GetTempPath()} {PackageId}"); Action a = () => uninstallCommand.Execute(); a.ShouldThrow<GracefulException>() .And .Message .Should() .Be(LocalizableStrings.UninstallToolCommandInvalidGlobalAndToolPath); } [Fact] public void GivenAnInvalidToolPathItThrowsException() { var toolPath = "tool-path-does-not-exist"; var uninstallCommand = CreateUninstallCommand($"--tool-path {toolPath} {PackageId}"); Action a = () => uninstallCommand.Execute(); a.ShouldThrow<GracefulException>() .And .Message .Should() .Be(string.Format(LocalizableStrings.InvalidToolPathOption, toolPath)); } [Fact] public void WhenRunWithNeitherOfGlobalNorToolPathShowErrorMessage() { var uninstallCommand = CreateUninstallCommand(PackageId); Action a = () => uninstallCommand.Execute(); a.ShouldThrow<GracefulException>() .And .Message .Should() .Be(LocalizableStrings.UninstallToolCommandNeedGlobalOrToolPath); } private ToolInstallCommand CreateInstallCommand(string options) { ParseResult result = Parser.Instance.Parse("dotnet tool install " + options); var store = new ToolPackageStoreMock(new DirectoryPath(ToolsDirectory), _fileSystem); var packageInstallerMock = new ToolPackageInstallerMock( _fileSystem, store, new ProjectRestorerMock( _fileSystem, _reporter)); return new ToolInstallCommand( result["dotnet"]["tool"]["install"], result, (_) => (store, packageInstallerMock), (_) => new ShellShimRepository( new DirectoryPath(ShimsDirectory), fileSystem: _fileSystem, appHostShellShimMaker: new AppHostShellShimMakerMock(_fileSystem)), _environmentPathInstructionMock, _reporter); } private ToolUninstallCommand CreateUninstallCommand(string options, Action uninstallCallback = null) { ParseResult result = Parser.Instance.Parse("dotnet tool uninstall " + options); return new ToolUninstallCommand( result["dotnet"]["tool"]["uninstall"], result, (_) => new ToolPackageStoreMock( new DirectoryPath(ToolsDirectory), _fileSystem, uninstallCallback), (_) => new ShellShimRepository( new DirectoryPath(ShimsDirectory), fileSystem: _fileSystem, appHostShellShimMaker: new AppHostShellShimMakerMock(_fileSystem)), _reporter); } } }
/******************************************************************** 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. *********************************************************************/ #region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; using System.Collections.Generic; using Axiom.Animating; using Axiom.Core; using Axiom.MathLib; using Axiom.Graphics; namespace Multiverse.Serialization { /// <summary> /// Class to write out a skeleton in Ogre's xml format /// </summary> public class OgreXmlSkeletonWriter { #region Member variables private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(OgreXmlSkeletonWriter)); protected Skeleton skeleton; protected Stream stream; protected XmlDocument document; protected Matrix4 exportTransform = Matrix4.Identity; protected float exportScale = 1.0f; #endregion #region Constructors public OgreXmlSkeletonWriter(Stream data) { stream = data; } #endregion #region Methods public void Export(Skeleton skeleton, Matrix4 exportTransform) { this.exportTransform = exportTransform; float det = exportTransform.Determinant; this.exportScale = (float)Math.Pow(det, 1 / 3.0f); Export(skeleton); } public void Export(Skeleton skeleton) { // store a local reference to the mesh for modification this.skeleton = skeleton; this.document = new XmlDocument(); XmlNode skeletonNode = WriteSkeleton(); document.AppendChild(skeletonNode); document.Save(stream); } protected XmlNode WriteSkeleton() { XmlElement node = document.CreateElement("skeleton"); XmlNode childNode; // Write the bones childNode = WriteBones(); node.AppendChild(childNode); // Next write bone hierarchy childNode = WriteBoneHierarchy(); node.AppendChild(childNode); // Next write animations childNode = WriteAnimations(); node.AppendChild(childNode); return node; } protected XmlElement WriteBones() { XmlElement node = document.CreateElement("bones"); if (exportTransform != Matrix4.Identity) { Vector3 tmpTranslate = exportTransform.Translation; Quaternion tmpRotate = GetRotation(exportTransform); TransformSkeleton(exportTransform); } for (ushort i = 0; i < skeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); XmlElement childNode = WriteBone(bone); node.AppendChild(childNode); } return node; } protected XmlElement WriteBoneHierarchy() { XmlElement node = document.CreateElement("bonehierarchy"); for (ushort i = 0; i < skeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); if (bone.Parent != null) { XmlElement subNode = document.CreateElement("boneparent"); XmlAttribute attr; attr = document.CreateAttribute("bone"); attr.Value = bone.Name; subNode.Attributes.Append(attr); attr = document.CreateAttribute("parent"); attr.Value = bone.Parent.Name; subNode.Attributes.Append(attr); node.AppendChild(subNode); } } return node; } protected void TransformSkeleton(Matrix4 exportTransform) { Matrix4 invExportTransform = exportTransform.Inverse(); Dictionary<string, Matrix4> fullInverseBoneTransforms = new Dictionary<string, Matrix4>(); Skeleton newSkeleton = new Skeleton(skeleton.Name); // Construct new versions of the bones, and build // the inverse bind matrix that will be needed. for (ushort i = 0; i < skeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); Bone newBone = newSkeleton.CreateBone(bone.Name, bone.Handle); fullInverseBoneTransforms[bone.Name] = bone.BindDerivedInverseTransform; } // Build the parenting relationship for the new skeleton for (ushort i = 0; i < skeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); Bone newBone = newSkeleton.GetBone(i); Bone parentBone = (Bone)bone.Parent; if (parentBone != null) { Bone newParentBone = newSkeleton.GetBone(parentBone.Handle); newParentBone.AddChild(newBone); } } // Set the orientation and position for the various bones // B' = T * B * Tinv for (ushort i = 0; i < newSkeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); string boneName = bone.Name; string parentName = (bone.Parent == null) ? null : bone.Parent.Name; Matrix4 transform = GetLocalBindMatrix(fullInverseBoneTransforms, boneName, parentName, true); transform = exportTransform * transform * invExportTransform; Quaternion orientation = GetRotation(transform); Bone newBone = newSkeleton.GetBone(i); newBone.Orientation = orientation; newBone.Position = transform.Translation; //if (newBone.Name == "Lower_Torso_BIND_jjj") { // log.DebugFormat("New Bone Position: {0}", transform.Translation); //} } newSkeleton.SetBindingPose(); for (int i = 0; i < skeleton.AnimationCount; ++i) { Animation anim = skeleton.GetAnimation(i); Animation newAnim = newSkeleton.CreateAnimation(anim.Name, anim.Length); TransformAnimation(exportTransform, newAnim, anim, newSkeleton); } skeleton = newSkeleton; } protected void TransformAnimation(Matrix4 exportTransform, Animation newAnim, Animation anim, Skeleton newSkeleton) { foreach (NodeAnimationTrack track in anim.NodeTracks.Values) { NodeAnimationTrack newTrack = newAnim.CreateNodeTrack(track.Handle); Bone targetBone = (Bone)track.TargetNode; newTrack.TargetNode = newSkeleton.GetBone(targetBone.Handle); TransformTrack(exportTransform, newTrack, track, targetBone); } } protected void TransformTrack(Matrix4 exportTransform, NodeAnimationTrack newTrack, NodeAnimationTrack track, Bone bone) { Matrix4 invExportTransform = exportTransform.Inverse(); Bone oldNode = (Bone)track.TargetNode; Bone newNode = (Bone)newTrack.TargetNode; for (int i = 0; i < track.KeyFrames.Count; ++i) { TransformKeyFrame keyFrame = track.GetTransformKeyFrame(i); TransformKeyFrame newKeyFrame = newTrack.CreateNodeKeyFrame(keyFrame.Time); Quaternion oldOrientation = oldNode.Orientation * keyFrame.Rotation; Vector3 oldTranslation = oldNode.Position + keyFrame.Translate; Matrix4 oldTransform = Multiverse.MathLib.MathUtil.GetTransform(oldOrientation, oldTranslation); Matrix4 newTransform = exportTransform * oldTransform * invExportTransform; Quaternion newOrientation = GetRotation(newTransform); Vector3 newTranslation = newTransform.Translation; newKeyFrame.Rotation = newNode.Orientation.Inverse() * newOrientation; newKeyFrame.Translate = newTranslation - newNode.Position; //if (oldNode.Name == "Lower_Torso_BIND_jjj") { // log.DebugFormat("New translation: {0}; New Position: {1}", newTranslation, newNode.Position); //} } } #if COMPLEX_WAY protected void TransformSkeleton(Matrix4 unscaledTransform, float scale) { Matrix4 invExportTransform = unscaledTransform.Inverse(); Dictionary<string, Matrix4> fullInverseBoneTransforms = new Dictionary<string, Matrix4>(); Skeleton newSkeleton = new Skeleton(skeleton.Name); // Construct new versions of the bones, and build // the inverse bind matrix that will be needed. for (ushort i = 0; i < skeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); Bone newBone = newSkeleton.CreateBone(bone.Name, bone.Handle); fullInverseBoneTransforms[bone.Name] = bone.BindDerivedInverseTransform * invExportTransform; } // Build the parenting relationship for the new skeleton for (ushort i = 0; i < skeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); Bone newBone = newSkeleton.GetBone(i); Bone parentBone = (Bone)bone.Parent; if (parentBone != null) { Bone newParentBone = newSkeleton.GetBone(parentBone.Handle); newParentBone.AddChild(newBone); } } // Set the orientation and position for the various bones for (ushort i = 0; i < newSkeleton.BoneCount; ++i) { Bone bone = skeleton.GetBone(i); string boneName = bone.Name; string parentName = (bone.Parent == null) ? null : bone.Parent.Name; Matrix4 transform = GetLocalBindMatrix(fullInverseBoneTransforms, boneName, parentName, true); Quaternion orientation = GetRotation(transform); Bone newBone = newSkeleton.GetBone(i); newBone.Orientation = orientation; // newBone.Scale = transform.Scale; newBone.Position = scale * transform.Translation; } newSkeleton.SetBindingPose(); for (int i = 0; i < skeleton.AnimationCount; ++i) { Animation anim = skeleton.GetAnimation(i); Animation newAnim = newSkeleton.CreateAnimation(anim.Name, anim.Length); TransformAnimation(unscaledTransform, scale, newAnim, anim, newSkeleton); } skeleton = newSkeleton; } public List<Bone> GetOrderedBoneList(Bone parentBone, Skeleton skel) { List<Bone> rv = new List<Bone>(); // Get all the bones that are my children List<Bone> childBones = new List<Bone>(); for (ushort i = 0; i < skel.BoneCount; ++i) { Bone bone = skel.GetBone(i); if (bone.Parent == parentBone) childBones.Add(bone); } rv.AddRange(childBones); // For each of those bones, get their descendents foreach (Bone childBone in childBones) { List<Bone> bones = GetOrderedBoneList(childBone, skel); rv.AddRange(bones); } return rv; } protected void TransformAnimation(Matrix4 unscaledTransform, float scale, Animation newAnim, Animation anim, Skeleton newSkeleton) { // With the new idea I had for transforming these, I need the tracks // set up for the parent bones before I can handle the child bones. for (int i = 0; i < anim.Tracks.Count; ++i) { AnimationTrack track = anim.Tracks[i]; AnimationTrack newTrack = newAnim.CreateTrack(track.Handle); Bone targetBone = (Bone)track.TargetNode; newTrack.TargetNode = newSkeleton.GetBone(targetBone.Handle); } // This gets the ordered bone list, and transforms the tracks in // that order instead. List<Bone> orderedBoneList = GetOrderedBoneList(null, newSkeleton); foreach (Bone bone in orderedBoneList) TransformTrack(unscaledTransform, scale, newAnim, anim, bone); } protected AnimationTrack GetBoneTrack(Animation anim, ushort boneHandle) { for (int i = 0; i < anim.Tracks.Count; ++i) { AnimationTrack track = anim.Tracks[i]; Bone bone = (Bone)track.TargetNode; if (bone.Handle == boneHandle) return track; } return null; } protected void GetCompositeTransform(ref Quaternion orientation, ref Vector3 translation, Bone bone, Animation anim, int keyFrameIndex) { if (bone == null) return; Quaternion tmpOrient = Quaternion.Identity; Vector3 tmpTranslate = Vector3.Zero; GetCompositeTransform(ref tmpOrient, ref tmpTranslate, (Bone)bone.Parent, anim, keyFrameIndex); AnimationTrack track = GetBoneTrack(anim, bone.Handle); KeyFrame keyFrame = track.KeyFrames[keyFrameIndex]; orientation = tmpOrient * bone.Orientation * keyFrame.Rotation; translation = tmpTranslate + bone.Position + keyFrame.Translate; } protected void TransformTrack(Matrix4 unscaledTransform, float scale, Animation newAnim, Animation anim, Bone bone) { AnimationTrack track = GetBoneTrack(anim, bone.Handle); AnimationTrack newTrack = GetBoneTrack(newAnim, bone.Handle); Bone oldNode = (Bone)track.TargetNode; Bone newNode = (Bone)newTrack.TargetNode; Quaternion exportRotation = GetRotation(unscaledTransform); Vector3 exportTranslation = unscaledTransform.Translation; for (int i = 0; i < track.KeyFrames.Count; ++i) { KeyFrame keyFrame = track.KeyFrames[i]; Quaternion oldOrientation = Quaternion.Identity; Vector3 oldTranslation = Vector3.Zero; // Now build the composite transform for the old node GetCompositeTransform(ref oldOrientation, ref oldTranslation, oldNode, anim, i); Quaternion targetOrientation = exportRotation * oldOrientation; Vector3 targetTranslation = exportTranslation + scale * (exportRotation * oldTranslation); KeyFrame newKeyFrame = newTrack.CreateKeyFrame(keyFrame.Time); // we have a parent - where is it? Quaternion parentOrientation = Quaternion.Identity; Vector3 parentTranslation = Vector3.Zero; GetCompositeTransform(ref parentOrientation, ref parentTranslation, (Bone)newNode.Parent, newAnim, i); newKeyFrame.Rotation = newNode.Orientation.Inverse() * parentOrientation.Inverse() * targetOrientation; newKeyFrame.Translate = (-1 * newNode.Position) + (-1 * parentTranslation) + targetTranslation; } } #endif public static Matrix4 ScaleMatrix(Matrix4 transform, float scale) { Matrix4 rv = transform; for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) { rv[row, col] *= scale; } } return rv; } public static float GetScale(Matrix4 transform) { Matrix3 tmp = new Matrix3(transform.m00, transform.m01, transform.m02, transform.m10, transform.m11, transform.m12, transform.m20, transform.m21, transform.m22); return (float)Math.Pow(tmp.Determinant, 1 / 3.0f); } public static Quaternion GetRotation(Matrix4 transform) { Matrix3 tmp = new Matrix3(transform.m00, transform.m01, transform.m02, transform.m10, transform.m11, transform.m12, transform.m20, transform.m21, transform.m22); float scale = (float)Math.Pow(tmp.Determinant, 1 / 3.0f); tmp = tmp * scale; Quaternion rv = Quaternion.Identity; rv.FromRotationMatrix(tmp); return rv; } /// <summary> /// Get the transform of the child bone at bind pose relative to /// the parent bone at bind pose. Note that this could be different /// for a different controller, but that I assume that it will be /// the same for now, and just assert that all skinned objects use /// the same bind pose for the skeleton. /// Since the xml skeleton format does not support scale, these /// local bind matrices all contain the export scale. /// </summary> /// <param name="boneName">Name of the bone</param> /// <param name="parentName">Name of the parent bone</param> /// <param name="debug">Set this to true to dump the matrices</param> /// <returns></returns> protected Matrix4 GetLocalBindMatrix(Dictionary<string, Matrix4> invBindMatrices, string boneName, string parentName, bool debug) { if (!invBindMatrices.ContainsKey(boneName)) { log.WarnFormat("No skin seems to use bone: {0}", boneName); return Matrix4.Identity; } Matrix4 transform = invBindMatrices[boneName].Inverse(); log.DebugFormat("BIND_MATRIX[{0}] = \n{1}", boneName, transform); if (parentName != null) { Matrix4 parInvTrans = invBindMatrices[parentName]; parInvTrans = parInvTrans * (1 / parInvTrans.Determinant); transform = parInvTrans * transform; } log.DebugFormat("LOCAL_BIND_MATRIX[{0}] = \n{1}", boneName, transform); return transform; } protected XmlElement WriteBone(Bone bone) { XmlElement node = document.CreateElement("bone"); XmlAttribute attr; attr = document.CreateAttribute("id"); attr.Value = bone.Handle.ToString(); node.Attributes.Append(attr); attr = document.CreateAttribute("name"); attr.Value = bone.Name; node.Attributes.Append(attr); XmlElement childNode; childNode = WritePosition(bone.Position); node.AppendChild(childNode); childNode = WriteRotation(bone.Orientation); node.AppendChild(childNode); return node; } protected XmlElement WritePosition(Vector3 pos) { return WriteVector3("position", pos); } protected XmlElement WriteRotation(Quaternion rot) { return WriteQuaternion("rotation", rot); } protected XmlElement WriteRotate(Quaternion rot) { return WriteQuaternion("rotate", rot); } protected XmlElement WriteQuaternion(string elementName, Quaternion rot) { Vector3 axis = new Vector3(); float angle = 0; rot.ToAngleAxis(ref angle, ref axis); XmlElement node = document.CreateElement(elementName); XmlAttribute attr; attr = document.CreateAttribute("angle"); if (angle >= Math.PI && 2 * (float)Math.PI - angle < (float)Math.PI) { angle = 2 * (float)Math.PI - angle; axis = -1 * axis; Debug.Assert(angle < Math.PI); } Debug.Assert(angle < Math.PI + .0001); attr.Value = angle.ToString(); node.Attributes.Append(attr); XmlElement childNode = WriteAxis(axis); node.AppendChild(childNode); return node; } protected XmlElement WriteAxis(Vector3 axis) { return WriteVector3("axis", axis); } protected XmlElement WriteTranslate(Vector3 axis) { return WriteVector3("translate", axis); } protected XmlElement WriteVector3(string elementName, Vector3 vec) { XmlElement node = document.CreateElement(elementName); XmlAttribute attr; attr = document.CreateAttribute("x"); attr.Value = vec.x.ToString(); node.Attributes.Append(attr); attr = document.CreateAttribute("y"); attr.Value = vec.y.ToString(); node.Attributes.Append(attr); attr = document.CreateAttribute("z"); attr.Value = vec.z.ToString(); node.Attributes.Append(attr); return node; } protected XmlElement WriteAnimations() { XmlElement node = document.CreateElement("animations"); for (int i = 0; i < skeleton.AnimationCount; ++i) { Animation anim = skeleton.GetAnimation(i); XmlElement animNode = WriteAnimation(anim); node.AppendChild(animNode); } return node; } protected XmlElement WriteAnimation(Animation anim) { XmlElement node = document.CreateElement("animation"); XmlAttribute attr; attr = document.CreateAttribute("name"); attr.Value = anim.Name; node.Attributes.Append(attr); attr = document.CreateAttribute("length"); attr.Value = anim.Length.ToString(); node.Attributes.Append(attr); XmlElement tracksNode = document.CreateElement("tracks"); foreach (NodeAnimationTrack track in anim.NodeTracks.Values) { XmlElement trackNode = WriteTrack(track); tracksNode.AppendChild(trackNode); } node.AppendChild(tracksNode); return node; } protected XmlElement WriteTrack(NodeAnimationTrack track) { XmlElement node = document.CreateElement("track"); XmlAttribute attr; attr = document.CreateAttribute("bone"); attr.Value = track.TargetNode.Name; node.Attributes.Append(attr); XmlElement keyFramesNode = document.CreateElement("keyframes"); foreach (KeyFrame baseKeyFrame in track.KeyFrames) { TransformKeyFrame keyFrame = (TransformKeyFrame)baseKeyFrame; //if (track.TargetNode.Parent != null) // Debug.Assert(keyFrame.Translate.LengthSquared < .01); XmlElement keyFrameNode = WriteKeyFrame(keyFrame); keyFramesNode.AppendChild(keyFrameNode); } node.AppendChild(keyFramesNode); return node; } protected XmlElement WriteKeyFrame(TransformKeyFrame keyFrame) { XmlElement node = document.CreateElement("keyframe"); XmlAttribute attr; attr = document.CreateAttribute("time"); attr.Value = keyFrame.Time.ToString(); node.Attributes.Append(attr); XmlElement translate = WriteTranslate(keyFrame.Translate); node.AppendChild(translate); XmlElement rotate = WriteRotate(keyFrame.Rotation); node.AppendChild(rotate); return node; } #endregion #region Properties #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed class ExpressionTreeRewriter : ExprVisitorBase { public static ExprBinOp Rewrite(ExprBoundLambda expr) => new ExpressionTreeRewriter().VisitBoundLambda(expr); protected override Expr Dispatch(Expr expr) { Debug.Assert(expr != null); Expr result = base.Dispatch(expr); if (result == expr) { throw Error.InternalCompilerError(); } return result; } ///////////////////////////////////////////////////////////////////////////////// // Statement types. protected override Expr VisitASSIGNMENT(ExprAssignment assignment) { Debug.Assert(assignment != null); // For assignments, we either have a member assignment or an indexed assignment. //Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL()); Expr lhs; if (assignment.LHS is ExprProperty prop) { if (prop.OptionalArguments == null) { // Regular property. lhs = Visit(prop); } else { // Indexed assignment. Here we need to find the instance of the object, create the // PropInfo for the thing, and get the array of expressions that make up the index arguments. // // The LHS becomes Expression.Property(instance, indexerInfo, arguments). Expr instance = Visit(prop.MemberGroup.OptionalObject); Expr propInfo = ExprFactory.CreatePropertyInfo(prop.PropWithTypeSlot.Prop(), prop.PropWithTypeSlot.Ats); Expr arguments = GenerateParamsArray( GenerateArgsList(prop.OptionalArguments), PredefinedType.PT_EXPRESSION); lhs = GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, instance, propInfo, arguments); } } else { lhs = Visit(assignment.LHS); } Expr rhs = Visit(assignment.RHS); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } protected override Expr VisitMULTIGET(ExprMultiGet pExpr) { return Visit(pExpr.OptionalMulti.Left); } protected override Expr VisitMULTI(ExprMulti pExpr) { Expr rhs = Visit(pExpr.Operator); Expr lhs = Visit(pExpr.Left); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ASSIGN, lhs, rhs); } ///////////////////////////////////////////////////////////////////////////////// // Expression types. private ExprBinOp VisitBoundLambda(ExprBoundLambda anonmeth) { Debug.Assert(anonmeth != null); MethodSymbol lambdaMethod = GetPreDefMethod(PREDEFMETH.PM_EXPRESSION_LAMBDA); AggregateType delegateType = anonmeth.DelegateType; TypeArray lambdaTypeParams = TypeArray.Allocate(delegateType); AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); MethWithInst mwi = new MethWithInst(lambdaMethod, expressionType, lambdaTypeParams); Expr createParameters = CreateWraps(anonmeth); Debug.Assert(createParameters != null); Debug.Assert(anonmeth.Expression != null); Expr body = Visit(anonmeth.Expression); Debug.Assert(anonmeth.ArgumentScope.nextChild == null); Expr parameters = GenerateParamsArray(null, PredefinedType.PT_PARAMETEREXPRESSION); Expr args = ExprFactory.CreateList(body, parameters); CType typeRet = TypeManager.SubstType(mwi.Meth().RetType, mwi.GetType(), mwi.TypeArgs); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, typeRet, args, pMemGroup, mwi); call.PredefinedMethod = PREDEFMETH.PM_EXPRESSION_LAMBDA; return ExprFactory.CreateSequence(createParameters, call); } protected override Expr VisitCONSTANT(ExprConstant expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } protected override Expr VisitLOCAL(ExprLocal local) { Debug.Assert(local != null); Debug.Assert(local.Local.wrap != null); return local.Local.wrap; } protected override Expr VisitFIELD(ExprField expr) { Debug.Assert(expr != null); Expr pObject; if (expr.OptionalObject == null) { pObject = ExprFactory.CreateNull(); } else { pObject = Visit(expr.OptionalObject); } ExprFieldInfo pFieldInfo = ExprFactory.CreateFieldInfo(expr.FieldWithType.Field(), expr.FieldWithType.GetType()); return GenerateCall(PREDEFMETH.PM_EXPRESSION_FIELD, pObject, pFieldInfo); } protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr) { Debug.Assert(expr != null); return GenerateUserDefinedConversion(expr, expr.Argument); } protected override Expr VisitCAST(ExprCast pExpr) { Debug.Assert(pExpr != null); Expr pArgument = pExpr.Argument; // If we have generated an identity cast or reference cast to a base class // we can omit the cast. if (pArgument.Type == pExpr.Type || SymbolLoader.IsBaseClassOfClass(pArgument.Type, pExpr.Type) || CConversions.FImpRefConv(pArgument.Type, pExpr.Type)) { return Visit(pArgument); } // If we have a cast to PredefinedType.PT_G_EXPRESSION and the thing that we're casting is // a EXPRBOUNDLAMBDA that is an expression tree, then just visit the expression tree. if (pExpr.Type != null && pExpr.Type.IsPredefType(PredefinedType.PT_G_EXPRESSION) && pArgument is ExprBoundLambda) { return Visit(pArgument); } Expr result = GenerateConversion(pArgument, pExpr.Type, pExpr.isChecked()); if ((pExpr.Flags & EXPRFLAG.EXF_UNBOXRUNTIME) != 0) { // Propagate the unbox flag to the call for the ExpressionTreeCallRewriter. result.Flags |= EXPRFLAG.EXF_UNBOXRUNTIME; } return result; } protected override Expr VisitCONCAT(ExprConcat expr) { Debug.Assert(expr != null); PREDEFMETH pdm; if (expr.FirstArgument.Type.IsPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.IsPredefType(PredefinedType.PT_STRING)) { pdm = PREDEFMETH.PM_STRING_CONCAT_STRING_2; } else { pdm = PREDEFMETH.PM_STRING_CONCAT_OBJECT_2; } Expr p1 = Visit(expr.FirstArgument); Expr p2 = Visit(expr.SecondArgument); MethodSymbol method = GetPreDefMethod(pdm); Expr methodInfo = ExprFactory.CreateMethodInfo(method, SymbolLoader.GetPredefindType(PredefinedType.PT_STRING), null); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, p1, p2, methodInfo); } protected override Expr VisitBINOP(ExprBinOp expr) { Debug.Assert(expr != null); if (expr.UserDefinedCallMethod != null) { return GenerateUserDefinedBinaryOperator(expr); } else { return GenerateBuiltInBinaryOperator(expr); } } protected override Expr VisitUNARYOP(ExprUnaryOp pExpr) { Debug.Assert(pExpr != null); if (pExpr.UserDefinedCallMethod != null) { return GenerateUserDefinedUnaryOperator(pExpr); } else { return GenerateBuiltInUnaryOperator(pExpr); } } protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr) { Debug.Assert(pExpr != null); Expr arr = Visit(pExpr.Array); Expr args = GenerateIndexList(pExpr.Index); if (args is ExprList) { Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, arr, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, arr, args); } protected override Expr VisitCALL(ExprCall expr) { Debug.Assert(expr != null); switch (expr.NullableCallLiftKind) { default: break; case NullableCallLiftKind.NullableIntermediateConversion: case NullableCallLiftKind.NullableConversion: case NullableCallLiftKind.NullableConversionConstructor: return GenerateConversion(expr.OptionalArguments, expr.Type, expr.isChecked()); case NullableCallLiftKind.NotLiftedIntermediateConversion: case NullableCallLiftKind.UserDefinedConversion: return GenerateUserDefinedConversion(expr.OptionalArguments, expr.Type, expr.MethWithInst); } if (expr.MethWithInst.Meth().IsConstructor()) { return GenerateConstructor(expr); } ExprMemberGroup memberGroup = expr.MemberGroup; if (memberGroup.IsDelegate) { return GenerateDelegateInvoke(expr); } Expr pObject; if (expr.MethWithInst.Meth().isStatic || expr.MemberGroup.OptionalObject == null) { pObject = ExprFactory.CreateNull(); } else { pObject = expr.MemberGroup.OptionalObject; // If we have, say, an int? which is the object of a call to ToString // then we do NOT want to generate ((object)i).ToString() because that // will convert a null-valued int? to a null object. Rather what we want // to do is box it to a ValueType and call ValueType.ToString. // // To implement this we say that if the object of the call is an implicit boxing cast // then just generate the object, not the cast. If the cast is explicit in the // source code then it will be an EXPLICITCAST and we will visit it normally. // // It might be better to rewrite the expression tree API so that it // can handle in the general case all implicit boxing conversions. Right now it // requires that all arguments to a call that need to be boxed be explicitly boxed. if (pObject != null && pObject is ExprCast cast && cast.IsBoxingCast) { pObject = cast.Argument; } pObject = Visit(pObject); } Expr methodInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); PREDEFMETH pdm = PREDEFMETH.PM_EXPRESSION_CALL; Debug.Assert(!expr.MethWithInst.Meth().isVirtual || expr.MemberGroup.OptionalObject != null); return GenerateCall(pdm, pObject, methodInfo, Params); } protected override Expr VisitPROP(ExprProperty expr) { Debug.Assert(expr != null); Expr pObject; if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject == null) { pObject = ExprFactory.CreateNull(); } else { pObject = Visit(expr.MemberGroup.OptionalObject); } Expr propInfo = ExprFactory.CreatePropertyInfo(expr.PropWithTypeSlot.Prop(), expr.PropWithTypeSlot.GetType()); if (expr.OptionalArguments != null) { // It is an indexer property. Turn it into a virtual method call. Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo, Params); } return GenerateCall(PREDEFMETH.PM_EXPRESSION_PROPERTY, pObject, propInfo); } protected override Expr VisitARRINIT(ExprArrayInit expr) { Debug.Assert(expr != null); // POSSIBLE ERROR: Multi-d should be an error? Expr pTypeOf = CreateTypeOf(((ArrayType)expr.Type).ElementType); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, pTypeOf, Params); } protected override Expr VisitZEROINIT(ExprZeroInit expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } protected override Expr VisitTYPEOF(ExprTypeOf expr) { Debug.Assert(expr != null); return GenerateConstant(expr); } private Expr GenerateDelegateInvoke(ExprCall expr) { Debug.Assert(expr != null); ExprMemberGroup memberGroup = expr.MemberGroup; Debug.Assert(memberGroup.IsDelegate); Expr oldObject = memberGroup.OptionalObject; Debug.Assert(oldObject != null); Expr pObject = Visit(oldObject); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_INVOKE, pObject, Params); } private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm = expr.Kind switch { ExpressionKind.LeftShirt => PREDEFMETH.PM_EXPRESSION_LEFTSHIFT, ExpressionKind.RightShift => PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT, ExpressionKind.BitwiseExclusiveOr => PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR, ExpressionKind.BitwiseOr => PREDEFMETH.PM_EXPRESSION_OR, ExpressionKind.BitwiseAnd => PREDEFMETH.PM_EXPRESSION_AND, ExpressionKind.LogicalAnd => PREDEFMETH.PM_EXPRESSION_ANDALSO, ExpressionKind.LogicalOr => PREDEFMETH.PM_EXPRESSION_ORELSE, ExpressionKind.StringEq => PREDEFMETH.PM_EXPRESSION_EQUAL, ExpressionKind.Eq => PREDEFMETH.PM_EXPRESSION_EQUAL, ExpressionKind.StringNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL, ExpressionKind.NotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL, ExpressionKind.GreaterThanOrEqual => PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL, ExpressionKind.LessThanOrEqual => PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL, ExpressionKind.LessThan => PREDEFMETH.PM_EXPRESSION_LESSTHAN, ExpressionKind.GreaterThan => PREDEFMETH.PM_EXPRESSION_GREATERTHAN, ExpressionKind.Modulo => PREDEFMETH.PM_EXPRESSION_MODULO, ExpressionKind.Divide => PREDEFMETH.PM_EXPRESSION_DIVIDE, ExpressionKind.Multiply => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED : PREDEFMETH.PM_EXPRESSION_MULTIPLY, ExpressionKind.Subtract => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED : PREDEFMETH.PM_EXPRESSION_SUBTRACT, ExpressionKind.Add => expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED : PREDEFMETH.PM_EXPRESSION_ADD, _ => throw Error.InternalCompilerError(), }; Expr origL = expr.OptionalLeftChild; Expr origR = expr.OptionalRightChild; Debug.Assert(origL != null); Debug.Assert(origR != null); CType typeL = origL.Type; CType typeR = origR.Type; Expr newL = Visit(origL); Expr newR = Visit(origR); bool didEnumConversion = false; CType convertL = null; CType convertR = null; if (typeL.IsEnumType) { // We have already inserted casts if not lifted, so we should never see an enum. Debug.Assert(expr.IsLifted); convertL = TypeManager.GetNullable(typeL.UnderlyingEnumType); typeL = convertL; didEnumConversion = true; } else if (typeL is NullableType nubL && nubL.UnderlyingType.IsEnumType) { Debug.Assert(expr.IsLifted); convertL = TypeManager.GetNullable(nubL.UnderlyingType.UnderlyingEnumType); typeL = convertL; didEnumConversion = true; } if (typeR.IsEnumType) { Debug.Assert(expr.IsLifted); convertR = TypeManager.GetNullable(typeR.UnderlyingEnumType); typeR = convertR; didEnumConversion = true; } else if (typeR is NullableType nubR && nubR.UnderlyingType.IsEnumType) { Debug.Assert(expr.IsLifted); convertR = TypeManager.GetNullable(nubR.UnderlyingType.UnderlyingEnumType); typeR = convertR; didEnumConversion = true; } if (typeL is NullableType nubL2 && nubL2.UnderlyingType == typeR) { convertR = typeL; } if (typeR is NullableType nubR2 && nubR2.UnderlyingType == typeL) { convertL = typeR; } if (convertL != null) { newL = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newL, CreateTypeOf(convertL)); } if (convertR != null) { newR = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, newR, CreateTypeOf(convertR)); } Expr call = GenerateCall(pdm, newL, newR); if (didEnumConversion && expr.Type.StripNubs().IsEnumType) { call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, CreateTypeOf(expr.Type)); } return call; } private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.UnaryPlus: return Visit(expr.Child); case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT; break; case ExpressionKind.Negate: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED : PREDEFMETH.PM_EXPRESSION_NEGATE; break; default: throw Error.InternalCompilerError(); } Expr origOp = expr.Child; // Such operations are always already casts on operations on casts. Debug.Assert(!(origOp.Type is NullableType nub) || !nub.UnderlyingType.IsEnumType); return GenerateCall(pdm, Visit(origOp)); } private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; switch (expr.Kind) { case ExpressionKind.LogicalOr: pdm = PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED; break; case ExpressionKind.LogicalAnd: pdm = PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED; break; case ExpressionKind.LeftShirt: pdm = PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED; break; case ExpressionKind.RightShift: pdm = PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED; break; case ExpressionKind.BitwiseExclusiveOr: pdm = PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED; break; case ExpressionKind.BitwiseOr: pdm = PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED; break; case ExpressionKind.BitwiseAnd: pdm = PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED; break; case ExpressionKind.Modulo: pdm = PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED; break; case ExpressionKind.Divide: pdm = PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED; break; case ExpressionKind.StringEq: case ExpressionKind.StringNotEq: case ExpressionKind.DelegateEq: case ExpressionKind.DelegateNotEq: case ExpressionKind.Eq: case ExpressionKind.NotEq: case ExpressionKind.GreaterThanOrEqual: case ExpressionKind.GreaterThan: case ExpressionKind.LessThanOrEqual: case ExpressionKind.LessThan: return GenerateUserDefinedComparisonOperator(expr); case ExpressionKind.DelegateSubtract: case ExpressionKind.Subtract: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED; break; case ExpressionKind.DelegateAdd: case ExpressionKind.Add: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED; break; case ExpressionKind.Multiply: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED; break; default: throw Error.InternalCompilerError(); } Expr p1 = expr.OptionalLeftChild; Expr p2 = expr.OptionalRightChild; Expr udcall = expr.OptionalUserDefinedCall; if (udcall != null) { Debug.Assert(udcall.Kind == ExpressionKind.Call || udcall.Kind == ExpressionKind.UserLogicalOp); if (udcall is ExprCall ascall) { ExprList args = (ExprList)ascall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = args.OptionalElement; p2 = args.OptionalNextListNode; } else { ExprUserLogicalOp userLogOp = udcall as ExprUserLogicalOp; Debug.Assert(userLogOp != null); ExprList args = (ExprList)userLogOp.OperatorCall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = ((ExprWrap)args.OptionalElement).OptionalExpression; p2 = args.OptionalNextListNode; } } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod); Expr call = GenerateCall(pdm, p1, p2, methodInfo); // Delegate add/subtract generates a call to Combine/Remove, which returns System.Delegate, // not the operand delegate CType. We must cast to the delegate CType. if (expr.Kind == ExpressionKind.DelegateSubtract || expr.Kind == ExpressionKind.DelegateAdd) { Expr pTypeOf = CreateTypeOf(expr.Type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf); } return call; } private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm; Expr arg = expr.Child; ExprCall call = (ExprCall)expr.OptionalUserDefinedCall; if (call != null) { // Use the actual argument of the call; it may contain user-defined // conversions or be a bound lambda, and that will not be in the original // argument stashed away in the left child of the operator. arg = call.OptionalArguments; } Debug.Assert(arg != null && arg.Kind != ExpressionKind.List); switch (expr.Kind) { case ExpressionKind.True: case ExpressionKind.False: return Visit(call); case ExpressionKind.UnaryPlus: pdm = PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED; break; case ExpressionKind.BitwiseNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.LogicalNot: pdm = PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED; break; case ExpressionKind.DecimalNegate: case ExpressionKind.Negate: pdm = expr.isChecked() ? PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED; break; case ExpressionKind.Inc: case ExpressionKind.Dec: case ExpressionKind.DecimalInc: case ExpressionKind.DecimalDec: pdm = PREDEFMETH.PM_EXPRESSION_CALL; break; default: throw Error.InternalCompilerError(); } Expr op = Visit(arg); Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod); if (expr.Kind == ExpressionKind.Inc || expr.Kind == ExpressionKind.Dec || expr.Kind == ExpressionKind.DecimalInc || expr.Kind == ExpressionKind.DecimalDec) { return GenerateCall(pdm, null, methodInfo, GenerateParamsArray(op, PredefinedType.PT_EXPRESSION)); } return GenerateCall(pdm, op, methodInfo); } private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr) { Debug.Assert(expr != null); PREDEFMETH pdm = expr.Kind switch { ExpressionKind.StringEq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, ExpressionKind.StringNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, ExpressionKind.DelegateEq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, ExpressionKind.DelegateNotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, ExpressionKind.Eq => PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, ExpressionKind.NotEq => PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, ExpressionKind.LessThanOrEqual => PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, ExpressionKind.LessThan => PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED, ExpressionKind.GreaterThanOrEqual => PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, ExpressionKind.GreaterThan => PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED, _ => throw Error.InternalCompilerError(), }; Expr p1 = expr.OptionalLeftChild; Expr p2 = expr.OptionalRightChild; if (expr.OptionalUserDefinedCall != null) { ExprCall udcall = (ExprCall)expr.OptionalUserDefinedCall; ExprList args = (ExprList)udcall.OptionalArguments; Debug.Assert(args.OptionalNextListNode.Kind != ExpressionKind.List); p1 = args.OptionalElement; p2 = args.OptionalNextListNode; } p1 = Visit(p1); p2 = Visit(p2); FixLiftedUserDefinedBinaryOperators(expr, ref p1, ref p2); Expr lift = ExprFactory.CreateBoolConstant(false); // We never lift to null in C#. Expr methodInfo = ExprFactory.CreateMethodInfo(expr.UserDefinedCallMethod); return GenerateCall(pdm, p1, p2, lift, methodInfo); } private Expr GenerateConversion(Expr arg, CType CType, bool bChecked) => GenerateConversionWithSource(Visit(arg), CType, bChecked || arg.isChecked()); private static Expr GenerateConversionWithSource(Expr pTarget, CType pType, bool bChecked) { PREDEFMETH pdm = bChecked ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; Expr pTypeOf = CreateTypeOf(pType); return GenerateCall(pdm, pTarget, pTypeOf); } private Expr GenerateValueAccessConversion(Expr pArgument) { Debug.Assert(pArgument != null); CType pStrippedTypeOfArgument = pArgument.Type.StripNubs(); Expr pStrippedTypeExpr = CreateTypeOf(pStrippedTypeOfArgument); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, Visit(pArgument), pStrippedTypeExpr); } private Expr GenerateUserDefinedConversion(Expr arg, CType type, MethWithInst method) { Expr target = Visit(arg); return GenerateUserDefinedConversion(arg, type, target, method); } private static Expr GenerateUserDefinedConversion(Expr arg, CType CType, Expr target, MethWithInst method) { // The user-defined explicit conversion from enum? to decimal or decimal? requires // that we convert the enum? to its nullable underlying CType. if (isEnumToDecimalConversion(arg.Type, CType)) { // Special case: If we have enum? to decimal? then we need to emit // a conversion from enum? to its nullable underlying CType first. // This is unfortunate; we ought to reorganize how conversions are // represented in the Expr tree so that this is more transparent. // converting an enum to its underlying CType never fails, so no need to check it. CType underlyingType = arg.Type.StripNubs().UnderlyingEnumType; CType nullableType = TypeManager.GetNullable(underlyingType); Expr typeofNubEnum = CreateTypeOf(nullableType); target = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, target, typeofNubEnum); } // If the methodinfo does not return the target CType AND this is not a lifted conversion // from one value CType to another, then we need to wrap the whole thing in another conversion, // e.g. if we have a user-defined conversion from int to S? and we have (S)myint, then we need to generate // Convert(Convert(myint, typeof(S?), op_implicit), typeof(S)) CType pMethodReturnType = TypeManager.SubstType(method.Meth().RetType, method.GetType(), method.TypeArgs); bool fDontLiftReturnType = (pMethodReturnType == CType || (IsNullableValueType(arg.Type) && IsNullableValueType(CType))); Expr typeofInner = CreateTypeOf(fDontLiftReturnType ? CType : pMethodReturnType); Expr methodInfo = ExprFactory.CreateMethodInfo(method); PREDEFMETH pdmInner = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED : PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED; Expr callUserDefinedConversion = GenerateCall(pdmInner, target, typeofInner, methodInfo); if (fDontLiftReturnType) { return callUserDefinedConversion; } PREDEFMETH pdmOuter = arg.isChecked() ? PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED : PREDEFMETH.PM_EXPRESSION_CONVERT; Expr typeofOuter = CreateTypeOf(CType); return GenerateCall(pdmOuter, callUserDefinedConversion, typeofOuter); } private Expr GenerateUserDefinedConversion(ExprUserDefinedConversion pExpr, Expr pArgument) { Expr pCastCall = pExpr.UserDefinedCall; Expr pCastArgument = pExpr.Argument; Expr pConversionSource; if (!isEnumToDecimalConversion(pArgument.Type, pExpr.Type) && IsNullableValueAccess(pCastArgument, pArgument)) { // We have an implicit conversion of nullable CType to the value CType, generate a convert node for it. pConversionSource = GenerateValueAccessConversion(pArgument); } else { ExprCall call = pCastCall as ExprCall; Expr pUDConversion = call?.PConversions; if (pUDConversion != null) { if (pUDConversion is ExprCall convCall) { Expr pUDConversionArgument = convCall.OptionalArguments; if (IsNullableValueAccess(pUDConversionArgument, pArgument)) { pConversionSource = GenerateValueAccessConversion(pArgument); } else { pConversionSource = Visit(pUDConversionArgument); } return GenerateConversionWithSource(pConversionSource, pCastCall.Type, call.isChecked()); } // This can happen if we have a UD conversion from C to, say, int, // and we have an explicit cast to decimal?. The conversion should // then be bound as two chained user-defined conversions. Debug.Assert(pUDConversion is ExprUserDefinedConversion); // Just recurse. return GenerateUserDefinedConversion((ExprUserDefinedConversion)pUDConversion, pArgument); } pConversionSource = Visit(pCastArgument); } return GenerateUserDefinedConversion(pCastArgument, pExpr.Type, pConversionSource, pExpr.UserDefinedCallMethod); } private static Expr GenerateParameter(string name, CType CType) { SymbolLoader.GetPredefindType(PredefinedType.PT_STRING); // force an ensure state ExprConstant nameString = ExprFactory.CreateStringConstant(name); ExprTypeOf pTypeOf = CreateTypeOf(CType); return GenerateCall(PREDEFMETH.PM_EXPRESSION_PARAMETER, pTypeOf, nameString); } private static MethodSymbol GetPreDefMethod(PREDEFMETH pdm) => PredefinedMembers.GetMethod(pdm); private static ExprTypeOf CreateTypeOf(CType type) => ExprFactory.CreateTypeOf(type); private static Expr CreateWraps(ExprBoundLambda anonmeth) { Expr sequence = null; for (Symbol sym = anonmeth.ArgumentScope.firstChild; sym != null; sym = sym.nextChild) { if (!(sym is LocalVariableSymbol local)) { continue; } Debug.Assert(anonmeth.Expression != null); Expr create = GenerateParameter(local.name.Text, local.GetType()); local.wrap = ExprFactory.CreateWrap(create); Expr save = ExprFactory.CreateSave(local.wrap); if (sequence == null) { sequence = save; } else { sequence = ExprFactory.CreateSequence(sequence, save); } } return sequence; } private Expr GenerateConstructor(ExprCall expr) { Debug.Assert(expr != null); Debug.Assert(expr.MethWithInst.Meth().IsConstructor()); Expr constructorInfo = ExprFactory.CreateMethodInfo(expr.MethWithInst); Expr args = GenerateArgsList(expr.OptionalArguments); Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION); return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params); } private Expr GenerateArgsList(Expr oldArgs) { Expr newArgs = null; Expr newArgsTail = newArgs; for (ExpressionIterator it = new ExpressionIterator(oldArgs); !it.AtEnd(); it.MoveNext()) { Expr oldArg = it.Current(); ExprFactory.AppendItemToList(Visit(oldArg), ref newArgs, ref newArgsTail); } return newArgs; } private Expr GenerateIndexList(Expr oldIndices) { CType intType = SymbolLoader.GetPredefindType(PredefinedType.PT_INT); Expr newIndices = null; Expr newIndicesTail = newIndices; for (ExpressionIterator it = new ExpressionIterator(oldIndices); !it.AtEnd(); it.MoveNext()) { Expr newIndex = it.Current(); if (newIndex.Type != intType) { newIndex = ExprFactory.CreateCast(EXPRFLAG.EXF_INDEXEXPR, intType, newIndex); newIndex.Flags |= EXPRFLAG.EXF_CHECKOVERFLOW; } Expr rewrittenIndex = Visit(newIndex); ExprFactory.AppendItemToList(rewrittenIndex, ref newIndices, ref newIndicesTail); } return newIndices; } private static Expr GenerateConstant(Expr expr) { EXPRFLAG flags = 0; AggregateType pObject = SymbolLoader.GetPredefindType(PredefinedType.PT_OBJECT); if (expr.Type is NullType) { ExprTypeOf pTypeOf = CreateTypeOf(pObject); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, expr, pTypeOf); } AggregateType stringType = SymbolLoader.GetPredefindType(PredefinedType.PT_STRING); if (expr.Type != stringType) { flags = EXPRFLAG.EXF_BOX; } ExprCast cast = ExprFactory.CreateCast(flags, pObject, expr); ExprTypeOf pTypeOf2 = CreateTypeOf(expr.Type); return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, cast, pTypeOf2); } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1) { MethodSymbol method = GetPreDefMethod(pdm); // this should be enforced in an earlier pass and the transform pass should not // be handling this error if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, arg1, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = ExprFactory.CreateList(arg1, arg2); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = ExprFactory.CreateList(arg1, arg2, arg3); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprCall GenerateCall(PREDEFMETH pdm, Expr arg1, Expr arg2, Expr arg3, Expr arg4) { MethodSymbol method = GetPreDefMethod(pdm); if (method == null) return null; AggregateType expressionType = SymbolLoader.GetPredefindType(PredefinedType.PT_EXPRESSION); Expr args = ExprFactory.CreateList(arg1, arg2, arg3, arg4); MethWithInst mwi = new MethWithInst(method, expressionType); ExprMemberGroup pMemGroup = ExprFactory.CreateMemGroup(null, mwi); ExprCall call = ExprFactory.CreateCall(0, mwi.Meth().RetType, args, pMemGroup, mwi); call.PredefinedMethod = pdm; return call; } private static ExprArrayInit GenerateParamsArray(Expr args, PredefinedType pt) { int parameterCount = ExpressionIterator.Count(args); AggregateType paramsArrayElementType = SymbolLoader.GetPredefindType(pt); ArrayType paramsArrayType = TypeManager.GetArray(paramsArrayElementType, 1, true); ExprConstant paramsArrayArg = ExprFactory.CreateIntegerConstant(parameterCount); return ExprFactory.CreateArrayInit(paramsArrayType, args, paramsArrayArg, new int[] { parameterCount }); } private static void FixLiftedUserDefinedBinaryOperators(ExprBinOp expr, ref Expr pp1, ref Expr pp2) { // If we have lifted T1 op T2 to T1? op T2?, and we have an expression T1 op T2? or T1? op T2 then // we need to ensure that the unlifted actual arguments are promoted to their nullable CType. Debug.Assert(expr != null); Debug.Assert(pp1 != null); Debug.Assert(pp1 != null); Debug.Assert(pp2 != null); Debug.Assert(pp2 != null); MethodSymbol method = expr.UserDefinedCallMethod.Meth(); Expr orig1 = expr.OptionalLeftChild; Expr orig2 = expr.OptionalRightChild; Debug.Assert(orig1 != null && orig2 != null); Expr new1 = pp1; Expr new2 = pp2; CType fptype1 = method.Params[0]; CType fptype2 = method.Params[1]; CType aatype1 = orig1.Type; CType aatype2 = orig2.Type; // Is the operator even a candidate for lifting? if (!(fptype1 is AggregateType fat1) || !fat1.OwningAggregate.IsValueType() || !(fptype2 is AggregateType fat2) || !fat2.OwningAggregate.IsValueType()) { return; } CType nubfptype1 = TypeManager.GetNullable(fptype1); CType nubfptype2 = TypeManager.GetNullable(fptype2); // If we have null op X, or T1 op T2?, or T1 op null, lift first arg to T1? if (aatype1 is NullType || aatype1 == fptype1 && (aatype2 == nubfptype2 || aatype2 is NullType)) { new1 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new1, CreateTypeOf(nubfptype1)); } // If we have X op null, or T1? op T2, or null op T2, lift second arg to T2? if (aatype2 is NullType || aatype2 == fptype2 && (aatype1 == nubfptype1 || aatype1 is NullType)) { new2 = GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, new2, CreateTypeOf(nubfptype2)); } pp1 = new1; pp2 = new2; } private static bool IsNullableValueType(CType pType) => pType is NullableType && pType.StripNubs() is AggregateType agg && agg.OwningAggregate.IsValueType(); private static bool IsNullableValueAccess(Expr pExpr, Expr pObject) { Debug.Assert(pExpr != null); return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType; } private static bool isEnumToDecimalConversion(CType argtype, CType desttype) => argtype.StripNubs().IsEnumType && desttype.StripNubs().IsPredefType(PredefinedType.PT_DECIMAL); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This file is a line by line port of callingconvention.h from the CLR with the intention that we may wish to merge // changes from the CLR in at a later time. As such, the normal coding conventions are ignored. // // #if ARM #define _TARGET_ARM_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define FEATURE_HFA #elif ARM64 #define _TARGET_ARM64_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #define FEATURE_HFA #elif X86 #define _TARGET_X86_ #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #elif AMD64 #if PLATFORM_UNIX #define UNIX_AMD64_ABI #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #else #endif #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define _TARGET_AMD64_ #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #else #error Unknown architecture! #endif // Provides an abstraction over platform specific calling conventions (specifically, the calling convention // utilized by the JIT on that platform). The caller enumerates each argument of a signature in turn, and is // provided with information mapping that argument into registers and/or stack locations. using System; namespace Internal.Runtime { #if _TARGET_AMD64_ #pragma warning disable 0169 #if UNIX_AMD64_ABI struct ReturnBlock { IntPtr returnValue; IntPtr returnValue2; } struct ArgumentRegisters { IntPtr rdi; IntPtr rsi; IntPtr rdx; IntPtr rcx; IntPtr r8; IntPtr r9; } #else // UNIX_AMD64_ABI struct ReturnBlock { IntPtr returnValue; } struct ArgumentRegisters { IntPtr rdx; IntPtr rcx; IntPtr r8; IntPtr r9; } #endif // UNIX_AMD64_ABI #pragma warning restore 0169 #pragma warning disable 0169 struct M128A { IntPtr a; IntPtr b; } struct FloatArgumentRegisters { M128A d0; M128A d1; M128A d2; M128A d3; #if UNIX_AMD64_ABI M128A d4; M128A d5; M128A d6; M128A d7; #endif } #pragma warning restore 0169 struct ArchitectureConstants { // To avoid corner case bugs, limit maximum size of the arguments with sufficient margin public const int MAX_ARG_SIZE = 0xFFFFFF; #if UNIX_AMD64_ABI public const int NUM_ARGUMENT_REGISTERS = 6; #else public const int NUM_ARGUMENT_REGISTERS = 4; #endif public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 8; public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 8; public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 8; public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 8; public const int ENREGISTERED_PARAMTYPE_MAXSIZE = 8; public const int STACK_ELEM_SIZE = 8; public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); } } #elif _TARGET_ARM64_ #pragma warning disable 0169 struct ReturnBlock { IntPtr returnValue; IntPtr returnValue2; IntPtr returnValue3; IntPtr returnValue4; IntPtr returnValue5; IntPtr returnValue6; IntPtr returnValue7; IntPtr returnValue8; } struct CalleeSavedRegisters { IntPtr x29; public IntPtr m_ReturnAddress; // Also known as x30 IntPtr x19; IntPtr x20; IntPtr x21; IntPtr x22; IntPtr x23; IntPtr x24; IntPtr x25; IntPtr x26; IntPtr x27; IntPtr x28; } struct ArgumentRegisters { IntPtr x0; IntPtr x1; IntPtr x2; IntPtr x3; IntPtr x4; IntPtr x5; IntPtr x6; IntPtr x7; } #pragma warning restore 0169 #pragma warning disable 0169 struct FloatArgumentRegisters { double d0; double d1; double d2; double d3; double d4; double d5; double d6; double d7; } #pragma warning restore 0169 struct ArchitectureConstants { // To avoid corner case bugs, limit maximum size of the arguments with sufficient margin public const int MAX_ARG_SIZE = 0xFFFFFF; public const int NUM_ARGUMENT_REGISTERS = 8; public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 8; public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 64; //(maximum HFA size is 8 doubles) public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 8; public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 8; public const int ENREGISTERED_PARAMTYPE_MAXSIZE = 16; //(max value type size than can be passed by value) public const int STACK_ELEM_SIZE = 8; public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); } } #elif _TARGET_X86_ #pragma warning disable 0169, 0649 struct ReturnBlock { public IntPtr returnValue; public IntPtr returnValue2; } struct ArgumentRegisters { public IntPtr edx; public static unsafe int GetOffsetOfEdx() { return 0; } public IntPtr ecx; public static unsafe int GetOffsetOfEcx() { return sizeof(IntPtr); } } // This struct isn't used by x86, but exists for compatibility with the definition of the CallDescrData struct struct FloatArgumentRegisters { } #pragma warning restore 0169, 0649 struct ArchitectureConstants { // To avoid corner case bugs, limit maximum size of the arguments with sufficient margin public const int MAX_ARG_SIZE = 0xFFFFFF; public const int NUM_ARGUMENT_REGISTERS = 2; public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 4; public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 8; public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 4; public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 4; public const int STACK_ELEM_SIZE = 4; public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); } } #elif _TARGET_ARM_ #pragma warning disable 0169 struct ReturnBlock { IntPtr returnValue; IntPtr returnValue2; IntPtr returnValue3; IntPtr returnValue4; IntPtr returnValue5; IntPtr returnValue6; IntPtr returnValue7; IntPtr returnValue8; } struct ArgumentRegisters { IntPtr r0; IntPtr r1; IntPtr r2; IntPtr r3; } struct FloatArgumentRegisters { double d0; double d1; double d2; double d3; double d4; double d5; double d6; double d7; } #pragma warning restore 0169 struct ArchitectureConstants { // To avoid corner case bugs, limit maximum size of the arguments with sufficient margin public const int MAX_ARG_SIZE = 0xFFFFFF; public const int NUM_ARGUMENT_REGISTERS = 4; public const int ARGUMENTREGISTERS_SIZE = NUM_ARGUMENT_REGISTERS * 4; public const int ENREGISTERED_RETURNTYPE_MAXSIZE = 32; public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE = 4; public const int ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE = 8; public const int STACK_ELEM_SIZE = 4; public static int StackElemSize(int size) { return (((size) + STACK_ELEM_SIZE - 1) & ~(STACK_ELEM_SIZE - 1)); } } #endif // // TransitionBlock is layout of stack frame of method call, saved argument registers and saved callee saved registers. Even though not // all fields are used all the time, we use uniform form for simplicity. // internal struct TransitionBlock { #pragma warning disable 0169,0649 #if _TARGET_X86_ public ArgumentRegisters m_argumentRegisters; public static unsafe int GetOffsetOfArgumentRegisters() { return 0; } public ReturnBlock m_returnBlock; public static unsafe int GetOffsetOfReturnValuesBlock() { return sizeof(ArgumentRegisters); } IntPtr m_ebp; IntPtr m_ReturnAddress; #elif _TARGET_AMD64_ #if UNIX_AMD64_ABI public ReturnBlock m_returnBlock; public static unsafe int GetOffsetOfReturnValuesBlock() { return 0; } public ArgumentRegisters m_argumentRegisters; public static unsafe int GetOffsetOfArgumentRegisters() { return sizeof(ReturnBlock); } IntPtr m_alignmentPadding; IntPtr m_ReturnAddress; #else // UNIX_AMD64_ABI IntPtr m_returnBlockPadding; ReturnBlock m_returnBlock; public static unsafe int GetOffsetOfReturnValuesBlock() { return sizeof(IntPtr); } IntPtr m_alignmentPadding; IntPtr m_ReturnAddress; public static unsafe int GetOffsetOfArgumentRegisters() { return sizeof(TransitionBlock); } #endif // UNIX_AMD64_ABI #elif _TARGET_ARM_ public ReturnBlock m_returnBlock; public static unsafe int GetOffsetOfReturnValuesBlock() { return 0; } public ArgumentRegisters m_argumentRegisters; public static unsafe int GetOffsetOfArgumentRegisters() { return sizeof(ReturnBlock); } #elif _TARGET_ARM64_ public ReturnBlock m_returnBlock; public static unsafe int GetOffsetOfReturnValuesBlock() { return 0; } public ArgumentRegisters m_argumentRegisters; public static unsafe int GetOffsetOfArgumentRegisters() { return sizeof(ReturnBlock); } #else #error Portability problem #endif #pragma warning restore 0169,0649 // The transition block should define everything pushed by callee. The code assumes in number of places that // end of the transition block is caller's stack pointer. public static unsafe byte GetOffsetOfArgs() { return (byte)sizeof(TransitionBlock); } public static bool IsStackArgumentOffset(int offset) { int ofsArgRegs = GetOffsetOfArgumentRegisters(); return offset >= (int)(ofsArgRegs + ArchitectureConstants.ARGUMENTREGISTERS_SIZE); } public static bool IsArgumentRegisterOffset(int offset) { int ofsArgRegs = GetOffsetOfArgumentRegisters(); return offset >= ofsArgRegs && offset < (int)(ofsArgRegs + ArchitectureConstants.ARGUMENTREGISTERS_SIZE); } #if !_TARGET_X86_ public static unsafe int GetArgumentIndexFromOffset(int offset) { return ((offset - GetOffsetOfArgumentRegisters()) / IntPtr.Size); } #endif #if CALLDESCR_FPARGREGS public static bool IsFloatArgumentRegisterOffset(int offset) { return offset < 0; } public static int GetOffsetOfFloatArgumentRegisters() { return -GetNegSpaceSize(); } #endif public static unsafe int GetNegSpaceSize() { int negSpaceSize = 0; #if CALLDESCR_FPARGREGS negSpaceSize += sizeof(FloatArgumentRegisters); #endif return negSpaceSize; } public static int GetThisOffset() { // This pointer is in the first argument register by default int ret = TransitionBlock.GetOffsetOfArgumentRegisters(); #if _TARGET_X86_ // x86 is special as always ret += ArgumentRegisters.GetOffsetOfEcx(); #endif return ret; } public const int InvalidOffset = -1; }; }
// Copyright (c) MOSA Project. Licensed under the New BSD License. namespace Mosa.Compiler.Framework.CIL { /// <summary> /// /// </summary> public static class CILInstruction { #region Static Data private static BaseCILInstruction[] opcodeMap = Initialize(); /// <summary> /// Gets the instructions. /// </summary> public static BaseCILInstruction[] Instructions { get { return opcodeMap; } } #endregion Static Data /// <summary> /// Gets the instruction. /// </summary> /// <param name="opcode">The opcode.</param> public static BaseCILInstruction Get(OpCode opcode) { return opcodeMap[(int)opcode]; } /// <summary> /// Initializes this instance. /// </summary> /// <returns></returns> public static BaseCILInstruction[] Initialize() { BaseCILInstruction[] opcodeMap = new BaseCILInstruction[0x120]; /* 0x000 */ opcodeMap[(int)OpCode.Nop] = new NopInstruction(OpCode.Nop); /* 0x001 */ opcodeMap[(int)OpCode.Break] = new BreakInstruction(OpCode.Break); /* 0x002 */ opcodeMap[(int)OpCode.Ldarg_0] = new LdargInstruction(OpCode.Ldarg_0); /* 0x003 */ opcodeMap[(int)OpCode.Ldarg_1] = new LdargInstruction(OpCode.Ldarg_1); /* 0x004 */ opcodeMap[(int)OpCode.Ldarg_2] = new LdargInstruction(OpCode.Ldarg_2); /* 0x005 */ opcodeMap[(int)OpCode.Ldarg_3] = new LdargInstruction(OpCode.Ldarg_3); /* 0x006 */ opcodeMap[(int)OpCode.Ldloc_0] = new LdlocInstruction(OpCode.Ldloc_0); /* 0x007 */ opcodeMap[(int)OpCode.Ldloc_1] = new LdlocInstruction(OpCode.Ldloc_1); /* 0x008 */ opcodeMap[(int)OpCode.Ldloc_2] = new LdlocInstruction(OpCode.Ldloc_2); /* 0x009 */ opcodeMap[(int)OpCode.Ldloc_3] = new LdlocInstruction(OpCode.Ldloc_3); /* 0x00A */ opcodeMap[(int)OpCode.Stloc_0] = new StlocInstruction(OpCode.Stloc_0); /* 0x00B */ opcodeMap[(int)OpCode.Stloc_1] = new StlocInstruction(OpCode.Stloc_1); /* 0x00C */ opcodeMap[(int)OpCode.Stloc_2] = new StlocInstruction(OpCode.Stloc_2); /* 0x00D */ opcodeMap[(int)OpCode.Stloc_3] = new StlocInstruction(OpCode.Stloc_3); /* 0x00E */ opcodeMap[(int)OpCode.Ldarg_s] = new LdargInstruction(OpCode.Ldarg_s); /* 0x00F */ opcodeMap[(int)OpCode.Ldarga_s] = new LdargaInstruction(OpCode.Ldarga_s); /* 0x010 */ opcodeMap[(int)OpCode.Starg_s] = new StargInstruction(OpCode.Starg_s); /* 0x011 */ opcodeMap[(int)OpCode.Ldloc_s] = new LdlocInstruction(OpCode.Ldloc_s); /* 0x012 */ opcodeMap[(int)OpCode.Ldloca_s] = new LdlocaInstruction(OpCode.Ldloca_s); /* 0x013 */ opcodeMap[(int)OpCode.Stloc_s] = new StlocInstruction(OpCode.Stloc_s); /* 0x014 */ opcodeMap[(int)OpCode.Ldnull] = new LdcInstruction(OpCode.Ldnull); /* 0x015 */ opcodeMap[(int)OpCode.Ldc_i4_m1] = new LdcInstruction(OpCode.Ldc_i4_m1); /* 0x016 */ opcodeMap[(int)OpCode.Ldc_i4_0] = new LdcInstruction(OpCode.Ldc_i4_0); /* 0x017 */ opcodeMap[(int)OpCode.Ldc_i4_1] = new LdcInstruction(OpCode.Ldc_i4_1); /* 0x018 */ opcodeMap[(int)OpCode.Ldc_i4_2] = new LdcInstruction(OpCode.Ldc_i4_2); /* 0x019 */ opcodeMap[(int)OpCode.Ldc_i4_3] = new LdcInstruction(OpCode.Ldc_i4_3); /* 0x01A */ opcodeMap[(int)OpCode.Ldc_i4_4] = new LdcInstruction(OpCode.Ldc_i4_4); /* 0x01B */ opcodeMap[(int)OpCode.Ldc_i4_5] = new LdcInstruction(OpCode.Ldc_i4_5); /* 0x01C */ opcodeMap[(int)OpCode.Ldc_i4_6] = new LdcInstruction(OpCode.Ldc_i4_6); /* 0x01D */ opcodeMap[(int)OpCode.Ldc_i4_7] = new LdcInstruction(OpCode.Ldc_i4_7); /* 0x01E */ opcodeMap[(int)OpCode.Ldc_i4_8] = new LdcInstruction(OpCode.Ldc_i4_8); /* 0x01F */ opcodeMap[(int)OpCode.Ldc_i4_s] = new LdcInstruction(OpCode.Ldc_i4_s); /* 0x020 */ opcodeMap[(int)OpCode.Ldc_i4] = new LdcInstruction(OpCode.Ldc_i4); /* 0x021 */ opcodeMap[(int)OpCode.Ldc_i8] = new LdcInstruction(OpCode.Ldc_i8); /* 0x022 */ opcodeMap[(int)OpCode.Ldc_r4] = new LdcInstruction(OpCode.Ldc_r4); /* 0x023 */ opcodeMap[(int)OpCode.Ldc_r8] = new LdcInstruction(OpCode.Ldc_r8); /* 0x024 is undefined */ /* 0x025 */ opcodeMap[(int)OpCode.Dup] = new DupInstruction(OpCode.Dup); /* 0x026 */ opcodeMap[(int)OpCode.Pop] = new PopInstruction(OpCode.Pop); /* 0x027 */ opcodeMap[(int)OpCode.Jmp] = new JumpInstruction(OpCode.Jmp); /* 0x028 */ opcodeMap[(int)OpCode.Call] = new CallInstruction(OpCode.Call); /* 0x029 */ opcodeMap[(int)OpCode.Calli] = new CalliInstruction(OpCode.Calli); /* 0x02A */ opcodeMap[(int)OpCode.Ret] = new ReturnInstruction(OpCode.Ret); /* 0x02B */ opcodeMap[(int)OpCode.Br_s] = new BranchInstruction(OpCode.Br_s); /* 0x02C */ opcodeMap[(int)OpCode.Brfalse_s] = new UnaryBranchInstruction(OpCode.Brfalse_s); /* 0x02D */ opcodeMap[(int)OpCode.Brtrue_s] = new UnaryBranchInstruction(OpCode.Brtrue_s); /* 0x02E */ opcodeMap[(int)OpCode.Beq_s] = new BinaryBranchInstruction(OpCode.Beq_s); /* 0x02F */ opcodeMap[(int)OpCode.Bge_s] = new BinaryBranchInstruction(OpCode.Bge_s); /* 0x030 */ opcodeMap[(int)OpCode.Bgt_s] = new BinaryBranchInstruction(OpCode.Bgt_s); /* 0x031 */ opcodeMap[(int)OpCode.Ble_s] = new BinaryBranchInstruction(OpCode.Ble_s); /* 0x032 */ opcodeMap[(int)OpCode.Blt_s] = new BinaryBranchInstruction(OpCode.Blt_s); /* 0x033 */ opcodeMap[(int)OpCode.Bne_un_s] = new BinaryBranchInstruction(OpCode.Bne_un_s); /* 0x034 */ opcodeMap[(int)OpCode.Bge_un_s] = new BinaryBranchInstruction(OpCode.Bge_un_s); /* 0x035 */ opcodeMap[(int)OpCode.Bgt_un_s] = new BinaryBranchInstruction(OpCode.Bgt_un_s); /* 0x036 */ opcodeMap[(int)OpCode.Ble_un_s] = new BinaryBranchInstruction(OpCode.Ble_un_s); /* 0x037 */ opcodeMap[(int)OpCode.Blt_un_s] = new BinaryBranchInstruction(OpCode.Blt_un_s); /* 0x038 */ opcodeMap[(int)OpCode.Br] = new BranchInstruction(OpCode.Br); /* 0x039 */ opcodeMap[(int)OpCode.Brfalse] = new UnaryBranchInstruction(OpCode.Brfalse); /* 0x03A */ opcodeMap[(int)OpCode.Brtrue] = new UnaryBranchInstruction(OpCode.Brtrue); /* 0x03B */ opcodeMap[(int)OpCode.Beq] = new BinaryBranchInstruction(OpCode.Beq); /* 0x03C */ opcodeMap[(int)OpCode.Bge] = new BinaryBranchInstruction(OpCode.Bge); /* 0x03D */ opcodeMap[(int)OpCode.Bgt] = new BinaryBranchInstruction(OpCode.Bgt); /* 0x03E */ opcodeMap[(int)OpCode.Ble] = new BinaryBranchInstruction(OpCode.Ble); /* 0x03F */ opcodeMap[(int)OpCode.Blt] = new BinaryBranchInstruction(OpCode.Blt); /* 0x040 */ opcodeMap[(int)OpCode.Bne_un] = new BinaryBranchInstruction(OpCode.Bne_un); /* 0x041 */ opcodeMap[(int)OpCode.Bge_un] = new BinaryBranchInstruction(OpCode.Bge_un); /* 0x042 */ opcodeMap[(int)OpCode.Bgt_un] = new BinaryBranchInstruction(OpCode.Bgt_un); /* 0x043 */ opcodeMap[(int)OpCode.Ble_un] = new BinaryBranchInstruction(OpCode.Ble_un); /* 0x044 */ opcodeMap[(int)OpCode.Blt_un] = new BinaryBranchInstruction(OpCode.Blt_un); /* 0x045 */ opcodeMap[(int)OpCode.Switch] = new SwitchInstruction(OpCode.Switch); /* 0x046 */ opcodeMap[(int)OpCode.Ldind_i1] = new LdobjInstruction(OpCode.Ldind_i1); /* 0x047 */ opcodeMap[(int)OpCode.Ldind_u1] = new LdobjInstruction(OpCode.Ldind_u1); /* 0x048 */ opcodeMap[(int)OpCode.Ldind_i2] = new LdobjInstruction(OpCode.Ldind_i2); /* 0x049 */ opcodeMap[(int)OpCode.Ldind_u2] = new LdobjInstruction(OpCode.Ldind_u2); /* 0x04A */ opcodeMap[(int)OpCode.Ldind_i4] = new LdobjInstruction(OpCode.Ldind_i4); /* 0x04B */ opcodeMap[(int)OpCode.Ldind_u4] = new LdobjInstruction(OpCode.Ldind_u4); /* 0x04C */ opcodeMap[(int)OpCode.Ldind_i8] = new LdobjInstruction(OpCode.Ldind_i8); /* 0x04D */ opcodeMap[(int)OpCode.Ldind_i] = new LdobjInstruction(OpCode.Ldind_i); /* 0x04E */ opcodeMap[(int)OpCode.Ldind_r4] = new LdobjInstruction(OpCode.Ldind_r4); /* 0x04F */ opcodeMap[(int)OpCode.Ldind_r8] = new LdobjInstruction(OpCode.Ldind_r8); /* 0x050 */ opcodeMap[(int)OpCode.Ldind_ref] = new LdobjInstruction(OpCode.Ldind_ref); /* 0x051 */ opcodeMap[(int)OpCode.Stind_ref] = new StobjInstruction(OpCode.Stind_ref); /* 0x052 */ opcodeMap[(int)OpCode.Stind_i1] = new StobjInstruction(OpCode.Stind_i1); /* 0x053 */ opcodeMap[(int)OpCode.Stind_i2] = new StobjInstruction(OpCode.Stind_i2); /* 0x054 */ opcodeMap[(int)OpCode.Stind_i4] = new StobjInstruction(OpCode.Stind_i4); /* 0x055 */ opcodeMap[(int)OpCode.Stind_i8] = new StobjInstruction(OpCode.Stind_i8); /* 0x056 */ opcodeMap[(int)OpCode.Stind_r4] = new StobjInstruction(OpCode.Stind_r4); /* 0x057 */ opcodeMap[(int)OpCode.Stind_r8] = new StobjInstruction(OpCode.Stind_r8); /* 0x058 */ opcodeMap[(int)OpCode.Add] = new AddInstruction(OpCode.Add); /* 0x059 */ opcodeMap[(int)OpCode.Sub] = new SubInstruction(OpCode.Sub); /* 0x05A */ opcodeMap[(int)OpCode.Mul] = new MulInstruction(OpCode.Mul); /* 0x05B */ opcodeMap[(int)OpCode.Div] = new DivInstruction(OpCode.Div); /* 0x05C */ opcodeMap[(int)OpCode.Div_un] = new BinaryLogicInstruction(OpCode.Div_un); /* 0x05D */ opcodeMap[(int)OpCode.Rem] = new RemInstruction(OpCode.Rem); /* 0x05E */ opcodeMap[(int)OpCode.Rem_un] = new BinaryLogicInstruction(OpCode.Rem_un); /* 0x05F */ opcodeMap[(int)OpCode.And] = new BinaryLogicInstruction(OpCode.And); /* 0x060 */ opcodeMap[(int)OpCode.Or] = new BinaryLogicInstruction(OpCode.Or); /* 0x061 */ opcodeMap[(int)OpCode.Xor] = new BinaryLogicInstruction(OpCode.Xor); /* 0x062 */ opcodeMap[(int)OpCode.Shl] = new ShiftInstruction(OpCode.Shl); /* 0x063 */ opcodeMap[(int)OpCode.Shr] = new ShiftInstruction(OpCode.Shr); /* 0x064 */ opcodeMap[(int)OpCode.Shr_un] = new ShiftInstruction(OpCode.Shr_un); /* 0x065 */ opcodeMap[(int)OpCode.Neg] = new NegInstruction(OpCode.Neg); /* 0x066 */ opcodeMap[(int)OpCode.Not] = new NotInstruction(OpCode.Not); /* 0x067 */ opcodeMap[(int)OpCode.Conv_i1] = new ConversionInstruction(OpCode.Conv_i1); /* 0x068 */ opcodeMap[(int)OpCode.Conv_i2] = new ConversionInstruction(OpCode.Conv_i2); /* 0x069 */ opcodeMap[(int)OpCode.Conv_i4] = new ConversionInstruction(OpCode.Conv_i4); /* 0x06A */ opcodeMap[(int)OpCode.Conv_i8] = new ConversionInstruction(OpCode.Conv_i8); /* 0x06B */ opcodeMap[(int)OpCode.Conv_r4] = new ConversionInstruction(OpCode.Conv_r4); /* 0x06C */ opcodeMap[(int)OpCode.Conv_r8] = new ConversionInstruction(OpCode.Conv_r8); /* 0x06D */ opcodeMap[(int)OpCode.Conv_u4] = new ConversionInstruction(OpCode.Conv_u4); /* 0x06E */ opcodeMap[(int)OpCode.Conv_u8] = new ConversionInstruction(OpCode.Conv_u8); /* 0x06F */ opcodeMap[(int)OpCode.Callvirt] = new CallvirtInstruction(OpCode.Callvirt); /* 0x070 */ opcodeMap[(int)OpCode.Cpobj] = new CpobjInstruction(OpCode.Cpobj); /* 0x071 */ opcodeMap[(int)OpCode.Ldobj] = new LdobjInstruction(OpCode.Ldobj); /* 0x072 */ opcodeMap[(int)OpCode.Ldstr] = new LdstrInstruction(OpCode.Ldstr); /* 0x073 */ opcodeMap[(int)OpCode.Newobj] = new NewobjInstruction(OpCode.Newobj); /* 0x074 */ opcodeMap[(int)OpCode.Castclass] = new CastclassInstruction(OpCode.Castclass); /* 0x075 */ opcodeMap[(int)OpCode.Isinst] = new IsInstInstruction(OpCode.Isinst); /* 0x076 */ opcodeMap[(int)OpCode.Conv_r_un] = new ConversionInstruction(OpCode.Conv_r_un); /* Opcodes 0x077-0x078 undefined */ /* 0x079 */ opcodeMap[(int)OpCode.Unbox] = new UnboxInstruction(OpCode.Unbox); /* 0x07A */ opcodeMap[(int)OpCode.Throw] = new ThrowInstruction(OpCode.Throw); /* 0x07B */ opcodeMap[(int)OpCode.Ldfld] = new LdfldInstruction(OpCode.Ldfld); /* 0x07C */ opcodeMap[(int)OpCode.Ldflda] = new LdfldaInstruction(OpCode.Ldflda); /* 0x07D */ opcodeMap[(int)OpCode.Stfld] = new StfldInstruction(OpCode.Stfld); /* 0x07E */ opcodeMap[(int)OpCode.Ldsfld] = new LdsfldInstruction(OpCode.Ldsfld); /* 0x07F */ opcodeMap[(int)OpCode.Ldsflda] = new LdsfldaInstruction(OpCode.Ldsflda); /* 0x080 */ opcodeMap[(int)OpCode.Stsfld] = new StsfldInstruction(OpCode.Stsfld); /* 0x081 */ opcodeMap[(int)OpCode.Stobj] = new StobjInstruction(OpCode.Stobj); /* 0x082 */ opcodeMap[(int)OpCode.Conv_ovf_i1_un] = new ConversionInstruction(OpCode.Conv_ovf_i1_un); /* 0x083 */ opcodeMap[(int)OpCode.Conv_ovf_i2_un] = new ConversionInstruction(OpCode.Conv_ovf_i2_un); /* 0x084 */ opcodeMap[(int)OpCode.Conv_ovf_i4_un] = new ConversionInstruction(OpCode.Conv_ovf_i4_un); /* 0x085 */ opcodeMap[(int)OpCode.Conv_ovf_i8_un] = new ConversionInstruction(OpCode.Conv_ovf_i8_un); /* 0x086 */ opcodeMap[(int)OpCode.Conv_ovf_u1_un] = new ConversionInstruction(OpCode.Conv_ovf_u1_un); /* 0x087 */ opcodeMap[(int)OpCode.Conv_ovf_u2_un] = new ConversionInstruction(OpCode.Conv_ovf_u2_un); /* 0x088 */ opcodeMap[(int)OpCode.Conv_ovf_u4_un] = new ConversionInstruction(OpCode.Conv_ovf_u4_un); /* 0x089 */ opcodeMap[(int)OpCode.Conv_ovf_u8_un] = new ConversionInstruction(OpCode.Conv_ovf_u8_un); /* 0x08A */ opcodeMap[(int)OpCode.Conv_ovf_i_un] = new ConversionInstruction(OpCode.Conv_ovf_i_un); /* 0x08B */ opcodeMap[(int)OpCode.Conv_ovf_u_un] = new ConversionInstruction(OpCode.Conv_ovf_u_un); /* 0x08C */ opcodeMap[(int)OpCode.Box] = new BoxInstruction(OpCode.Box); /* 0x08D */ opcodeMap[(int)OpCode.Newarr] = new NewarrInstruction(OpCode.Newarr); /* 0x08E */ opcodeMap[(int)OpCode.Ldlen] = new LdlenInstruction(OpCode.Ldlen); /* 0x08F */ opcodeMap[(int)OpCode.Ldelema] = new LdelemaInstruction(OpCode.Ldelema); /* 0x090 */ opcodeMap[(int)OpCode.Ldelem_i1] = new LdelemInstruction(OpCode.Ldelem_i1); /* 0x091 */ opcodeMap[(int)OpCode.Ldelem_u1] = new LdelemInstruction(OpCode.Ldelem_u1); /* 0x092 */ opcodeMap[(int)OpCode.Ldelem_i2] = new LdelemInstruction(OpCode.Ldelem_i2); /* 0x093 */ opcodeMap[(int)OpCode.Ldelem_u2] = new LdelemInstruction(OpCode.Ldelem_u2); /* 0x094 */ opcodeMap[(int)OpCode.Ldelem_i4] = new LdelemInstruction(OpCode.Ldelem_i4); /* 0x095 */ opcodeMap[(int)OpCode.Ldelem_u4] = new LdelemInstruction(OpCode.Ldelem_u4); /* 0x096 */ opcodeMap[(int)OpCode.Ldelem_i8] = new LdelemInstruction(OpCode.Ldelem_i8); /* 0x097 */ opcodeMap[(int)OpCode.Ldelem_i] = new LdelemInstruction(OpCode.Ldelem_i); /* 0x098 */ opcodeMap[(int)OpCode.Ldelem_r4] = new LdelemInstruction(OpCode.Ldelem_r4); /* 0x099 */ opcodeMap[(int)OpCode.Ldelem_r8] = new LdelemInstruction(OpCode.Ldelem_r8); /* 0x09A */ opcodeMap[(int)OpCode.Ldelem_ref] = new LdelemInstruction(OpCode.Ldelem_ref); /* 0x09B */ opcodeMap[(int)OpCode.Stelem_i] = new StelemInstruction(OpCode.Stelem_i); /* 0x09C */ opcodeMap[(int)OpCode.Stelem_i1] = new StelemInstruction(OpCode.Stelem_i1); /* 0x09D */ opcodeMap[(int)OpCode.Stelem_i2] = new StelemInstruction(OpCode.Stelem_i2); /* 0x09E */ opcodeMap[(int)OpCode.Stelem_i4] = new StelemInstruction(OpCode.Stelem_i4); /* 0x09F */ opcodeMap[(int)OpCode.Stelem_i8] = new StelemInstruction(OpCode.Stelem_i8); /* 0x0A0 */ opcodeMap[(int)OpCode.Stelem_r4] = new StelemInstruction(OpCode.Stelem_r4); /* 0x0A1 */ opcodeMap[(int)OpCode.Stelem_r8] = new StelemInstruction(OpCode.Stelem_r8); /* 0x0A2 */ opcodeMap[(int)OpCode.Stelem_ref] = new StelemInstruction(OpCode.Stelem_ref); /* 0x0A3 */ opcodeMap[(int)OpCode.Ldelem] = new LdelemInstruction(OpCode.Ldelem); /* 0x0A4 */ opcodeMap[(int)OpCode.Stelem] = new StelemInstruction(OpCode.Stelem); /* 0x0A5 */ opcodeMap[(int)OpCode.Unbox_any] = new UnboxAnyInstruction(OpCode.Unbox_any); /* Opcodes 0x0A6-0x0B2 are undefined */ /* 0x0B3 */ opcodeMap[(int)OpCode.Conv_ovf_i1] = new ConversionInstruction(OpCode.Conv_ovf_i1); /* 0x0B4 */ opcodeMap[(int)OpCode.Conv_ovf_u1] = new ConversionInstruction(OpCode.Conv_ovf_u1); /* 0x0B5 */ opcodeMap[(int)OpCode.Conv_ovf_i2] = new ConversionInstruction(OpCode.Conv_ovf_i2); /* 0x0B6 */ opcodeMap[(int)OpCode.Conv_ovf_u2] = new ConversionInstruction(OpCode.Conv_ovf_u2); /* 0x0B7 */ opcodeMap[(int)OpCode.Conv_ovf_i4] = new ConversionInstruction(OpCode.Conv_ovf_i4); /* 0x0B8 */ opcodeMap[(int)OpCode.Conv_ovf_u4] = new ConversionInstruction(OpCode.Conv_ovf_u4); /* 0x0B9 */ opcodeMap[(int)OpCode.Conv_ovf_i8] = new ConversionInstruction(OpCode.Conv_ovf_i8); /* 0x0BA */ opcodeMap[(int)OpCode.Conv_ovf_u8] = new ConversionInstruction(OpCode.Conv_ovf_u8); /* Opcodes 0x0BB-0x0C1 are undefined */ /* 0x0C2 */ opcodeMap[(int)OpCode.Refanyval] = new RefanyvalInstruction(OpCode.Refanyval); /* 0x0C3 */ opcodeMap[(int)OpCode.Ckfinite] = new UnaryArithmeticInstruction(OpCode.Ckfinite); /* Opcodes 0x0C4-0x0C5 are undefined */ /* 0x0C6 */ opcodeMap[(int)OpCode.Mkrefany] = new MkrefanyInstruction(OpCode.Mkrefany); /* Opcodes 0x0C7-0x0CF are reserved */ /* 0x0D0 */ opcodeMap[(int)OpCode.Ldtoken] = new LdtokenInstruction(OpCode.Ldtoken); /* 0x0D1 */ opcodeMap[(int)OpCode.Conv_u2] = new ConversionInstruction(OpCode.Conv_u2); /* 0x0D2 */ opcodeMap[(int)OpCode.Conv_u1] = new ConversionInstruction(OpCode.Conv_u1); /* 0x0D3 */ opcodeMap[(int)OpCode.Conv_i] = new ConversionInstruction(OpCode.Conv_i); /* 0x0D4 */ opcodeMap[(int)OpCode.Conv_ovf_i] = new ConversionInstruction(OpCode.Conv_ovf_i); /* 0x0D5 */ opcodeMap[(int)OpCode.Conv_ovf_u] = new ConversionInstruction(OpCode.Conv_ovf_u); /* 0x0D6 */ opcodeMap[(int)OpCode.Add_ovf] = new ArithmeticOverflowInstruction(OpCode.Add_ovf); /* 0x0D7 */ opcodeMap[(int)OpCode.Add_ovf_un] = new ArithmeticOverflowInstruction(OpCode.Add_ovf_un); /* 0x0D8 */ opcodeMap[(int)OpCode.Mul_ovf] = new ArithmeticOverflowInstruction(OpCode.Mul_ovf); /* 0x0D9 */ opcodeMap[(int)OpCode.Mul_ovf_un] = new ArithmeticOverflowInstruction(OpCode.Mul_ovf_un); /* 0x0DA */ opcodeMap[(int)OpCode.Sub_ovf] = new ArithmeticOverflowInstruction(OpCode.Sub_ovf); /* 0x0DB */ opcodeMap[(int)OpCode.Sub_ovf_un] = new ArithmeticOverflowInstruction(OpCode.Sub_ovf_un); /* 0x0DC */ opcodeMap[(int)OpCode.Endfinally] = new EndFinallyInstruction(OpCode.Endfinally); /* 0x0DD */ opcodeMap[(int)OpCode.Leave] = new LeaveInstruction(OpCode.Leave); /* 0x0DE */ opcodeMap[(int)OpCode.Leave_s] = new LeaveInstruction(OpCode.Leave_s); /* 0x0DF */ opcodeMap[(int)OpCode.Stind_i] = new StobjInstruction(OpCode.Stind_i); /* 0x0E0 */ opcodeMap[(int)OpCode.Conv_u] = new ConversionInstruction(OpCode.Conv_u); /* Opcodes 0xE1-0xFF are reserved */ /* 0x100 */ opcodeMap[(int)OpCode.Arglist] = new ArglistInstruction(OpCode.Arglist); /* 0x101 */ opcodeMap[(int)OpCode.Ceq] = new BinaryComparisonInstruction(OpCode.Ceq); /* 0x102 */ opcodeMap[(int)OpCode.Cgt] = new BinaryComparisonInstruction(OpCode.Cgt); /* 0x103 */ opcodeMap[(int)OpCode.Cgt_un] = new BinaryComparisonInstruction(OpCode.Cgt_un); /* 0x104 */ opcodeMap[(int)OpCode.Clt] = new BinaryComparisonInstruction(OpCode.Clt); /* 0x105 */ opcodeMap[(int)OpCode.Clt_un] = new BinaryComparisonInstruction(OpCode.Clt_un); /* 0x106 */ opcodeMap[(int)OpCode.Ldftn] = new LdftnInstruction(OpCode.Ldftn); /* 0x107 */ opcodeMap[(int)OpCode.Ldvirtftn] = new LdvirtftnInstruction(OpCode.Ldvirtftn); /* Opcode 0x108 is undefined. */ /* 0x109 */ opcodeMap[(int)OpCode.Ldarg] = new LdargInstruction(OpCode.Ldarg); /* 0x10A */ opcodeMap[(int)OpCode.Ldarga] = new LdargaInstruction(OpCode.Ldarga); /* 0x10B */ opcodeMap[(int)OpCode.Starg] = new StargInstruction(OpCode.Starg); /* 0x10C */ opcodeMap[(int)OpCode.Ldloc] = new LdlocInstruction(OpCode.Ldloc); /* 0x10D */ opcodeMap[(int)OpCode.Ldloca] = new LdlocaInstruction(OpCode.Ldloca); /* 0x10E */ opcodeMap[(int)OpCode.Stloc] = new StlocInstruction(OpCode.Stloc); /* 0x10F */ opcodeMap[(int)OpCode.Localalloc] = new LocalallocInstruction(OpCode.Localalloc); /* Opcode 0x110 is undefined */ /* 0x111 */ opcodeMap[(int)OpCode.Endfilter] = new EndFilterInstruction(OpCode.Endfilter); /* 0x112 */ opcodeMap[(int)OpCode.PreUnaligned] = new UnalignedPrefixInstruction(OpCode.PreUnaligned); /* 0x113 */ opcodeMap[(int)OpCode.PreVolatile] = new VolatilePrefixInstruction(OpCode.PreVolatile); /* 0x114 */ opcodeMap[(int)OpCode.PreTail] = new TailPrefixInstruction(OpCode.PreTail); /* 0x115 */ opcodeMap[(int)OpCode.InitObj] = new InitObjInstruction(OpCode.InitObj); /* 0x116 */ opcodeMap[(int)OpCode.PreConstrained] = new ConstrainedPrefixInstruction(OpCode.PreConstrained); /* 0x117 */ opcodeMap[(int)OpCode.Cpblk] = new CpblkInstruction(OpCode.Cpblk); /* 0x118 */ opcodeMap[(int)OpCode.Initblk] = new InitblkInstruction(OpCode.Initblk); /* 0x119 */ opcodeMap[(int)OpCode.PreNo] = new NoPrefixInstruction(OpCode.PreNo); /* 0x11A */ opcodeMap[(int)OpCode.Rethrow] = new RethrowInstruction(OpCode.Rethrow); /* Opcode 0x11B is undefined */ /* 0x11C */ opcodeMap[(int)OpCode.Sizeof] = new SizeofInstruction(OpCode.Sizeof); /* 0x11D */ opcodeMap[(int)OpCode.Refanytype] = new RefanytypeInstruction(OpCode.Refanytype); /* 0x11E */ opcodeMap[(int)OpCode.PreReadOnly] = new ReadOnlyPrefixInstruction(OpCode.PreReadOnly); return opcodeMap; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using ID3; /* * The goal of this name space is just */ namespace System.IO { internal class FileStreamEx : FileStream { public FileStreamEx(string path, FileMode mode) : base(path, mode) { } /// <summary> /// Read string from current FileStream /// </summary> /// <param name="MaxLength">Maximum length that can read from stream</param> /// <param name="TEncoding">TextEcoding to read from Stream</param> /// <param name="DetectEncoding">Can method recognize encoding of text from Encoding inicators</param> /// <returns>string readed from current FileStream</returns> public string ReadText(int MaxLength, TextEncodings TEncoding, ref int ReadedLength, bool DetectEncoding) { if (MaxLength <= 0) return ""; long Pos = base.Position; MemoryStream MStream = new MemoryStream(); if (DetectEncoding && MaxLength >= 3) { byte[] Buffer = new byte[3]; base.Read(Buffer, 0, Buffer.Length); if (Buffer[0] == 0xFF && Buffer[1] == 0xFE) { // FF FE TEncoding = TextEncodings.UTF_16;// UTF-16 (LE) base.Position--; MaxLength -= 2; } else if (Buffer[0] == 0xFE && Buffer[1] == 0xFF) { // FE FF TEncoding = TextEncodings.UTF_16BE; base.Position--; MaxLength -= 2; } else if (Buffer[0] == 0xEF && Buffer[1] == 0xBB && Buffer[2] == 0xBF) { // EF BB BF TEncoding = TextEncodings.UTF8; MaxLength -= 3; } else base.Position -= 3; } bool Is2ByteSeprator = (TEncoding == TextEncodings.UTF_16 || TEncoding == TextEncodings.UTF_16BE); byte Buf; while (MaxLength > 0) { Buf = ReadByte(); // Read First/Next byte from stream if (Buf != 0) // if it's data byte MStream.WriteByte(Buf); else // if Buf == 0 { if (Is2ByteSeprator) { byte Temp = ReadByte(); if (Temp == 0) { if (MStream.Length % 2 == 1) MStream.WriteByte(Temp); break; } else { MStream.WriteByte(Buf); MStream.WriteByte(Temp); MaxLength--; } } else break; } MaxLength--; } if (MaxLength < 0) base.Position += MaxLength; ReadedLength -= Convert.ToInt32(base.Position - Pos); return GetEncoding(TEncoding).GetString(MStream.ToArray()); } public string ReadText(int MaxLength, TextEncodings TEncoding) { int i = 0; return ReadText(MaxLength, TEncoding, ref i, true); } public string ReadText(int MaxLength, TextEncodings TEncoding, bool DetectEncoding) { int i = 0; return ReadText(MaxLength, TEncoding, ref i, DetectEncoding); } /// <summary> /// Read a byte from current FileStream /// </summary> /// <returns>Readed byte</returns> public new byte ReadByte() { byte[] RByte = new byte[1]; // Use read method of FileStream instead of ReadByte // Becuase ReadByte return a SIGNED byte as integer // But what we want here is unsigned byte base.Read(RByte, 0, 1); return RByte[0]; } /// <summary> /// Read some bytes from FileStream and return it as unsigned integer /// </summary> /// <param name="Length">length of number in bytes</param> /// <returns>uint represent number readed from stream</returns> public uint ReadUInt(int Length) { if (Length > 4 || Length < 1) throw (new ArgumentOutOfRangeException("ReadUInt method can read 1-4 byte(s)")); byte[] Buf = new byte[Length]; byte[] RBuf = new byte[4]; base.Read(Buf, 0, Length); Buf.CopyTo(RBuf, 4 - Buf.Length); Array.Reverse(RBuf); return BitConverter.ToUInt32(RBuf, 0); } /// <summary> /// Read data from specific FileStream and return it as MemoryStream /// </summary> /// <param name="Length">Length that must read</param> /// <returns>MemoryStream readed from FileStream</returns> public MemoryStream ReadData(int Length) { MemoryStream ms; byte[] Buf = new byte[Length]; base.Read(Buf, 0, Length); ms = new MemoryStream(); ms.Write(Buf, 0, Length); return ms; } /// <summary> /// Indicate if file contain ID3v2 information /// </summary> /// <returns>true if contain otherwise false</returns> public bool HaveID3v2() { /* if the first three characters in begining of a file * be "ID3". that mpeg file contain ID3v2 information */ string Iden = ReadText(3, TextEncodings.Ascii); if (Iden == "ID3") return true; else return false; } /// <summary> /// Indicate if current File have ID3v1 /// </summary> public bool HaveID3v1() { base.Seek(-128, SeekOrigin.End); string Tag = ReadText(3, TextEncodings.Ascii); if (Tag == "TAG") return true; else return false; } /// <summary> /// Read ID3 version from current file /// </summary> /// <returns>Version contain ID3v2 version</returns> public Version ReadVersion() { return new Version("2." + ReadByte().ToString() + "." + ReadByte().ToString()); } /// <summary> /// Read ID3 Size /// </summary> /// <returns>ID3 Length size</returns> public int ReadSize() { /* ID3 Size is like: * 0XXXXXXXb 0XXXXXXXb 0XXXXXXXb 0XXXXXXXb (b means binary) * the zero bytes must ignore, so we have 28 bits number = 0x1000 0000 (maximum) * it's equal to 256MB */ int RInt; RInt = ReadByte() * 0x200000; RInt += ReadByte() * 0x4000; RInt += ReadByte() * 0x80; RInt += ReadByte(); return RInt; } public static Encoding GetEncoding(TextEncodings TEncoding) { switch (TEncoding) { case TextEncodings.UTF_16: return Encoding.Unicode; case TextEncodings.UTF_16BE: return Encoding.GetEncoding("UTF-16BE"); case TextEncodings.UTF8: return Encoding.UTF8; default: return Encoding.Default; } } } }
using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.Msagl.Drawing; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.DataStructures; using MsaglRectangle = Microsoft.Msagl.Core.Geometry.Rectangle; using Color = System.Windows.Media.Color; using DrawingGraph = Microsoft.Msagl.Drawing.Graph; using GeometryEdge = Microsoft.Msagl.Core.Layout.Edge; using GeometryNode = Microsoft.Msagl.Core.Layout.Node; using DrawingEdge = Microsoft.Msagl.Drawing.Edge; using DrawingNode = Microsoft.Msagl.Drawing.Node; using MsaglPoint = Microsoft.Msagl.Core.Geometry.Point; using WinPoint = System.Windows.Point; using MsaglStyle = Microsoft.Msagl.Drawing.Style; using MsaglLineSegment = Microsoft.Msagl.Core.Geometry.Curves.LineSegment; using WinLineSegment = System.Windows.Media.LineSegment; using WinSize = System.Windows.Size; namespace Microsoft.Msagl.GraphControlSilverlight { /// <summary> /// exposes some drawing functionality /// </summary> public sealed class Draw { /// <summary> /// private constructor /// </summary> Draw() { } static double doubleCircleOffsetRatio = 0.9; internal static double DoubleCircleOffsetRatio { get { return doubleCircleOffsetRatio; } } internal static float dashSize = 0.05f; //inches /// <summary> /// A color converter /// </summary> /// <param name="gleeColor"></param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Msagl")] public static Color MsaglColorToDrawingColor(Drawing.Color gleeColor) { return Color.FromArgb(gleeColor.A, gleeColor.R, gleeColor.G, gleeColor.B); } internal static void DrawUnderlyingPolyline(PathGeometry pg, DEdge edge) { IEnumerable<WinPoint> points = edge.GeometryEdge.UnderlyingPolyline.Select(p => WinPoint(p)); PathFigure pf = new PathFigure() { IsFilled = false, IsClosed = false, StartPoint = points.First() }; foreach (WinPoint p in points) { if (p != points.First()) pf.Segments.Add(new WinLineSegment() { Point = p }); PathFigure circle = new PathFigure() { IsFilled = false, IsClosed = true, StartPoint = new WinPoint(p.X - edge.RadiusOfPolylineCorner, p.Y) }; circle.Segments.Add( new ArcSegment() { Size = new WinSize(edge.RadiusOfPolylineCorner, edge.RadiusOfPolylineCorner), SweepDirection = SweepDirection.Clockwise, Point = new WinPoint(p.X + edge.RadiusOfPolylineCorner, p.Y) }); circle.Segments.Add( new ArcSegment() { Size = new WinSize(edge.RadiusOfPolylineCorner, edge.RadiusOfPolylineCorner), SweepDirection = SweepDirection.Clockwise, Point = new WinPoint(p.X - edge.RadiusOfPolylineCorner, p.Y) }); pg.Figures.Add(circle); } pg.Figures.Add(pf); } internal static void DrawEdgeArrows(PathGeometry pg, DrawingEdge edge, bool fillAtSource, bool fillAtTarget) { ArrowAtTheEnd(pg, edge, fillAtTarget); ArrowAtTheBeginning(pg, edge, fillAtSource); } private static void ArrowAtTheBeginning(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.GeometryEdge != null && edge.Attr.ArrowAtSource) DrawArrowAtTheBeginningWithControlPoints(pg, edge, fill); } private static void DrawArrowAtTheBeginningWithControlPoints(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.EdgeCurve != null) if (edge.Attr.ArrowheadAtSource == ArrowStyle.None) DrawLine(pg, edge.EdgeCurve.Start, edge.ArrowAtSourcePosition); else DrawArrow(pg, edge.EdgeCurve.Start, edge.ArrowAtSourcePosition, edge.Attr.LineWidth, edge.Attr.ArrowheadAtSource, fill); } private static void ArrowAtTheEnd(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.GeometryEdge != null && edge.Attr.ArrowAtTarget) DrawArrowAtTheEndWithControlPoints(pg, edge, fill); } const float toDegrees = 180 / (float)Math.PI; static void DrawArrowAtTheEndWithControlPoints(PathGeometry pg, DrawingEdge edge, bool fill) { if (edge.EdgeCurve != null) if (edge.Attr.ArrowheadAtTarget == ArrowStyle.None) DrawLine(pg, edge.EdgeCurve.End, edge.ArrowAtTargetPosition); else DrawArrow(pg, edge.EdgeCurve.End, edge.ArrowAtTargetPosition, edge.Attr.LineWidth, edge.Attr.ArrowheadAtTarget, fill); } internal static WinPoint WinPoint(MsaglPoint p) { return new WinPoint(p.X, p.Y); } internal static void CreateGraphicsPathFromCurve(PathFigure pathFigure, Curve curve) { foreach (ICurve seg in curve.Segments) { if (seg is CubicBezierSegment) { var bezSeg = seg as CubicBezierSegment; pathFigure.Segments.Add(new BezierSegment { Point1 = WinPoint(bezSeg.B(1)), Point2 = WinPoint(bezSeg.B(2)), Point3 = WinPoint(bezSeg.B(3)) }); } else if (seg is Ellipse) { var ellipse = seg as Ellipse; pathFigure.Segments.Add(new ArcSegment() { Size = new WinSize(ellipse.AxisA.Length, ellipse.AxisB.Length), SweepDirection = ellipse.OrientedCounterclockwise() ? SweepDirection.Clockwise : SweepDirection.Counterclockwise, Point = WinPoint(ellipse.End) }); } else pathFigure.Segments.Add(new WinLineSegment() { Point = WinPoint(seg.End) }); } } internal static PathFigure CreateGraphicsPath(ICurve iCurve) { var pathFigure = new PathFigure { StartPoint = WinPoint(iCurve.Start), IsFilled = false, IsClosed = false }; if (iCurve is Curve) { CreateGraphicsPathFromCurve(pathFigure, iCurve as Curve); } else if (iCurve is Polyline) { var polyline = iCurve as Polyline; pathFigure.IsClosed = polyline.Closed; foreach (var p in polyline.PolylinePoints) { pathFigure.Segments.Add(new WinLineSegment() { Point = WinPoint(p.Point) }); } } else if (iCurve is CubicBezierSegment) { var bezSeg = iCurve as CubicBezierSegment; pathFigure.Segments.Add(new BezierSegment { Point1 = WinPoint(bezSeg.B(1)), Point2 = WinPoint(bezSeg.B(2)), Point3 = WinPoint(bezSeg.B(3)) }); } else if (iCurve is MsaglLineSegment) { var segment = iCurve as MsaglLineSegment; pathFigure.Segments.Add( new WinLineSegment() { Point = WinPoint(segment.End) }); } else if (iCurve is Ellipse) { var ellipse = iCurve as Ellipse; pathFigure.Segments.Add( new ArcSegment() { Size = new WinSize(ellipse.BoundingBox.Width / 2, ellipse.BoundingBox.Height / 2), SweepDirection = SweepDirection.Clockwise, Point = WinPoint(ellipse[Math.PI]) }); pathFigure.Segments.Add( new ArcSegment() { Size = new WinSize(ellipse.BoundingBox.Width / 2, ellipse.BoundingBox.Height / 2), SweepDirection = SweepDirection.Clockwise, Point = WinPoint(ellipse.Start) }); } else if (iCurve is RoundedRect) { CreateGraphicsPathFromCurve(pathFigure, (iCurve as RoundedRect).Curve); } return pathFigure; } const double arrowAngle = 25.0; //degrees internal static void DrawArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, double thickness, ArrowStyle arrowStyle, bool fill) { switch (arrowStyle) { case ArrowStyle.NonSpecified: case ArrowStyle.Normal: DrawNormalArrow(pg, start, end, thickness, fill); break; case ArrowStyle.Tee: DrawTeeArrow(pg, start, end, fill); break; case ArrowStyle.Diamond: DrawDiamondArrow(pg, start, end); break; case ArrowStyle.ODiamond: throw new NotImplementedException(); case ArrowStyle.Generalization: throw new NotImplementedException(); default: throw new InvalidOperationException(); } } internal static void DrawNormalArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, double thickness, bool fill) { MsaglPoint dir = end - start; MsaglPoint h = dir; dir /= dir.Length; // compensate for line thickness end -= dir * thickness / ((double)Math.Tan(arrowAngle * (Math.PI / 180.0))); var s = new MsaglPoint(-dir.Y, dir.X); s *= h.Length * ((double)Math.Tan(arrowAngle * 0.5 * (Math.PI / 180.0))); PathFigure pf = new PathFigure() { IsFilled = fill, IsClosed = true }; pf.StartPoint = WinPoint(start + s); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start - s) }); pg.Figures.Add(pf); } // For tee arrows, "fill" indicates whether the line should continue up to the node's boundary. static void DrawTeeArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end, bool fill) { MsaglPoint dir = end - start; MsaglPoint h = dir; dir /= dir.Length; if (fill) { PathFigure pf = new PathFigure(); pf.StartPoint = WinPoint(start); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pg.Figures.Add(pf); } var s = new MsaglPoint(-dir.Y, dir.X); s *= 2 * h.Length * ((float)Math.Tan(arrowAngle * 0.5f * (Math.PI / 180.0))); s += s.Normalize(); PathFigure pf2 = new PathFigure(); pf2.StartPoint = WinPoint(start + s); pf2.Segments.Add(new WinLineSegment() { Point = WinPoint(start - s) }); pg.Figures.Add(pf2); } internal static void DrawDiamondArrow(PathGeometry pg, MsaglPoint start, MsaglPoint end) { MsaglPoint dir = end - start; MsaglPoint h = dir; dir /= dir.Length; var s = new MsaglPoint(-dir.Y, dir.X); PathFigure pf = new PathFigure(); pf.StartPoint = WinPoint(start - dir); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start + (h / 2) + s * (h.Length / 3)) }); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pf.Segments.Add(new WinLineSegment() { Point = WinPoint(start + (h / 2) - s * (h.Length / 3)) }); pf.IsClosed = true; pg.Figures.Add(pf); } internal static void DrawLine(PathGeometry pg, MsaglPoint start, MsaglPoint end) { PathFigure pf = new PathFigure() { StartPoint = WinPoint(start) }; pf.Segments.Add(new WinLineSegment() { Point = WinPoint(end) }); pg.Figures.Add(pf); } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Xml.Schema; using System.Diagnostics; using System.Reflection; namespace XmlNotepad { /// <summary> /// This class keeps track of DOM node line locations so you can do error reporting. /// </summary> class DomLoader { Dictionary<XmlNode, LineInfo> lineTable = new Dictionary<XmlNode, LineInfo>(); XmlDocument doc; XmlReader reader; IServiceProvider site; const string xsiUri = "http://www.w3.org/2001/XMLSchema-instance"; public DomLoader(IServiceProvider site) { this.site = site; } void AddToTable(XmlNode node) { lineTable[node] = new LineInfo(reader); } public LineInfo GetLineInfo(XmlNode node) { if (node != null && lineTable.ContainsKey(node)) { return lineTable[node]; } return null; } public XmlDocument Load(XmlReader r) { this.lineTable = new Dictionary<XmlNode, LineInfo>(); this.doc = new XmlDocument(); this.doc.XmlResolver = new XmlProxyResolver(this.site); this.doc.Schemas.XmlResolver = new XmlProxyResolver(this.site); SetLoading(this.doc, true); try { this.reader = r; AddToTable(this.doc); LoadDocument(); } finally { SetLoading(this.doc, false); } return doc; } void SetLoading(XmlDocument doc, bool flag) { FieldInfo fi = this.doc.GetType().GetField("isLoading", BindingFlags.Instance | BindingFlags.NonPublic); if (fi != null) { fi.SetValue(doc, flag); } } private void LoadDocument() { bool preserveWhitespace = false; XmlReader r = this.reader; XmlNode parent = this.doc; XmlElement element; while (r.Read()) { XmlNode node = null; switch (r.NodeType) { case XmlNodeType.Element: bool fEmptyElement = r.IsEmptyElement; element = doc.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); AddToTable(element); element.IsEmpty = fEmptyElement; ReadAttributes(r, element); if (!fEmptyElement) { parent.AppendChild(element); parent = element; continue; } node = element; break; case XmlNodeType.EndElement: if (parent.ParentNode == null) { // syntax error in document. IXmlLineInfo li = (IXmlLineInfo)r; throw new XmlException(string.Format(SR.UnexpectedToken, "</"+r.LocalName+">", li.LineNumber, li.LinePosition), null, li.LineNumber, li.LinePosition); } parent = parent.ParentNode; continue; case XmlNodeType.EntityReference: if (r.CanResolveEntity) { r.ResolveEntity(); } continue; case XmlNodeType.EndEntity: continue; case XmlNodeType.Attribute: node = LoadAttributeNode(); break; case XmlNodeType.Text: node = doc.CreateTextNode(r.Value); AddToTable(node); break; case XmlNodeType.SignificantWhitespace: node = doc.CreateSignificantWhitespace(r.Value); AddToTable(node); break; case XmlNodeType.Whitespace: if (preserveWhitespace) { node = doc.CreateWhitespace(r.Value); AddToTable(node); break; } else { continue; } case XmlNodeType.CDATA: node = doc.CreateCDataSection(r.Value); AddToTable(node); break; case XmlNodeType.XmlDeclaration: node = LoadDeclarationNode(); break; case XmlNodeType.ProcessingInstruction: node = doc.CreateProcessingInstruction(r.Name, r.Value); AddToTable(node); if (string.IsNullOrEmpty(this.xsltFileName) && r.Name == "xml-stylesheet") { string href = ParseXsltArgs(((XmlProcessingInstruction)node).Data); if (!string.IsNullOrEmpty(href)) this.xsltFileName = href; } break; case XmlNodeType.Comment: node = doc.CreateComment(r.Value); AddToTable(node); break; case XmlNodeType.DocumentType: { string pubid = r.GetAttribute("PUBLIC"); string sysid = r.GetAttribute("SYSTEM"); node = doc.CreateDocumentType(r.Name, pubid, sysid, r.Value); break; } default: UnexpectedNodeType(r.NodeType); break; } Debug.Assert(node != null); Debug.Assert(parent != null); if (parent != null) { parent.AppendChild(node); } } } public static string ParseXsltArgs(string data) { try { XmlDocument doc = new XmlDocument(); doc.LoadXml("<xsl " + data + "/>"); XmlElement root = doc.DocumentElement; if (root.GetAttribute("type") == "text/xsl") { return root.GetAttribute("href"); } } catch (Exception){ } return null; } private void ReadAttributes(XmlReader r, XmlElement element) { if (r.MoveToFirstAttribute()) { XmlAttributeCollection attributes = element.Attributes; do { XmlAttribute attr = LoadAttributeNode(); attributes.Append(attr); // special case for load } while (r.MoveToNextAttribute()); r.MoveToElement(); } } string xsltFileName=null; public string XsltFileName { get { return this.xsltFileName; } } private XmlAttribute LoadAttributeNode() { Debug.Assert(reader.NodeType == XmlNodeType.Attribute); XmlReader r = reader; XmlAttribute attr = doc.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI); AddToTable(attr); XmlNode parent = attr; while (r.ReadAttributeValue()) { XmlNode node = null; switch (r.NodeType) { case XmlNodeType.Text: node = doc.CreateTextNode(r.Value); AddToTable(node); break; case XmlNodeType.EntityReference: if (r.CanResolveEntity) { r.ResolveEntity(); } continue; case XmlNodeType.EndEntity: continue; default: UnexpectedNodeType(r.NodeType); break; } Debug.Assert(node != null); parent.AppendChild(node); } if (attr.NamespaceURI == xsiUri) { HandleXsiAttribute(attr); } return attr; } void HandleXsiAttribute(XmlAttribute a) { switch (a.LocalName) { case "schemaLocation": LoadSchemaLocations(a.Value); break; case "noNamespaceSchemaLocation": LoadSchema(a.Value); break; } } void LoadSchemaLocations(string pairs) { string[] words = pairs.Split(new char[] { ' ', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0, n = words.Length; i < n; i++) { if (i + 1 < n) { i++; string url = words[i]; LoadSchema(url); } } } void LoadSchema(string fname) { try { Uri resolved = new Uri(new Uri(reader.BaseURI), fname); this.doc.Schemas.Add(null, resolved.AbsoluteUri); } catch (Exception) { } } private XmlDeclaration LoadDeclarationNode() { Debug.Assert(reader.NodeType == XmlNodeType.XmlDeclaration); //parse data XmlDeclaration decl = doc.CreateXmlDeclaration("1.0",null,null); AddToTable(decl); // Try first to use the reader to get the xml decl "attributes". Since not all readers are required to support this, it is possible to have // implementations that do nothing while (reader.MoveToNextAttribute()) { switch (reader.Name) { case "version": break; case "encoding": decl.Encoding = reader.Value; break; case "standalone": decl.Standalone = reader.Value; break; default: Debug.Assert(false); break; } } return decl; } void UnexpectedNodeType(XmlNodeType type) { IXmlLineInfo li = (IXmlLineInfo)reader; throw new XmlException(string.Format(SR.UnexpectedNodeType, type.ToString()), null, li.LineNumber, li.LinePosition); } } public class LineInfo : IXmlLineInfo { int line, col; string baseUri; IXmlSchemaInfo info; internal LineInfo(int line, int col) { this.line = line; this.col = col; } internal LineInfo(XmlReader reader) { IXmlLineInfo li = reader as IXmlLineInfo; if (li != null) { this.line = li.LineNumber; this.col = li.LinePosition; this.baseUri = reader.BaseURI; this.info = reader.SchemaInfo; } } public bool HasLineInfo() { return true; } public int LineNumber { get { return this.line; } } public int LinePosition { get { return this.col; } } public string BaseUri { get { return this.baseUri; } } public IXmlSchemaInfo SchemaInfo { get { return this.info; } } } }
//Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using Microsoft.WindowsAPI.Internal; namespace Microsoft.WindowsAPI.Shell { /// <summary> /// Defines properties for known folders that identify the path of standard known folders. /// </summary> public static class KnownFolders { /// <summary> /// Gets a strongly-typed read-only collection of all the registered known folders. /// </summary> public static ICollection<IKnownFolder> All { get { return GetAllFolders(); } } private static ReadOnlyCollection<IKnownFolder> GetAllFolders() { // Should this method be thread-safe?? (It'll take a while // to get a list of all the known folders, create the managed wrapper // and return the read-only collection. IList<IKnownFolder> foldersList = new List<IKnownFolder>(); uint count; IntPtr folders = IntPtr.Zero; try { KnownFolderManagerClass knownFolderManager = new KnownFolderManagerClass(); knownFolderManager.GetFolderIds(out folders, out count); if (count > 0 && folders != IntPtr.Zero) { // Loop through all the KnownFolderID elements for (int i = 0; i < count; i++) { // Read the current pointer IntPtr current = new IntPtr(folders.ToInt64() + (Marshal.SizeOf(typeof(Guid)) * i)); // Convert to Guid Guid knownFolderID = (Guid)Marshal.PtrToStructure(current, typeof(Guid)); IKnownFolder kf = KnownFolderHelper.FromKnownFolderIdInternal(knownFolderID); // Add to our collection if it's not null (some folders might not exist on the system // or we could have an exception that resulted in the null return from above method call if (kf != null) { foldersList.Add(kf); } } } } finally { if (folders != IntPtr.Zero) { Marshal.FreeCoTaskMem(folders); } } return new ReadOnlyCollection<IKnownFolder>(foldersList); } private static IKnownFolder GetKnownFolder(Guid guid) { return KnownFolderHelper.FromKnownFolderId(guid); } #region Default Known Folders /// <summary> /// Gets the metadata for the <b>Computer</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Computer { get { return GetKnownFolder( FolderIdentifiers.Computer); } } /// <summary> /// Gets the metadata for the <b>Conflict</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Conflict { get { return GetKnownFolder( FolderIdentifiers.Conflict); } } /// <summary> /// Gets the metadata for the <b>ControlPanel</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ControlPanel { get { return GetKnownFolder( FolderIdentifiers.ControlPanel); } } /// <summary> /// Gets the metadata for the <b>Desktop</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Desktop { get { return GetKnownFolder( FolderIdentifiers.Desktop); } } /// <summary> /// Gets the metadata for the <b>Internet</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Internet { get { return GetKnownFolder( FolderIdentifiers.Internet); } } /// <summary> /// Gets the metadata for the <b>Network</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Network { get { return GetKnownFolder( FolderIdentifiers.Network); } } /// <summary> /// Gets the metadata for the <b>Printers</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Printers { get { return GetKnownFolder( FolderIdentifiers.Printers); } } /// <summary> /// Gets the metadata for the <b>SyncManager</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SyncManager { get { return GetKnownFolder( FolderIdentifiers.SyncManager); } } /// <summary> /// Gets the metadata for the <b>Connections</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Connections { get { return GetKnownFolder( FolderIdentifiers.Connections); } } /// <summary> /// Gets the metadata for the <b>SyncSetup</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SyncSetup { get { return GetKnownFolder( FolderIdentifiers.SyncSetup); } } /// <summary> /// Gets the metadata for the <b>SyncResults</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SyncResults { get { return GetKnownFolder( FolderIdentifiers.SyncResults); } } /// <summary> /// Gets the metadata for the <b>RecycleBin</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder RecycleBin { get { return GetKnownFolder( FolderIdentifiers.RecycleBin); } } /// <summary> /// Gets the metadata for the <b>Fonts</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Fonts { get { return GetKnownFolder(FolderIdentifiers.Fonts); } } /// <summary> /// Gets the metadata for the <b>Startup</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Startup { get { return GetKnownFolder(FolderIdentifiers.Startup); } } /// <summary> /// Gets the metadata for the <b>Programs</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Programs { get { return GetKnownFolder(FolderIdentifiers.Programs); } } /// <summary> /// Gets the metadata for the per-user <b>StartMenu</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder StartMenu { get { return GetKnownFolder(FolderIdentifiers.StartMenu); } } /// <summary> /// Gets the metadata for the per-user <b>Recent</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Recent { get { return GetKnownFolder(FolderIdentifiers.Recent); } } /// <summary> /// Gets the metadata for the per-user <b>SendTo</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SendTo { get { return GetKnownFolder(FolderIdentifiers.SendTo); } } /// <summary> /// Gets the metadata for the per-user <b>Documents</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Documents { get { return GetKnownFolder(FolderIdentifiers.Documents); } } /// <summary> /// Gets the metadata for the per-user <b>Favorites</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Favorites { get { return GetKnownFolder(FolderIdentifiers.Favorites); } } /// <summary> /// Gets the metadata for the <b>NetHood</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder NetHood { get { return GetKnownFolder(FolderIdentifiers.NetHood); } } /// <summary> /// Gets the metadata for the <b>PrintHood</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PrintHood { get { return GetKnownFolder(FolderIdentifiers.PrintHood); } } /// <summary> /// Gets the metadata for the <b>Templates</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Templates { get { return GetKnownFolder(FolderIdentifiers.Templates); } } /// <summary> /// Gets the metadata for the <b>CommonStartup</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder CommonStartup { get { return GetKnownFolder(FolderIdentifiers.CommonStartup); } } /// <summary> /// Gets the metadata for the <b>CommonPrograms</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder CommonPrograms { get { return GetKnownFolder(FolderIdentifiers.CommonPrograms); } } /// <summary> /// Gets the metadata for the <b>CommonStartMenu</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder CommonStartMenu { get { return GetKnownFolder(FolderIdentifiers.CommonStartMenu); } } /// <summary> /// Gets the metadata for the <b>PublicDesktop</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PublicDesktop { get { return GetKnownFolder(FolderIdentifiers.PublicDesktop); } } /// <summary> /// Gets the metadata for the <b>ProgramData</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ProgramData { get { return GetKnownFolder(FolderIdentifiers.ProgramData); } } /// <summary> /// Gets the metadata for the <b>CommonTemplates</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder CommonTemplates { get { return GetKnownFolder(FolderIdentifiers.CommonTemplates); } } /// <summary> /// Gets the metadata for the <b>PublicDocuments</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PublicDocuments { get { return GetKnownFolder(FolderIdentifiers.PublicDocuments); } } /// <summary> /// Gets the metadata for the <b>RoamingAppData</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder RoamingAppData { get { return GetKnownFolder(FolderIdentifiers.RoamingAppData); } } /// <summary> /// Gets the metadata for the per-user <b>LocalAppData</b> /// folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder LocalAppData { get { return GetKnownFolder(FolderIdentifiers.LocalAppData); } } /// <summary> /// Gets the metadata for the <b>LocalAppDataLow</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder LocalAppDataLow { get { return GetKnownFolder(FolderIdentifiers.LocalAppDataLow); } } /// <summary> /// Gets the metadata for the <b>InternetCache</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder InternetCache { get { return GetKnownFolder(FolderIdentifiers.InternetCache); } } /// <summary> /// Gets the metadata for the <b>Cookies</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Cookies { get { return GetKnownFolder(FolderIdentifiers.Cookies); } } /// <summary> /// Gets the metadata for the <b>History</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder History { get { return GetKnownFolder(FolderIdentifiers.History); } } /// <summary> /// Gets the metadata for the <b>System</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder System { get { return GetKnownFolder(FolderIdentifiers.System); } } /// <summary> /// Gets the metadata for the <b>SystemX86</b> /// folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SystemX86 { get { return GetKnownFolder(FolderIdentifiers.SystemX86); } } /// <summary> /// Gets the metadata for the <b>Windows</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Windows { get { return GetKnownFolder(FolderIdentifiers.Windows); } } /// <summary> /// Gets the metadata for the <b>Profile</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Profile { get { return GetKnownFolder(FolderIdentifiers.Profile); } } /// <summary> /// Gets the metadata for the per-user <b>Pictures</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Pictures { get { return GetKnownFolder(FolderIdentifiers.Pictures); } } /// <summary> /// Gets the metadata for the <b>ProgramFilesX86</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ProgramFilesX86 { get { return GetKnownFolder(FolderIdentifiers.ProgramFilesX86); } } /// <summary> /// Gets the metadata for the <b>ProgramFilesCommonX86</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ProgramFilesCommonX86 { get { return GetKnownFolder(FolderIdentifiers.ProgramFilesCommonX86); } } /// <summary> /// Gets the metadata for the <b>ProgramsFilesX64</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ProgramFilesX64 { get { return GetKnownFolder(FolderIdentifiers.ProgramFilesX64); } } /// <summary> /// Gets the metadata for the <b> ProgramFilesCommonX64</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ProgramFilesCommonX64 { get { return GetKnownFolder(FolderIdentifiers.ProgramFilesCommonX64); } } /// <summary> /// Gets the metadata for the <b>ProgramFiles</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ProgramFiles { get { return GetKnownFolder(FolderIdentifiers.ProgramFiles); } } /// <summary> /// Gets the metadata for the <b>ProgramFilesCommon</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ProgramFilesCommon { get { return GetKnownFolder(FolderIdentifiers.ProgramFilesCommon); } } /// <summary> /// Gets the metadata for the <b>AdminTools</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder AdminTools { get { return GetKnownFolder(FolderIdentifiers.AdminTools); } } /// <summary> /// Gets the metadata for the <b>CommonAdminTools</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder CommonAdminTools { get { return GetKnownFolder(FolderIdentifiers.CommonAdminTools); } } /// <summary> /// Gets the metadata for the per-user <b>Music</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Music { get { return GetKnownFolder(FolderIdentifiers.Music); } } /// <summary> /// Gets the metadata for the <b>Videos</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Videos { get { return GetKnownFolder(FolderIdentifiers.Videos); } } /// <summary> /// Gets the metadata for the <b>PublicPictures</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PublicPictures { get { return GetKnownFolder(FolderIdentifiers.PublicPictures); } } /// <summary> /// Gets the metadata for the <b>PublicMusic</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PublicMusic { get { return GetKnownFolder(FolderIdentifiers.PublicMusic); } } /// <summary> /// Gets the metadata for the <b>PublicVideos</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PublicVideos { get { return GetKnownFolder(FolderIdentifiers.PublicVideos); } } /// <summary> /// Gets the metadata for the <b>ResourceDir</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ResourceDir { get { return GetKnownFolder(FolderIdentifiers.ResourceDir); } } /// <summary> /// Gets the metadata for the <b>LocalizedResourcesDir</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder LocalizedResourcesDir { get { return GetKnownFolder(FolderIdentifiers.LocalizedResourcesDir); } } /// <summary> /// Gets the metadata for the <b>CommonOEMLinks</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder CommonOemLinks { get { return GetKnownFolder(FolderIdentifiers.CommonOEMLinks); } } /// <summary> /// Gets the metadata for the <b>CDBurning</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder CDBurning { get { return GetKnownFolder(FolderIdentifiers.CDBurning); } } /// <summary> /// Gets the metadata for the <b>UserProfiles</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder UserProfiles { get { return GetKnownFolder(FolderIdentifiers.UserProfiles); } } /// <summary> /// Gets the metadata for the <b>Playlists</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Playlists { get { return GetKnownFolder(FolderIdentifiers.Playlists); } } /// <summary> /// Gets the metadata for the <b>SamplePlaylists</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SamplePlaylists { get { return GetKnownFolder(FolderIdentifiers.SamplePlaylists); } } /// <summary> /// Gets the metadata for the <b>SampleMusic</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SampleMusic { get { return GetKnownFolder(FolderIdentifiers.SampleMusic); } } /// <summary> /// Gets the metadata for the <b>SamplePictures</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SamplePictures { get { return GetKnownFolder(FolderIdentifiers.SamplePictures); } } /// <summary> /// Gets the metadata for the <b>SampleVideos</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SampleVideos { get { return GetKnownFolder(FolderIdentifiers.SampleVideos); } } /// <summary> /// Gets the metadata for the <b>PhotoAlbums</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PhotoAlbums { get { return GetKnownFolder(FolderIdentifiers.PhotoAlbums); } } /// <summary> /// Gets the metadata for the <b>Public</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Public { get { return GetKnownFolder(FolderIdentifiers.Public); } } /// <summary> /// Gets the metadata for the <b>ChangeRemovePrograms</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder ChangeRemovePrograms { get { return GetKnownFolder(FolderIdentifiers.ChangeRemovePrograms); } } /// <summary> /// Gets the metadata for the <b>AppUpdates</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder AppUpdates { get { return GetKnownFolder(FolderIdentifiers.AppUpdates); } } /// <summary> /// Gets the metadata for the <b>AddNewPrograms</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder AddNewPrograms { get { return GetKnownFolder(FolderIdentifiers.AddNewPrograms); } } /// <summary> /// Gets the metadata for the per-user <b>Downloads</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Downloads { get { return GetKnownFolder(FolderIdentifiers.Downloads); } } /// <summary> /// Gets the metadata for the <b>PublicDownloads</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PublicDownloads { get { return GetKnownFolder(FolderIdentifiers.PublicDownloads); } } /// <summary> /// Gets the metadata for the per-user <b>SavedSearches</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SavedSearches { get { return GetKnownFolder(FolderIdentifiers.SavedSearches); } } /// <summary> /// Gets the metadata for the per-user <b>QuickLaunch</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder QuickLaunch { get { return GetKnownFolder(FolderIdentifiers.QuickLaunch); } } /// <summary> /// Gets the metadata for the <b>Contacts</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Contacts { get { return GetKnownFolder(FolderIdentifiers.Contacts); } } /// <summary> /// Gets the metadata for the <b>SidebarParts</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SidebarParts { get { return GetKnownFolder(FolderIdentifiers.SidebarParts); } } /// <summary> /// Gets the metadata for the <b>SidebarDefaultParts</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SidebarDefaultParts { get { return GetKnownFolder(FolderIdentifiers.SidebarDefaultParts); } } /// <summary> /// Gets the metadata for the <b>TreeProperties</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder TreeProperties { get { return GetKnownFolder(FolderIdentifiers.TreeProperties); } } /// <summary> /// Gets the metadata for the <b>PublicGameTasks</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder PublicGameTasks { get { return GetKnownFolder(FolderIdentifiers.PublicGameTasks); } } /// <summary> /// Gets the metadata for the <b>GameTasks</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder GameTasks { get { return GetKnownFolder(FolderIdentifiers.GameTasks); } } /// <summary> /// Gets the metadata for the per-user <b>SavedGames</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SavedGames { get { return GetKnownFolder(FolderIdentifiers.SavedGames); } } /// <summary> /// Gets the metadata for the <b>Games</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Games { get { return GetKnownFolder(FolderIdentifiers.Games); } } /// <summary> /// Gets the metadata for the <b>RecordedTV</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> /// <remarks>This folder is not used.</remarks> public static IKnownFolder RecordedTV { get { return GetKnownFolder(FolderIdentifiers.RecordedTV); } } /// <summary> /// Gets the metadata for the <b>SearchMapi</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SearchMapi { get { return GetKnownFolder(FolderIdentifiers.SearchMapi); } } /// <summary> /// Gets the metadata for the <b>SearchCsc</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SearchCsc { get { return GetKnownFolder(FolderIdentifiers.SearchCsc); } } /// <summary> /// Gets the metadata for the per-user <b>Links</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder Links { get { return GetKnownFolder(FolderIdentifiers.Links); } } /// <summary> /// Gets the metadata for the <b>UsersFiles</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder UsersFiles { get { return GetKnownFolder(FolderIdentifiers.UsersFiles); } } /// <summary> /// Gets the metadata for the <b>SearchHome</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder SearchHome { get { return GetKnownFolder(FolderIdentifiers.SearchHome); } } /// <summary> /// Gets the metadata for the <b>OriginalImages</b> folder. /// </summary> /// <value>An <see cref="IKnownFolder"/> object.</value> public static IKnownFolder OriginalImages { get { return GetKnownFolder(FolderIdentifiers.OriginalImages); } } /// <summary> /// Gets the metadata for the <b>UserProgramFiles</b> folder. /// </summary> public static IKnownFolder UserProgramFiles { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.UserProgramFiles); } } /// <summary> /// Gets the metadata for the <b>UserProgramFilesCommon</b> folder. /// </summary> public static IKnownFolder UserProgramFilesCommon { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.UserProgramFilesCommon); } } /// <summary> /// Gets the metadata for the <b>Ringtones</b> folder. /// </summary> public static IKnownFolder Ringtones { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.Ringtones); } } /// <summary> /// Gets the metadata for the <b>PublicRingtones</b> folder. /// </summary> public static IKnownFolder PublicRingtones { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.PublicRingtones); } } /// <summary> /// Gets the metadata for the <b>UsersLibraries</b> folder. /// </summary> public static IKnownFolder UsersLibraries { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.UsersLibraries); } } /// <summary> /// Gets the metadata for the <b>DocumentsLibrary</b> folder. /// </summary> public static IKnownFolder DocumentsLibrary { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.DocumentsLibrary); } } /// <summary> /// Gets the metadata for the <b>MusicLibrary</b> folder. /// </summary> public static IKnownFolder MusicLibrary { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.MusicLibrary); } } /// <summary> /// Gets the metadata for the <b>PicturesLibrary</b> folder. /// </summary> public static IKnownFolder PicturesLibrary { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.PicturesLibrary); } } /// <summary> /// Gets the metadata for the <b>VideosLibrary</b> folder. /// </summary> public static IKnownFolder VideosLibrary { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.VideosLibrary); } } /// <summary> /// Gets the metadata for the <b>RecordedTVLibrary</b> folder. /// </summary> public static IKnownFolder RecordedTVLibrary { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.RecordedTVLibrary); } } /// <summary> /// Gets the metadata for the <b>OtherUsers</b> folder. /// </summary> public static IKnownFolder OtherUsers { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.OtherUsers); } } /// <summary> /// Gets the metadata for the <b>DeviceMetadataStore</b> folder. /// </summary> public static IKnownFolder DeviceMetadataStore { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.DeviceMetadataStore); } } /// <summary> /// Gets the metadata for the <b>Libraries</b> folder. /// </summary> public static IKnownFolder Libraries { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.Libraries); } } /// <summary> ///Gets the metadata for the <b>UserPinned</b> folder. /// </summary> public static IKnownFolder UserPinned { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.UserPinned); } } /// <summary> /// Gets the metadata for the <b>ImplicitAppShortcuts</b> folder. /// </summary> public static IKnownFolder ImplicitAppShortcuts { get { CoreHelpers.ThrowIfNotWin7(); return GetKnownFolder(FolderIdentifiers.ImplicitAppShortcuts); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Configuration.Internal; using System.Diagnostics; using System.IO; using System.Net; using System.Runtime.InteropServices; namespace System.Configuration { internal sealed class ClientConfigurationHost : DelegatingConfigHost, IInternalConfigClientHost { internal const string MachineConfigName = "MACHINE"; internal const string ExeConfigName = "EXE"; internal const string RoamingUserConfigName = "ROAMING_USER"; internal const string LocalUserConfigName = "LOCAL_USER"; internal const string MachineConfigPath = MachineConfigName; internal const string ExeConfigPath = MachineConfigPath + "/" + ExeConfigName; internal const string RoamingUserConfigPath = ExeConfigPath + "/" + RoamingUserConfigName; internal const string LocalUserConfigPath = RoamingUserConfigPath + "/" + LocalUserConfigName; private const string MachineConfigFilename = "machine.config"; private const string MachineConfigSubdirectory = "Config"; private static readonly object s_version = new object(); private static volatile string s_machineConfigFilePath; private ClientConfigPaths _configPaths; // physical paths to client config files private string _exePath; // the physical path to the exe being configured private ExeConfigurationFileMap _fileMap; // optional file map private bool _initComplete; internal ClientConfigurationHost() { Host = new InternalConfigHost(); } internal ClientConfigPaths ConfigPaths => _configPaths ?? (_configPaths = ClientConfigPaths.GetPaths(_exePath, _initComplete)); internal static string MachineConfigFilePath { get { if (s_machineConfigFilePath == null) { string directory = RuntimeEnvironment.GetRuntimeDirectory(); s_machineConfigFilePath = Path.Combine(Path.Combine(directory, MachineConfigSubdirectory), MachineConfigFilename); } return s_machineConfigFilePath; } } public override bool HasRoamingConfig { get { if (_fileMap != null) return !string.IsNullOrEmpty(_fileMap.RoamingUserConfigFilename); else return ConfigPaths.HasRoamingConfig; } } public override bool HasLocalConfig { get { if (_fileMap != null) return !string.IsNullOrEmpty(_fileMap.LocalUserConfigFilename); else return ConfigPaths.HasLocalConfig; } } public override bool IsAppConfigHttp => !IsFile(GetStreamName(ExeConfigPath)); public override bool SupportsRefresh => true; public override bool SupportsPath => false; // Do we support location tags? public override bool SupportsLocation => false; bool IInternalConfigClientHost.IsExeConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, ExeConfigPath); } bool IInternalConfigClientHost.IsRoamingUserConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, RoamingUserConfigPath); } bool IInternalConfigClientHost.IsLocalUserConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, LocalUserConfigPath); } string IInternalConfigClientHost.GetExeConfigPath() { return ExeConfigPath; } string IInternalConfigClientHost.GetRoamingUserConfigPath() { return RoamingUserConfigPath; } string IInternalConfigClientHost.GetLocalUserConfigPath() { return LocalUserConfigPath; } public override void RefreshConfigPaths() { // Refresh current config paths. if ((_configPaths != null) && !_configPaths.HasEntryAssembly && (_exePath == null)) { ClientConfigPaths.RefreshCurrent(); _configPaths = null; } } // Return true if the config path is for a user.config file, false otherwise. private bool IsUserConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, RoamingUserConfigPath) || StringUtil.EqualsIgnoreCase(configPath, LocalUserConfigPath); } public override void Init(IInternalConfigRoot configRoot, params object[] hostInitParams) { try { ConfigurationFileMap fileMap = (ConfigurationFileMap)hostInitParams[0]; _exePath = (string)hostInitParams[1]; Host.Init(configRoot, hostInitParams); // Do not complete initialization in runtime config, to avoid expense of // loading user.config files that may not be required. _initComplete = configRoot.IsDesignTime; if ((fileMap != null) && !string.IsNullOrEmpty(_exePath)) throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init"); if (string.IsNullOrEmpty(_exePath)) _exePath = null; // Initialize the fileMap, if provided. if (fileMap != null) { _fileMap = new ExeConfigurationFileMap(); if (!string.IsNullOrEmpty(fileMap.MachineConfigFilename)) _fileMap.MachineConfigFilename = Path.GetFullPath(fileMap.MachineConfigFilename); ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap; if (exeFileMap != null) { if (!string.IsNullOrEmpty(exeFileMap.ExeConfigFilename)) _fileMap.ExeConfigFilename = Path.GetFullPath(exeFileMap.ExeConfigFilename); if (!string.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename)) _fileMap.RoamingUserConfigFilename = Path.GetFullPath(exeFileMap.RoamingUserConfigFilename); if (!string.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename)) _fileMap.LocalUserConfigFilename = Path.GetFullPath(exeFileMap.LocalUserConfigFilename); } } } catch { throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Init"); } } public override void InitForConfiguration(ref string locationSubPath, out string configPath, out string locationConfigPath, IInternalConfigRoot configRoot, params object[] hostInitConfigurationParams) { locationSubPath = null; configPath = (string)hostInitConfigurationParams[2]; locationConfigPath = null; Init(configRoot, hostInitConfigurationParams); } // Delay init if we have not been asked to complete init, and it is a user.config file. public override bool IsInitDelayed(IInternalConfigRecord configRecord) { return !_initComplete && IsUserConfig(configRecord.ConfigPath); } public override void RequireCompleteInit(IInternalConfigRecord record) { // Loading information about user.config files is expensive, // so do it just once by locking. lock (this) { if (!_initComplete) { // Note that all future requests for config must be complete. _initComplete = true; // Throw out the ConfigPath for this exe. ClientConfigPaths.RefreshCurrent(); // Throw out our cached copy. _configPaths = null; // Force loading of user.config file information under lock. ClientConfigPaths configPaths = ConfigPaths; } } } public override bool IsConfigRecordRequired(string configPath) { string configName = ConfigPathUtility.GetName(configPath); switch (configName) { case MachineConfigName: case ExeConfigName: return true; case RoamingUserConfigName: // Makes the design easier even if we only have an empty Roaming config record. return HasRoamingConfig || HasLocalConfig; case LocalUserConfigName: return HasLocalConfig; default: // should never get here Debug.Fail("unexpected config name: " + configName); return false; } } public override string GetStreamName(string configPath) { string configName = ConfigPathUtility.GetName(configPath); switch (configName) { case MachineConfigName: return _fileMap?.MachineConfigFilename ?? MachineConfigFilePath; case ExeConfigName: return _fileMap?.ExeConfigFilename ?? ConfigPaths.ApplicationConfigUri; case RoamingUserConfigName: return _fileMap?.RoamingUserConfigFilename ?? ConfigPaths.RoamingConfigFilename; case LocalUserConfigName: return _fileMap?.LocalUserConfigFilename ?? ConfigPaths.LocalConfigFilename; default: // should never get here Debug.Fail("unexpected config name: " + configName); goto case MachineConfigName; } } public override string GetStreamNameForConfigSource(string streamName, string configSource) { if (IsFile(streamName)) return Host.GetStreamNameForConfigSource(streamName, configSource); int index = streamName.LastIndexOf('/'); if (index < 0) return null; string parentUri = streamName.Substring(0, index + 1); string result = parentUri + configSource.Replace('\\', '/'); return result; } public override object GetStreamVersion(string streamName) { return IsFile(streamName) ? Host.GetStreamVersion(streamName) : s_version; } // default impl treats name as a file name // null means stream doesn't exist for this name public override Stream OpenStreamForRead(string streamName) { // the streamName can either be a file name, or a URI if (IsFile(streamName)) return Host.OpenStreamForRead(streamName); if (streamName == null) return null; // scheme is http WebClient client = new WebClient(); // Try using default credentials try { client.Credentials = CredentialCache.DefaultCredentials; } catch { } byte[] fileData = null; try { fileData = client.DownloadData(streamName); } catch { } if (fileData == null) return null; MemoryStream stream = new MemoryStream(fileData); return stream; } public override Stream OpenStreamForWrite(string streamName, string templateStreamName, ref object writeContext) { // only support files, not URIs if (!IsFile(streamName)) throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::OpenStreamForWrite"); return Host.OpenStreamForWrite(streamName, templateStreamName, ref writeContext); } public override void DeleteStream(string streamName) { // only support files, not URIs if (!IsFile(streamName)) throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::Delete"); Host.DeleteStream(streamName); } public override bool IsDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition) { string allowedConfigPath; switch (allowExeDefinition) { case ConfigurationAllowExeDefinition.MachineOnly: allowedConfigPath = MachineConfigPath; break; case ConfigurationAllowExeDefinition.MachineToApplication: allowedConfigPath = ExeConfigPath; break; case ConfigurationAllowExeDefinition.MachineToRoamingUser: allowedConfigPath = RoamingUserConfigPath; break; // MachineToLocalUser does not current have any definition restrictions case ConfigurationAllowExeDefinition.MachineToLocalUser: return true; default: // If we have extended ConfigurationAllowExeDefinition // make sure to update this switch accordingly throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::IsDefinitionAllowed"); } return configPath.Length <= allowedConfigPath.Length; } public override void VerifyDefinitionAllowed(string configPath, ConfigurationAllowDefinition allowDefinition, ConfigurationAllowExeDefinition allowExeDefinition, IConfigErrorInfo errorInfo) { if (!IsDefinitionAllowed(configPath, allowDefinition, allowExeDefinition)) { switch (allowExeDefinition) { case ConfigurationAllowExeDefinition.MachineOnly: throw new ConfigurationErrorsException( SR.Config_allow_exedefinition_error_machine, errorInfo); case ConfigurationAllowExeDefinition.MachineToApplication: throw new ConfigurationErrorsException( SR.Config_allow_exedefinition_error_application, errorInfo); case ConfigurationAllowExeDefinition.MachineToRoamingUser: throw new ConfigurationErrorsException( SR.Config_allow_exedefinition_error_roaminguser, errorInfo); default: // If we have extended ConfigurationAllowExeDefinition // make sure to update this switch accordingly throw ExceptionUtil.UnexpectedError("ClientConfigurationHost::VerifyDefinitionAllowed"); } } } // prefetch support public override bool PrefetchAll(string configPath, string streamName) { // If it's a file, we don't need to. Otherwise (e.g. it's from the web), we'll prefetch everything. return !IsFile(streamName); } public override bool PrefetchSection(string sectionGroupName, string sectionName) { return sectionGroupName == "system.net"; } public override object CreateDeprecatedConfigContext(string configPath) { return null; } public override object CreateConfigurationContext(string configPath, string locationSubPath) { return new ExeContext(GetUserLevel(configPath), ConfigPaths.ApplicationUri); } private ConfigurationUserLevel GetUserLevel(string configPath) { ConfigurationUserLevel level; switch (ConfigPathUtility.GetName(configPath)) { case MachineConfigName: level = ConfigurationUserLevel.None; break; case ExeConfigName: level = ConfigurationUserLevel.None; break; case LocalUserConfigName: level = ConfigurationUserLevel.PerUserRoamingAndLocal; break; case RoamingUserConfigName: level = ConfigurationUserLevel.PerUserRoaming; break; default: Debug.Fail("unrecognized configPath " + configPath); level = ConfigurationUserLevel.None; break; } return level; } internal static Configuration OpenExeConfiguration(ConfigurationFileMap fileMap, bool isMachine, ConfigurationUserLevel userLevel, string exePath) { // validate userLevel argument switch (userLevel) { case ConfigurationUserLevel.None: case ConfigurationUserLevel.PerUserRoaming: case ConfigurationUserLevel.PerUserRoamingAndLocal: break; default: throw ExceptionUtil.ParameterInvalid(nameof(userLevel)); } // validate fileMap arguments if (fileMap != null) { if (string.IsNullOrEmpty(fileMap.MachineConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(fileMap.MachineConfigFilename)); ExeConfigurationFileMap exeFileMap = fileMap as ExeConfigurationFileMap; if (exeFileMap != null) { switch (userLevel) { case ConfigurationUserLevel.None: if (string.IsNullOrEmpty(exeFileMap.ExeConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.ExeConfigFilename)); break; case ConfigurationUserLevel.PerUserRoaming: if (string.IsNullOrEmpty(exeFileMap.RoamingUserConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.RoamingUserConfigFilename)); goto case ConfigurationUserLevel.None; case ConfigurationUserLevel.PerUserRoamingAndLocal: if (string.IsNullOrEmpty(exeFileMap.LocalUserConfigFilename)) throw ExceptionUtil.ParameterNullOrEmpty(nameof(fileMap) + "." + nameof(exeFileMap.LocalUserConfigFilename)); goto case ConfigurationUserLevel.PerUserRoaming; } } } string configPath = null; if (isMachine) configPath = MachineConfigPath; else { switch (userLevel) { case ConfigurationUserLevel.None: configPath = ExeConfigPath; break; case ConfigurationUserLevel.PerUserRoaming: configPath = RoamingUserConfigPath; break; case ConfigurationUserLevel.PerUserRoamingAndLocal: configPath = LocalUserConfigPath; break; } } Configuration configuration = new Configuration(null, typeof(ClientConfigurationHost), fileMap, exePath, configPath); return configuration; } } }
using System; using System.Collections.Generic; using System.Composition; using System.IO; using System.Linq; using System.Net.WebSockets; using System.Reflection; using System.Security.Claims; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.FeatureModel; using Microsoft.AspNet.Http; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Core; using Microsoft.CodeAnalysis; using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.Logging; using Microsoft.Framework.Runtime; using Newtonsoft.Json; using OmniSharp.Mef; using OmniSharp.Middleware; using OmniSharp.Models; using OmniSharp.Models.v1; using OmniSharp.Services; using Xunit; namespace OmniSharp.Tests { public class EndpointMiddlewareFacts { [OmniSharpHandler(OmnisharpEndpoints.GotoDefinition, LanguageNames.CSharp)] public class GotoDefinitionService : RequestHandler<GotoDefinitionRequest, GotoDefinitionResponse> { [Import] public OmnisharpWorkspace Workspace { get; set; } public Task<GotoDefinitionResponse> Handle(GotoDefinitionRequest request) { return Task.FromResult<GotoDefinitionResponse>(null); } } [OmniSharpHandler(OmnisharpEndpoints.FindSymbols, LanguageNames.CSharp)] public class FindSymbolsService : RequestHandler<FindSymbolsRequest, QuickFixResponse> { [Import] public OmnisharpWorkspace Workspace { get; set; } public Task<QuickFixResponse> Handle(FindSymbolsRequest request) { return Task.FromResult<QuickFixResponse>(null); } } [OmniSharpHandler(OmnisharpEndpoints.UpdateBuffer, LanguageNames.CSharp)] public class UpdateBufferService : RequestHandler<UpdateBufferRequest, object> { [Import] public OmnisharpWorkspace Workspace { get; set; } public Task<object> Handle(UpdateBufferRequest request) { return Task.FromResult<object>(null); } } class Response { } [Export(typeof(IProjectSystem))] class FakeProjectSystem : IProjectSystem { public string Key { get { return "Fake"; } } public string Language { get { return LanguageNames.CSharp; } } public IEnumerable<string> Extensions { get; } = new[] { ".cs" }; public Task<object> GetInformationModel(WorkspaceInformationRequest request) { throw new NotImplementedException(); } public Task<object> GetProjectModel(string path) { throw new NotImplementedException(); } public void Initalize(IConfiguration configuration) { } } class LoggerFactory : ILoggerFactory { public LogLevel MinimumLevel { get; set; } public void AddProvider(ILoggerProvider provider) { } public ILogger CreateLogger(string categoryName) { return new Logger(); } } class Disposable : IDisposable { public void Dispose() { } } class Logger : ILogger { public IDisposable BeginScope(object state) { return new Disposable(); } public bool IsEnabled(LogLevel logLevel) { return true; } public void Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter) { } } [Fact] public async Task Passes_through_for_invalid_path() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/notvalid"); await Assert.ThrowsAsync<NotImplementedException>(() => middleware.Invoke(context)); } [Fact] public async Task Does_not_throw_for_valid_path() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/gotodefinition"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new GotoDefinitionRequest { FileName = "bar.cs", Line = 2, Column = 14, Timeout = 60000 }) ) ); await middleware.Invoke(context); Assert.True(true); } [Fact] public async Task Passes_through_to_services() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/gotodefinition"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new GotoDefinitionRequest { FileName = "bar.cs", Line = 2, Column = 14, Timeout = 60000 }) ) ); await middleware.Invoke(context); Assert.True(true); } [Fact] public async Task Passes_through_to_all_services_with_delegate() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/findsymbols"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new FindSymbolsRequest { }) ) ); await middleware.Invoke(context); Assert.True(true); } [Fact] public async Task Passes_through_to_specific_service_with_delegate() { RequestDelegate _next = (ctx) => Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly, typeof(EndpointDescriptor).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/findsymbols"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new FindSymbolsRequest { Language = LanguageNames.CSharp }) ) ); await middleware.Invoke(context); Assert.True(true); } public Func<ThrowRequest, Task<ThrowResponse>> ThrowDelegate = (request) => { return Task.FromResult<ThrowResponse>(null); }; [OmniSharpEndpoint("/throw", typeof(ThrowRequest), typeof(ThrowResponse))] public class ThrowRequest : IRequest { } public class ThrowResponse { } [Fact] public async Task Should_throw_if_type_is_not_mergeable() { RequestDelegate _next = async (ctx) => await Task.Run(() => { throw new NotImplementedException(); }); var host = TestHelpers.CreatePluginHost(new[] { typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly }); var middleware = new EndpointMiddleware(_next, host, new LoggerFactory()); var context = new DefaultHttpContext(); context.Request.Path = PathString.FromUriComponent("/throw"); var memoryStream = new MemoryStream(); context.Request.Body = new MemoryStream( Encoding.UTF8.GetBytes( JsonConvert.SerializeObject(new ThrowRequest()) ) ); await Assert.ThrowsAsync<NotSupportedException>(async () => await middleware.Invoke(context)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Search { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// AdminKeysOperations operations. /// </summary> internal partial class AdminKeysOperations : Microsoft.Rest.IServiceOperations<SearchManagementClient>, IAdminKeysOperations { /// <summary> /// Initializes a new instance of the AdminKeysOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal AdminKeysOperations(SearchManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the SearchManagementClient /// </summary> public SearchManagementClient Client { get; private set; } /// <summary> /// Gets the primary and secondary admin API keys for the specified Azure /// Search service. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service associated with the specified /// resource group. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AdminKeyResult>> GetWithHttpMessagesAsync(string resourceGroupName, string searchServiceName, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (searchServiceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "searchServiceName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } System.Guid? clientRequestId = default(System.Guid?); if (searchManagementRequestOptions != null) { clientRequestId = searchManagementRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("searchServiceName", searchServiceName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/listAdminKeys").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{searchServiceName}", System.Uri.EscapeDataString(searchServiceName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("x-ms-client-request-id")) { _httpRequest.Headers.Remove("x-ms-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<AdminKeyResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<AdminKeyResult>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Regenerates either the primary or secondary admin API key. You can only /// regenerate one key at a time. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service associated with the specified /// resource group. /// </param> /// <param name='keyKind'> /// Specifies which key to regenerate. Valid values include 'primary' and /// 'secondary'. Possible values include: 'primary', 'secondary' /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<AdminKeyResult>> RegenerateWithHttpMessagesAsync(string resourceGroupName, string searchServiceName, AdminKeyKind keyKind, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (searchServiceName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "searchServiceName"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } System.Guid? clientRequestId = default(System.Guid?); if (searchManagementRequestOptions != null) { clientRequestId = searchManagementRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("searchServiceName", searchServiceName); tracingParameters.Add("keyKind", keyKind); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Regenerate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/regenerateAdminKey/{keyKind}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{searchServiceName}", System.Uri.EscapeDataString(searchServiceName)); _url = _url.Replace("{keyKind}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(keyKind, this.Client.SerializationSettings).Trim('"'))); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("x-ms-client-request-id")) { _httpRequest.Headers.Remove("x-ms-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<AdminKeyResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<AdminKeyResult>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; // ReSharper disable once CheckNamespace namespace System { [DebuggerStepThrough] internal static class SharedTypeExtensions { public static Type UnwrapNullableType(this Type type) => Nullable.GetUnderlyingType(type) ?? type; public static bool IsNullableType(this Type type) { var typeInfo = type.GetTypeInfo(); return !typeInfo.IsValueType || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type MakeNullable(this Type type) => type.IsNullableType() ? type : typeof(Nullable<>).MakeGenericType(type); public static bool IsInteger(this Type type) { type = type.UnwrapNullableType(); return type == typeof(int) || type == typeof(long) || type == typeof(short) || type == typeof(byte) || type == typeof(uint) || type == typeof(ulong) || type == typeof(ushort) || type == typeof(sbyte); } public static bool IsIntegerForSerial(this Type type) { type = type.UnwrapNullableType(); return type == typeof(int) || type == typeof(long) || type == typeof(short); } public static PropertyInfo GetAnyProperty(this Type type, string name) { var props = type.GetRuntimeProperties().Where(p => p.Name == name).ToList(); if (props.Count() > 1) { throw new AmbiguousMatchException(); } return props.SingleOrDefault(); } private static bool IsNonIntegerPrimitive(this Type type) { type = type.UnwrapNullableType(); return type == typeof(bool) || type == typeof(byte[]) || type == typeof(char) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(decimal) || type == typeof(double) || type == typeof(float) || type == typeof(Guid) || type == typeof(string) || type == typeof(TimeSpan) || type.GetTypeInfo().IsEnum; } public static bool IsPrimitive(this Type type) => type.IsInteger() || type.IsNonIntegerPrimitive(); public static Type UnwrapEnumType(this Type type) => type.GetTypeInfo().IsEnum ? Enum.GetUnderlyingType(type) : type; public static Type GetSequenceType(this Type type) { var sequenceType = TryGetSequenceType(type); if (sequenceType == null) { throw new ArgumentException(); } return sequenceType; } public static Type TryGetSequenceType(this Type type) => type.TryGetElementType(typeof(IEnumerable<>)) ?? type.TryGetElementType(typeof(IAsyncEnumerable<>)); public static Type TryGetElementType(this Type type, Type interfaceOrBaseType) { if (type.GetTypeInfo().IsGenericTypeDefinition) { return null; } var types = GetGenericTypeImplementations(type, interfaceOrBaseType); Type singleImplementation = null; foreach (var impelementation in types) { if (singleImplementation == null) { singleImplementation = impelementation; } else { singleImplementation = null; break; } } return singleImplementation?.GetTypeInfo().GenericTypeArguments.FirstOrDefault(); } public static IEnumerable<Type> GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType) { var typeInfo = type.GetTypeInfo(); if (!typeInfo.IsGenericTypeDefinition) { var baseTypes = interfaceOrBaseType.GetTypeInfo().IsInterface ? typeInfo.ImplementedInterfaces : type.GetBaseTypes(); foreach (var baseType in baseTypes) { if (baseType.GetTypeInfo().IsGenericType && baseType.GetGenericTypeDefinition() == interfaceOrBaseType) { yield return baseType; } } if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == interfaceOrBaseType) { yield return type; } } } public static IEnumerable<Type> GetBaseTypes(this Type type) { type = type.GetTypeInfo().BaseType; while (type != null) { yield return type; type = type.GetTypeInfo().BaseType; } } public static ConstructorInfo GetDeclaredConstructor(this Type type, Type[] types) { types = types ?? Array.Empty<Type>(); return type.GetTypeInfo().DeclaredConstructors .SingleOrDefault( c => !c.IsStatic && c.GetParameters().Select(p => p.ParameterType).SequenceEqual(types)); } private static readonly Dictionary<Type, object> _commonTypeDictionary = new Dictionary<Type, object> { #pragma warning disable IDE0034 // Simplify 'default' expression - default causes default(object) { typeof(int), default(int) }, { typeof(Guid), default(Guid) }, { typeof(DateTime), default(DateTime) }, { typeof(DateTimeOffset), default(DateTimeOffset) }, { typeof(long), default(long) }, { typeof(bool), default(bool) }, { typeof(double), default(double) }, { typeof(short), default(short) }, { typeof(float), default(float) }, { typeof(byte), default(byte) }, { typeof(char), default(char) }, { typeof(uint), default(uint) }, { typeof(ushort), default(ushort) }, { typeof(ulong), default(ulong) }, { typeof(sbyte), default(sbyte) } #pragma warning restore IDE0034 // Simplify 'default' expression }; public static object GetDefaultValue(this Type type) { if (!type.GetTypeInfo().IsValueType) { return null; } // A bit of perf code to avoid calling Activator.CreateInstance for common types and // to avoid boxing on every call. This is about 50% faster than just calling CreateInstance // for all value types. return _commonTypeDictionary.TryGetValue(type, out var value) ? value : Activator.CreateInstance(type); } } }
// 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.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents accessing a field or property. /// </summary> [DebuggerTypeProxy(typeof(Expression.MemberExpressionProxy))] public class MemberExpression : Expression { private readonly Expression _expression; /// <summary> /// Gets the field or property to be accessed. /// </summary> public MemberInfo Member { get { return GetMember(); } } /// <summary> /// Gets the containing object of the field or property. /// </summary> public Expression Expression { get { return _expression; } } // param order: factories args in order, then other args internal MemberExpression(Expression expression) { _expression = expression; } internal static PropertyExpression Make(Expression expression, PropertyInfo property) { Debug.Assert(property != null); return new PropertyExpression(expression, property); } internal static FieldExpression Make(Expression expression, FieldInfo field) { Debug.Assert(field != null); return new FieldExpression(expression, field); } internal static MemberExpression Make(Expression expression, MemberInfo member) { FieldInfo fi = member as FieldInfo; return fi == null ? (MemberExpression)Make(expression, (PropertyInfo)member) : Make(expression, fi); } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.MemberAccess; } } [ExcludeFromCodeCoverage] // Unreachable internal virtual MemberInfo GetMember() { throw ContractUtils.Unreachable; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitMember(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expression">The <see cref="Expression" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public MemberExpression Update(Expression expression) { if (expression == Expression) { return this; } return Expression.MakeMemberAccess(expression, Member); } } internal class FieldExpression : MemberExpression { private readonly FieldInfo _field; public FieldExpression(Expression expression, FieldInfo member) : base(expression) { _field = member; } internal override MemberInfo GetMember() { return _field; } public sealed override Type Type { get { return _field.FieldType; } } } internal class PropertyExpression : MemberExpression { private readonly PropertyInfo _property; public PropertyExpression(Expression expression, PropertyInfo member) : base(expression) { _property = member; } internal override MemberInfo GetMember() { return _property; } public sealed override Type Type { get { return _property.PropertyType; } } } public partial class Expression { #region Field /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a field. /// </summary> /// <param name="expression">The containing object of the field. This can be null for static fields.</param> /// <param name="field">The field to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] public static MemberExpression Field(Expression expression, FieldInfo field) { ContractUtils.RequiresNotNull(field, nameof(field)); if (field.IsStatic) { if (expression != null) throw new ArgumentException(Strings.OnlyStaticFieldsHaveNullInstance, nameof(expression)); } else { if (expression == null) throw new ArgumentException(Strings.OnlyStaticFieldsHaveNullInstance, nameof(field)); RequiresCanRead(expression, nameof(expression)); if (!TypeUtils.AreReferenceAssignable(field.DeclaringType, expression.Type)) { throw Error.FieldInfoNotDefinedForType(field.DeclaringType, field.Name, expression.Type); } } return MemberExpression.Make(expression, field); } /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a field. /// </summary> /// <param name="expression">The containing object of the field. This can be null for static fields.</param> /// <param name="fieldName">The field to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> public static MemberExpression Field(Expression expression, string fieldName) { RequiresCanRead(expression, nameof(expression)); // bind to public names first FieldInfo fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (fi == null) { fi = expression.Type.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); } if (fi == null) { throw Error.InstanceFieldNotDefinedForType(fieldName, expression.Type); } return Expression.Field(expression, fi); } /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a field. /// </summary> /// <param name="expression">The containing object of the field. This can be null for static fields.</param> /// <param name="type">The <see cref="Type"/> containing the field.</param> /// <param name="fieldName">The field to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] public static MemberExpression Field(Expression expression, Type type, string fieldName) { ContractUtils.RequiresNotNull(type, nameof(type)); // bind to public names first FieldInfo fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (fi == null) { fi = type.GetField(fieldName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); } if (fi == null) { throw Error.FieldNotDefinedForType(fieldName, type); } return Expression.Field(expression, fi); } #endregion #region Property /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a property. /// </summary> /// <param name="expression">The containing object of the property. This can be null for static properties.</param> /// <param name="propertyName">The property to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> public static MemberExpression Property(Expression expression, string propertyName) { RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(propertyName, nameof(propertyName)); // bind to public names first PropertyInfo pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (pi == null) { pi = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); } if (pi == null) { throw Error.InstancePropertyNotDefinedForType(propertyName, expression.Type); } return Property(expression, pi); } /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a property. /// </summary> /// <param name="expression">The containing object of the property. This can be null for static properties.</param> /// <param name="type">The <see cref="Type"/> containing the property.</param> /// <param name="propertyName">The property to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> public static MemberExpression Property(Expression expression, Type type, string propertyName) { ContractUtils.RequiresNotNull(type, nameof(type)); ContractUtils.RequiresNotNull(propertyName, nameof(propertyName)); // bind to public names first PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (pi == null) { pi = type.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); } if (pi == null) { throw Error.PropertyNotDefinedForType(propertyName, type); } return Property(expression, pi); } /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a property. /// </summary> /// <param name="expression">The containing object of the property. This can be null for static properties.</param> /// <param name="property">The property to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames")] public static MemberExpression Property(Expression expression, PropertyInfo property) { ContractUtils.RequiresNotNull(property, nameof(property)); MethodInfo mi = property.GetGetMethod(true); if (mi == null) { mi = property.GetSetMethod(true); if (mi == null) { throw Error.PropertyDoesNotHaveAccessor(property, nameof(property)); } else if (mi.GetParametersCached().Length != 1) { throw Error.IncorrectNumberOfMethodCallArguments(mi); } } else if (mi.GetParametersCached().Length != 0) { throw Error.IncorrectNumberOfMethodCallArguments(mi); } if (mi.IsStatic) { if (expression != null) throw new ArgumentException(Strings.OnlyStaticPropertiesHaveNullInstance, nameof(expression)); } else { if (expression == null) throw new ArgumentException(Strings.OnlyStaticPropertiesHaveNullInstance, nameof(property)); RequiresCanRead(expression, nameof(expression)); if (!TypeUtils.IsValidInstanceType(property, expression.Type)) { throw Error.PropertyNotDefinedForType(property, expression.Type); } } return MemberExpression.Make(expression, property); } /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a property. /// </summary> /// <param name="expression">The containing object of the property. This can be null for static properties.</param> /// <param name="propertyAccessor">An accessor method of the property to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> public static MemberExpression Property(Expression expression, MethodInfo propertyAccessor) { ContractUtils.RequiresNotNull(propertyAccessor, nameof(propertyAccessor)); ValidateMethodInfo(propertyAccessor, nameof(propertyAccessor)); return Property(expression, GetProperty(propertyAccessor, nameof(propertyAccessor))); } private static PropertyInfo GetProperty(MethodInfo mi, string paramName) { Type type = mi.DeclaringType; BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic; flags |= (mi.IsStatic) ? BindingFlags.Static : BindingFlags.Instance; var props = type.GetProperties(flags); foreach (PropertyInfo pi in props) { if (pi.CanRead && CheckMethod(mi, pi.GetGetMethod(true))) { return pi; } if (pi.CanWrite && CheckMethod(mi, pi.GetSetMethod(true))) { return pi; } } throw Error.MethodNotPropertyAccessor(mi.DeclaringType, mi.Name, paramName); } private static bool CheckMethod(MethodInfo method, MethodInfo propertyMethod) { if (method.Equals(propertyMethod)) { return true; } // If the type is an interface then the handle for the method got by the compiler will not be the // same as that returned by reflection. // Check for this condition and try and get the method from reflection. Type type = method.DeclaringType; if (type.GetTypeInfo().IsInterface && method.Name == propertyMethod.Name && type.GetMethod(method.Name) == propertyMethod) { return true; } return false; } #endregion /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a property or field. /// </summary> /// <param name="expression">The containing object of the member. This can be null for static members.</param> /// <param name="propertyOrFieldName">The member to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName) { RequiresCanRead(expression, nameof(expression)); // bind to public names first PropertyInfo pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (pi != null) return Property(expression, pi); FieldInfo fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (fi != null) return Field(expression, fi); pi = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (pi != null) return Property(expression, pi); fi = expression.Type.GetField(propertyOrFieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy); if (fi != null) return Field(expression, fi); throw Error.NotAMemberOfType(propertyOrFieldName, expression.Type); } /// <summary> /// Creates a <see cref="MemberExpression"/> accessing a property or field. /// </summary> /// <param name="expression">The containing object of the member. This can be null for static members.</param> /// <param name="member">The member to be accessed.</param> /// <returns>The created <see cref="MemberExpression"/>.</returns> public static MemberExpression MakeMemberAccess(Expression expression, MemberInfo member) { ContractUtils.RequiresNotNull(member, nameof(member)); FieldInfo fi = member as FieldInfo; if (fi != null) { return Expression.Field(expression, fi); } PropertyInfo pi = member as PropertyInfo; if (pi != null) { return Expression.Property(expression, pi); } throw Error.MemberNotFieldOrProperty(member, nameof(member)); } } }
//----------------------------------------------------------------------------- // // <copyright file="StorageRoot.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // The root object for manipulating the WPP container. // // History: // 05/10/2002: RogerCh: Initial creation. // 06/12/2002: RogerCh: Catch & translate COMException from native calls. // 06/25/2002: RogerCh: Add a constructor to build on top of IStorage. // 06/28/2002: RogerCh: Add a boolean to avoid infinite loops in data space // manager initialization. // 07/31/2002: RogerCh: Make obvious that we are using security suppressed interfaces. // 05/20/2003: RogerCh: Ported to WCP tree. // //----------------------------------------------------------------------------- using System; using System.IO; using System.Runtime.InteropServices; using System.Windows; // For exception string lookup table using MS.Internal; // for Invariant using MS.Internal.IO.Packaging.CompoundFile; using MS.Internal.WindowsBase; namespace System.IO.Packaging { /// <summary> /// The main container class, one instance per compound file /// </summary> internal class StorageRoot : StorageInfo { /***********************************************************************/ // Default values to use for the StorageRoot.Open shortcuts const FileMode defaultFileMode = FileMode.OpenOrCreate; const FileAccess defaultFileAccess = FileAccess.ReadWrite; const FileShare defaultFileShare = FileShare.None; const int defaultSectorSize = 512; const int stgFormatDocFile = 5; // STGFMT_DOCFILE /***********************************************************************/ // Instance values /// <summary> /// The reference to the IStorage root of this container. This value /// is initialized at Open and zeroed out at Close. If this value is /// zero, it means the object has been disposed. /// </summary> IStorage rootIStorage; /// <summary> /// Cached instance to our data space manager /// </summary> DataSpaceManager dataSpaceManager; /// <summary> /// If we know we are in a read-only mode, we know not to do certain things. /// </summary> bool containerIsReadOnly; /// <summary> /// When data space manager is being initialized, sometimes it trips /// actions that would (in other circumstances) require checking the /// data space manager. To avoid an infinite loop, we break it by knowing /// when data space manager is being initialized. /// </summary> bool dataSpaceManagerInitializationInProgress; /***********************************************************************/ private StorageRoot(IStorage root, bool readOnly ) : base( root ) { rootIStorage = root; containerIsReadOnly = readOnly; dataSpaceManagerInitializationInProgress = false; } /// <summary> /// The access mode available on this container /// </summary> internal FileAccess OpenAccess { get { CheckRootDisposedStatus(); if(containerIsReadOnly) { return FileAccess.Read; } else { return FileAccess.ReadWrite; } } } /// <summary> /// Create a container StorageRoot based on the given System.IO.Stream object /// </summary> /// <param name="baseStream">The new Stream upon which to build the new StorageRoot</param> /// <returns>New StorageRoot object built on the given Stream</returns> internal static StorageRoot CreateOnStream( Stream baseStream ) { if (baseStream == null) { throw new ArgumentNullException("baseStream"); } if( 0 == baseStream.Length ) { return CreateOnStream( baseStream, FileMode.Create ); } else { return CreateOnStream( baseStream, FileMode.Open ); } } /// <summary> /// Create a container StorageRoot based on the given System.IO.Stream object /// </summary> /// <param name="baseStream">The new Stream upon which to build the new StorageRoot</param> /// <param name="mode">The mode (Open or Create) to use on the lock bytes</param> /// <returns>New StorageRoot object built on the given Stream</returns> internal static StorageRoot CreateOnStream(Stream baseStream, FileMode mode) { if( null == baseStream ) throw new ArgumentNullException("baseStream"); IStorage storageOnStream; int returnValue; int openFlags = SafeNativeCompoundFileConstants.STGM_SHARE_EXCLUSIVE; if( baseStream.CanRead ) { if( baseStream.CanWrite ) { openFlags |= SafeNativeCompoundFileConstants.STGM_READWRITE; } else { openFlags |= SafeNativeCompoundFileConstants.STGM_READ; if( FileMode.Create == mode ) throw new ArgumentException( SR.Get(SRID.CanNotCreateContainerOnReadOnlyStream)); } } else { throw new ArgumentException( SR.Get(SRID.CanNotCreateStorageRootOnNonReadableStream)); } if( FileMode.Create == mode ) { returnValue = SafeNativeCompoundFileMethods.SafeStgCreateDocfileOnStream( baseStream, openFlags | SafeNativeCompoundFileConstants.STGM_CREATE, out storageOnStream); } else if( FileMode.Open == mode ) { returnValue = SafeNativeCompoundFileMethods.SafeStgOpenStorageOnStream( baseStream, openFlags, out storageOnStream ); } else { throw new ArgumentException( SR.Get(SRID.CreateModeMustBeCreateOrOpen)); } switch( (uint) returnValue ) { case SafeNativeCompoundFileConstants.S_OK: return StorageRoot.CreateOnIStorage( storageOnStream ); default: throw new IOException( SR.Get(SRID.UnableToCreateOnStream), new COMException( SR.Get(SRID.CFAPIFailure), returnValue)); } } /// <summary>Open a container, given only the path.</summary> /// <param name="path">Path to container file on local file system</param> /// <returns>StorageRoot instance representing the file</returns> internal static StorageRoot Open( string path ) { return Open( path, defaultFileMode, defaultFileAccess, defaultFileShare, defaultSectorSize ); } /// <summary>Open a container, given path and open mode</summary> /// <param name="path">Path to container file on local file system</param> /// <param name="mode">Access mode, see System.IO.FileMode in .NET SDK</param> /// <returns>StorageRoot instance representing the file</returns> internal static StorageRoot Open( string path, FileMode mode ) { return Open( path, mode, defaultFileAccess, defaultFileShare, defaultSectorSize ); } /// <summary>Open a container, given path, open mode, and access flag</summary> /// <param name="path">Path to container file on local file system</param> /// <param name="mode">See System.IO.FileMode in .NET SDK</param> /// <param name="access">See System.IO.FileAccess in .NET SDK</param> /// <returns>StorageRoot instance representing the file</returns> internal static StorageRoot Open( string path, FileMode mode, FileAccess access ) { return Open( path, mode, access, defaultFileShare, defaultSectorSize ); } /// <summary>Open a container, given path, open mode, access flag, and sharing settings</summary> /// <param name="path">Path to container on local file system</param> /// <param name="mode">See System.IO.FileMode in .NET SDK</param> /// <param name="access">See System.IO.FileAccess in .NET SDK</param> /// <param name="share">See System.IO.FileSharing in .NET SDK</param> /// <returns>StorageRoot instance representing the file</returns> internal static StorageRoot Open( string path, FileMode mode, FileAccess access, FileShare share ) { return Open( path, mode, access, share, defaultSectorSize ); } /// <summary>Open a container given all the settings</summary> /// <param name="path">Path to container on local file system</param> /// <param name="mode">See System.IO.FileMode in .NET SDK</param> /// <param name="access">See System.IO.FileAccess in .NET SDK</param> /// <param name="share">See System.IO.FileShare in .NET SDK</param> /// <param name="sectorSize">Compound File sector size, must be 512 or 4096</param> /// <returns>StorageRoot instance representing the file</returns> internal static StorageRoot Open( string path, FileMode mode, FileAccess access, FileShare share, int sectorSize ) { int grfMode = 0; int returnValue = 0; // Simple path validation ContainerUtilities.CheckStringAgainstNullAndEmpty( path, "Path" ); Guid IID_IStorage = new Guid(0x0000000B,0x0000,0x0000,0xC0,0x00, 0x00,0x00,0x00,0x00,0x00,0x46); IStorage newRootStorage; //////////////////////////////////////////////////////////////////// // Generate STGM from FileMode switch(mode) { case FileMode.Append: throw new ArgumentException( SR.Get(SRID.FileModeUnsupported)); case FileMode.Create: grfMode |= SafeNativeCompoundFileConstants.STGM_CREATE; break; case FileMode.CreateNew: { FileInfo existTest = new FileInfo(path); if( existTest.Exists ) { throw new IOException( SR.Get(SRID.FileAlreadyExists)); } } goto case FileMode.Create; case FileMode.Open: break; case FileMode.OpenOrCreate: { FileInfo existTest = new FileInfo(path); if( existTest.Exists ) { // File exists, use open code path goto case FileMode.Open; } else { // File does not exist, use create code path goto case FileMode.Create; } } case FileMode.Truncate: throw new ArgumentException( SR.Get(SRID.FileModeUnsupported)); default: throw new ArgumentException( SR.Get(SRID.FileModeInvalid)); } // Generate the access flags from the access parameter SafeNativeCompoundFileMethods.UpdateModeFlagFromFileAccess( access, ref grfMode ); // Generate STGM from FileShare // Note: the .NET SDK does not specify the proper behavior in reaction to // incompatible flags being sent in together. Should ArgumentException be // thrown? Or do some values "trump" others? if( 0 != (share & FileShare.Inheritable) ) { throw new ArgumentException( SR.Get(SRID.FileShareUnsupported)); } else if( share == FileShare.None ) // FileShare.None is zero, using "&" to check causes unreachable code error { grfMode |= SafeNativeCompoundFileConstants.STGM_SHARE_EXCLUSIVE; } else if( share == FileShare.Read ) { grfMode |= SafeNativeCompoundFileConstants.STGM_SHARE_DENY_WRITE; } else if( share == FileShare.Write ) { grfMode |= SafeNativeCompoundFileConstants.STGM_SHARE_DENY_READ; // Note that this makes little sense when we don't support combination of flags } else if( share == FileShare.ReadWrite ) { grfMode |= SafeNativeCompoundFileConstants.STGM_SHARE_DENY_NONE; } else { throw new ArgumentException( SR.Get(SRID.FileShareInvalid)); } if( 0 != (grfMode & SafeNativeCompoundFileConstants.STGM_CREATE)) { // STGM_CREATE set, call StgCreateStorageEx. returnValue = SafeNativeCompoundFileMethods.SafeStgCreateStorageEx( path, grfMode, stgFormatDocFile, 0, IntPtr.Zero, IntPtr.Zero, ref IID_IStorage, out newRootStorage ); } else { // STGM_CREATE not set, call StgOpenStorageEx. returnValue = SafeNativeCompoundFileMethods.SafeStgOpenStorageEx( path, grfMode, stgFormatDocFile, 0, IntPtr.Zero, IntPtr.Zero, ref IID_IStorage, out newRootStorage ); } switch( returnValue ) { case SafeNativeCompoundFileConstants.S_OK: return StorageRoot.CreateOnIStorage( newRootStorage ); case SafeNativeCompoundFileConstants.STG_E_FILENOTFOUND: throw new FileNotFoundException( SR.Get(SRID.ContainerNotFound)); case SafeNativeCompoundFileConstants.STG_E_INVALIDFLAG: throw new ArgumentException( SR.Get(SRID.StorageFlagsUnsupported), new COMException( SR.Get(SRID.CFAPIFailure), returnValue)); default: throw new IOException( SR.Get(SRID.ContainerCanNotOpen), new COMException( SR.Get(SRID.CFAPIFailure), returnValue)); } } /// <summary> /// Clean up this container storage instance /// </summary> internal void Close() { if( null == rootIStorage ) return; // Extraneous calls to Close() are ignored if( null != dataSpaceManager ) { // Tell data space manager to flush all information as necessary dataSpaceManager.Dispose(); dataSpaceManager = null; } try { // Shut down the underlying storage if( !containerIsReadOnly ) rootIStorage.Commit(0); } finally { // We need these clean up steps to run even if there's a problem // with the commit above. RecursiveStorageInfoCoreRelease( core ); rootIStorage = null; } } /// <summary> /// Flush the storage root. /// </summary> internal void Flush() { CheckRootDisposedStatus(); // Shut down the underlying storage if( !containerIsReadOnly ) rootIStorage.Commit(0); } /// <summary> /// Obtains the data space manager object for this instance of the /// container. Subsequent calls will return reference to the same /// object. /// </summary> /// <returns>Reference to the manager object</returns> internal DataSpaceManager GetDataSpaceManager() { CheckRootDisposedStatus(); if( null == dataSpaceManager ) { if ( dataSpaceManagerInitializationInProgress ) return null; // initialization in progress - abort // Create new instance of data space manager dataSpaceManagerInitializationInProgress = true; dataSpaceManager = new DataSpaceManager( this ); dataSpaceManagerInitializationInProgress = false; } return dataSpaceManager; } internal IStorage GetRootIStorage() { return rootIStorage; } // Check whether this StorageRoot class still has its underlying storage. // If not, throw an object disposed exception. This should be checked from // every non-static container external API. internal void CheckRootDisposedStatus() { if( RootDisposed ) throw new ObjectDisposedException(null, SR.Get(SRID.StorageRootDisposed)); } // Check whether this StorageRoot class still has its underlying storage. internal bool RootDisposed { get { return ( null == rootIStorage ); } } /// <summary> /// This will create a container StorageRoot based on the given IStorage /// interface /// </summary> /// <param name="root">The new IStorage (RCW) upon which to build the new StorageRoot</param> /// <returns>New StorageRoot object built on the given IStorage</returns> private static StorageRoot CreateOnIStorage( IStorage root ) { // The root is created by calling unmanaged CompoundFile APIs. The return value from the call is always // checked to see if is S_OK. If it is S_OK, the root should never be null. However, just to make sure // call Invariant.Assert Invariant.Assert(root != null); System.Runtime.InteropServices.ComTypes.STATSTG rootSTAT; bool readOnly; root.Stat( out rootSTAT, SafeNativeCompoundFileConstants.STATFLAG_NONAME ); readOnly =( SafeNativeCompoundFileConstants.STGM_WRITE != ( rootSTAT.grfMode & SafeNativeCompoundFileConstants.STGM_WRITE ) && SafeNativeCompoundFileConstants.STGM_READWRITE != (rootSTAT.grfMode & SafeNativeCompoundFileConstants.STGM_READWRITE) ); return new StorageRoot( root, readOnly ); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using QuantConnect.Data; using QuantConnect.Orders; using QuantConnect.Interfaces; using QuantConnect.Securities; using System.Collections.Generic; using QuantConnect.Securities.Option; using Futures = QuantConnect.Securities.Futures; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Tests delistings for Futures and Futures Options to ensure that they are delisted at the expected times. /// </summary> public class FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private bool _invested; private int _liquidated; private int _delistingsReceived; private Symbol _esFuture; private Symbol _esFutureOption; private readonly DateTime _expectedExpiryWarningTime = new DateTime(2020, 6, 19); private readonly DateTime _expectedExpiryDelistingTime = new DateTime(2020, 6, 20); private readonly DateTime _expectedLiquidationTime = new DateTime(2020, 6, 20); public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 12, 1); SetCash(100000); var es = QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)); var esOption = QuantConnect.Symbol.CreateOption( es, Market.CME, OptionStyle.American, OptionRight.Put, 3400m, new DateTime(2020, 6, 19)); _esFuture = AddFutureContract(es, Resolution.Minute).Symbol; _esFutureOption = AddFutureOptionContract(esOption, Resolution.Minute).Symbol; } public override void OnData(Slice data) { foreach (var delisting in data.Delistings.Values) { // Two warnings and two delisted events should be received for a grand total of 4 events. _delistingsReceived++; if (delisting.Type == DelistingType.Warning && delisting.Time != _expectedExpiryWarningTime) { throw new Exception($"Expiry warning with time {delisting.Time} but is expected to be {_expectedExpiryWarningTime}"); } if (delisting.Type == DelistingType.Warning && delisting.Time != Time.Date) { throw new Exception($"Delisting warning received at an unexpected date: {Time} - expected {delisting.Time}"); } if (delisting.Type == DelistingType.Delisted && delisting.Time != _expectedExpiryDelistingTime) { throw new Exception($"Delisting occurred at unexpected time: {delisting.Time} - expected: {_expectedExpiryDelistingTime}"); } if (delisting.Type == DelistingType.Delisted && delisting.Time != Time.Date) { throw new Exception($"Delisting notice received at an unexpected date: {Time} - expected {delisting.Time}"); } } if (!_invested && (data.Bars.ContainsKey(_esFuture) || data.QuoteBars.ContainsKey(_esFuture)) && (data.Bars.ContainsKey(_esFutureOption) || data.QuoteBars.ContainsKey(_esFutureOption))) { _invested = true; MarketOrder(_esFuture, 1); var optionContract = Securities[_esFutureOption]; var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel; if (marginModel.InitialIntradayMarginRequirement == 0 || marginModel.InitialOvernightMarginRequirement == 0 || marginModel.MaintenanceIntradayMarginRequirement == 0 || marginModel.MaintenanceOvernightMarginRequirement == 0) { throw new Exception("Unexpected margin requirements"); } if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0) { throw new Exception("Unexpected Initial Margin requirement"); } if (marginModel.GetMaintenanceMargin(optionContract) != 0) { throw new Exception("Unexpected Maintenance Margin requirement"); } MarketOrder(_esFutureOption, 1); if (marginModel.GetMaintenanceMargin(optionContract) == 0) { throw new Exception("Unexpected Maintenance Margin requirement"); } } } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Direction != OrderDirection.Sell || orderEvent.Status != OrderStatus.Filled) { return; } // * Future Liquidation // * Future Option Exercise // * We expect NO Underlying Future Liquidation because we already hold a Long future position so the FOP Put selling leaves us breakeven _liquidated++; if (orderEvent.Symbol.SecurityType == SecurityType.FutureOption && _expectedLiquidationTime != Time) { throw new Exception($"Expected to liquidate option {orderEvent.Symbol} at {_expectedLiquidationTime}, instead liquidated at {Time}"); } if (orderEvent.Symbol.SecurityType == SecurityType.Future && _expectedLiquidationTime.AddMinutes(-1) != Time && _expectedLiquidationTime != Time) { throw new Exception($"Expected to liquidate future {orderEvent.Symbol} at {_expectedLiquidationTime} (+1 minute), instead liquidated at {Time}"); } } public override void OnEndOfAlgorithm() { if (!_invested) { throw new Exception("Never invested in ES futures and FOPs"); } if (_delistingsReceived != 4) { throw new Exception($"Expected 4 delisting events received, found: {_delistingsReceived}"); } if (_liquidated != 2) { throw new Exception($"Expected 3 liquidation events, found {_liquidated}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "3"}, {"Average Win", "10.15%"}, {"Average Loss", "-11.34%"}, {"Compounding Annual Return", "-2.573%"}, {"Drawdown", "2.300%"}, {"Expectancy", "-0.052"}, {"Net Profit", "-2.341%"}, {"Sharpe Ratio", "-0.867"}, {"Probabilistic Sharpe Ratio", "0.001%"}, {"Loss Rate", "50%"}, {"Win Rate", "50%"}, {"Profit-Loss Ratio", "0.90"}, {"Alpha", "-0.014"}, {"Beta", "0.001"}, {"Annual Standard Deviation", "0.016"}, {"Annual Variance", "0"}, {"Information Ratio", "-0.603"}, {"Tracking Error", "0.291"}, {"Treynor Ratio", "-13.292"}, {"Total Fees", "$3.70"}, {"Estimated Strategy Capacity", "$45000000.00"}, {"Lowest Capacity Asset", "ES XFH59UK0MYO1"}, {"Fitness Score", "0.005"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-0.181"}, {"Return Over Maximum Drawdown", "-1.1"}, {"Portfolio Turnover", "0.013"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "67d8ad460ff796937ee252c3e4340e62"} }; } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ namespace UniversalDetector.Core { public abstract class BulgarianModel : SequenceModel { //Model Table: //total sequences: 100% //first 512 sequences: 96.9392% //first 1024 sequences:3.0618% //rest sequences: 0.2992% //negative sequences: 0.0020% private static byte[] BULGARIAN_LANG_MODEL = { 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,2,2,1,2,2, 3,1,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,0,1, 0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,3,3,0,3,1,0, 0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,1,3,3,3,3,2,2,2,1,1,2,0,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,2,3,2,2,3,3,1,1,2,3,3,2,3,3,3,3,2,1,2,0,2,0,3,0,0, 0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,1,3,3,3,3,3,2,3,2,3,3,3,3,3,2,3,3,1,3,0,3,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,1,3,3,2,3,3,3,1,3,3,2,3,2,2,2,0,0,2,0,2,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,3,3,1,2,2,3,2,1,1,2,0,2,0,0,0,0, 1,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,2,3,3,1,2,3,2,2,2,3,3,3,3,3,2,2,3,1,2,0,2,1,2,0,0, 0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,1,3,3,3,3,3,2,3,3,3,2,3,3,2,3,2,2,2,3,1,2,0,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,3,3,1,1,1,2,2,1,3,1,3,2,2,3,0,0,1,0,1,0,1,0,0, 0,0,0,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,2,2,3,2,2,3,1,2,1,1,1,2,3,1,3,1,2,2,0,1,1,1,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,1,3,2,2,3,3,1,2,3,1,1,3,3,3,3,1,2,2,1,1,1,0,2,0,2,0,1, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,2,2,3,3,3,2,2,1,1,2,0,2,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,0,1,2,1,3,3,2,3,3,3,3,3,2,3,2,1,0,3,1,2,1,2,1,2,3,2,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,1,3,3,2,3,3,2,2,2,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,0,3,3,3,3,3,2,1,1,2,1,3,3,0,3,1,1,1,1,3,2,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,1,1,3,1,3,3,2,3,2,2,2,3,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,3,2,2,3,2,1,1,1,1,1,3,1,3,1,1,0,0,0,1,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,2,0,3,2,0,3,0,2,0,0,2,1,3,1,0,0,1,0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,2,1,1,1,1,2,1,1,2,1,1,1,2,2,1,2,1,1,1,0,1,1,0,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,2,1,3,1,1,2,1,3,2,1,1,0,1,2,3,2,1,1,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,3,3,3,3,2,2,1,0,1,0,0,1,0,0,0,2,1,0,3,0,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,2,3,2,3,3,1,3,2,1,1,1,2,1,1,2,1,3,0,1,0,0,0,1,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,1,1,2,2,3,3,2,3,2,2,2,3,1,2,2,1,1,2,1,1,2,2,0,1,1,0,1,0,2,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,2,1,3,1,0,2,2,1,3,2,1,0,0,2,0,2,0,1,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1, 3,3,3,3,3,3,1,2,0,2,3,1,2,3,2,0,1,3,1,2,1,1,1,0,0,1,0,0,2,2,2,3, 2,2,2,2,1,2,1,1,2,2,1,1,2,0,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,0,1, 3,3,3,3,3,2,1,2,2,1,2,0,2,0,1,0,1,2,1,2,1,1,0,0,0,1,0,1,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1, 3,3,2,3,3,1,1,3,1,0,3,2,1,0,0,0,1,2,0,2,0,1,0,0,0,1,0,1,2,1,2,2, 1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1,0,1,2,1,1,1,0,0,0,0,0,1,1,0,0, 3,1,0,1,0,2,3,2,2,2,3,2,2,2,2,2,1,0,2,1,2,1,1,1,0,1,2,1,2,2,2,1, 1,1,2,2,2,2,1,2,1,1,0,1,2,1,2,2,2,1,1,1,0,1,1,1,1,2,0,1,0,0,0,0, 2,3,2,3,3,0,0,2,1,0,2,1,0,0,0,0,2,3,0,2,0,0,0,0,0,1,0,0,2,0,1,2, 2,1,2,1,2,2,1,1,1,2,1,1,1,0,1,2,2,1,1,1,1,1,0,1,1,1,0,0,1,2,0,0, 3,3,2,2,3,0,2,3,1,1,2,0,0,0,1,0,0,2,0,2,0,0,0,1,0,1,0,1,2,0,2,2, 1,1,1,1,2,1,0,1,2,2,2,1,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,1,0,0, 2,3,2,3,3,0,0,3,0,1,1,0,1,0,0,0,2,2,1,2,0,0,0,0,0,0,0,0,2,0,1,2, 2,2,1,1,1,1,1,2,2,2,1,0,2,0,1,0,1,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0, 3,3,3,3,2,2,2,2,2,0,2,1,1,1,1,2,1,2,1,1,0,2,0,1,0,1,0,0,2,0,1,2, 1,1,1,1,1,1,1,2,2,1,1,0,2,0,1,0,2,0,0,1,1,1,0,0,2,0,0,0,1,1,0,0, 2,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0,0,0,0,1,2,0,1,2, 2,2,2,1,1,2,1,1,2,2,2,1,2,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,1,1,0,0, 2,3,3,3,3,0,2,2,0,2,1,0,0,0,1,1,1,2,0,2,0,0,0,3,0,0,0,0,2,0,2,2, 1,1,1,2,1,2,1,1,2,2,2,1,2,0,1,1,1,0,1,1,1,1,0,2,1,0,0,0,1,1,0,0, 2,3,3,3,3,0,2,1,0,0,2,0,0,0,0,0,1,2,0,2,0,0,0,0,0,0,0,0,2,0,1,2, 1,1,1,2,1,1,1,1,2,2,2,0,1,0,1,1,1,0,0,1,1,1,0,0,1,0,0,0,0,1,0,0, 3,3,2,2,3,0,1,0,1,0,0,0,0,0,0,0,1,1,0,3,0,0,0,0,0,0,0,0,1,0,2,2, 1,1,1,1,1,2,1,1,2,2,1,2,2,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,1,1,0,0, 3,1,0,1,0,2,2,2,2,3,2,1,1,1,2,3,0,0,1,0,2,1,1,0,1,1,1,1,2,1,1,1, 1,2,2,1,2,1,2,2,1,1,0,1,2,1,2,2,1,1,1,0,0,1,1,1,2,1,0,1,0,0,0,0, 2,1,0,1,0,3,1,2,2,2,2,1,2,2,1,1,1,0,2,1,2,2,1,1,2,1,1,0,2,1,1,1, 1,2,2,2,2,2,2,2,1,2,0,1,1,0,2,1,1,1,1,1,0,0,1,1,1,1,0,1,0,0,0,0, 2,1,1,1,1,2,2,2,2,1,2,2,2,1,2,2,1,1,2,1,2,3,2,2,1,1,1,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,3,2,0,1,2,0,1,2,1,1,0,1,0,1,2,1,2,0,0,0,1,1,0,0,0,1,0,0,2, 1,1,0,0,1,1,0,1,1,1,1,0,2,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0, 2,0,0,0,0,1,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,2,1,1,1, 1,2,2,2,2,1,1,2,1,2,1,1,1,0,2,1,2,1,1,1,0,2,1,1,1,1,0,1,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0, 1,1,0,1,0,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,3,2,0,0,0,0,1,0,0,0,0,0,0,1,1,0,2,0,0,0,0,0,0,0,0,1,0,1,2, 1,1,1,1,1,1,0,0,2,2,2,2,2,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0,1,1,0,1, 2,3,1,2,1,0,1,1,0,2,2,2,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,1,2, 1,1,1,1,2,1,1,1,1,1,1,1,1,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0, 2,2,2,2,2,0,0,2,0,0,2,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,0,2,2, 1,1,1,1,1,0,0,1,2,1,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,0,2,0,1,1,0,0,0,1,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,1,1, 0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,3,2,0,0,1,0,0,1,0,0,0,0,0,0,1,0,2,0,0,0,1,0,0,0,0,0,0,0,2, 1,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 2,1,2,2,2,1,2,1,2,2,1,1,2,1,1,1,0,1,1,1,1,2,0,1,0,1,1,1,1,0,1,1, 1,1,2,1,1,1,1,1,1,0,0,1,2,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0, 1,0,0,1,3,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,1,0,0,1,0,2,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,2,0,0,1, 0,2,0,1,0,0,1,1,2,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 1,2,2,2,2,0,1,1,0,2,1,0,1,1,1,0,0,1,0,2,0,1,0,0,0,0,0,0,0,0,0,1, 0,1,0,0,1,0,0,0,1,1,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1, 0,1,0,1,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0, 2,0,1,0,0,1,2,1,1,1,1,1,1,2,2,1,0,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0, 1,1,2,1,1,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,2,1,2,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0, 0,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, 1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,2,0,0,2,0,1,0,0,1,0,0,1, 1,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0, 1,1,1,1,1,1,1,2,0,0,0,0,0,0,2,1,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1, }; public BulgarianModel(byte[] charToOrderMap, string name) : base(charToOrderMap, BULGARIAN_LANG_MODEL, 0.969392f, false, name) { } } public class Latin5BulgarianModel : BulgarianModel { //255: Control characters that usually does not exist in any text //254: Carriage/Return //253: symbol (punctuation) that does not belong to word //252: 0 - 9 // Character Mapping Table: // this table is modified base on win1251BulgarianCharToOrderMap, so // only number <64 is sure valid private static byte[] LATIN5_CHAR_TO_ORDER_MAP = { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 +253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, //40 110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, //50 253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, //60 116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, //70 194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209, //80 210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225, //90 81,226,227,228,229,230,105,231,232,233,234,235,236, 45,237,238, //a0 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, //b0 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,239, 67,240, 60, 56, //c0 1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, //d0 7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,241, 42, 16, //e0 62,242,243,244, 58,245, 98,246,247,248,249,250,251, 91,252,253, //f0 }; public Latin5BulgarianModel() : base(LATIN5_CHAR_TO_ORDER_MAP, "ISO-8859-5") { } } public class Win1251BulgarianModel : BulgarianModel { private static byte[] WIN1251__CHAR_TO_ORDER_MAP = { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 +253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, //40 110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, //50 253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, //60 116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, //70 206,207,208,209,210,211,212,213,120,214,215,216,217,218,219,220, //80 221, 78, 64, 83,121, 98,117,105,222,223,224,225,226,227,228,229, //90 88,230,231,232,233,122, 89,106,234,235,236,237,238, 45,239,240, //a0 73, 80,118,114,241,242,243,244,245, 62, 58,246,247,248,249,250, //b0 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, //c0 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,251, 67,252, 60, 56, //d0 1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, //e0 7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,253, 42, 16, //f0 }; public Win1251BulgarianModel() : base(WIN1251__CHAR_TO_ORDER_MAP, "windows-1251") { } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Xml.XPath; using SIL.Lift.Merging.xmldiff; namespace SIL.Lift.Merging { ///<summary></summary> public interface ILiftChangeDetector { /// <summary> /// Makes the reference data just reflect exactly what is in the lift file. Only changes made after calling this will be detected. /// </summary> void Reset(); ///<summary></summary> void ClearCache(); ///<summary></summary> bool CanProvideChangeRecord { get; } ///<summary></summary> ILiftChangeReport GetChangeReport(IProgress progress); } ///<summary></summary> public class LiftChangeDetector : ILiftChangeDetector { private readonly string _pathToLift; private readonly string _pathToCacheDir; ///<summary></summary> public LiftChangeDetector(string pathToLift, string pathToCacheDir) { _pathToLift = pathToLift; _pathToCacheDir = pathToCacheDir; //no no no! Reset(); } /// <summary> /// Makes the reference data just reflect exactly what is in the lift file. Only changes made after calling this will be detected. /// </summary> public void Reset() { try { if (!Directory.Exists(_pathToCacheDir)) { return; //if they don't have a cache directory yet, then it's proper for us to NOT have a reference copy //we'll get reset() again after they build the cache/load the db/whatever. } File.Copy(_pathToLift, PathToReferenceCopy, true); } catch (Exception error) { throw new ApplicationException( string.Format("LiftChangeDetector could not copy the working file to the reference file at ({0} to {1}). {2}", _pathToLift, PathToReferenceCopy, error.Message)); } } ///<summary></summary> public void ClearCache() { if (File.Exists(PathToReferenceCopy)) { File.Delete(PathToReferenceCopy); } } ///<summary></summary> public bool CanProvideChangeRecord { get { return File.Exists(PathToReferenceCopy) && File.Exists(_pathToLift); } } ///<summary></summary> public ILiftChangeReport GetChangeReport(IProgress progress) { StreamReader reference=null; StreamReader working = null; try { try { reference = new StreamReader(PathToReferenceCopy); } catch (Exception error) { throw new ApplicationException( string.Format("Could not open LiftChangeDetector Reference file at {0}. {1}", PathToReferenceCopy, error.Message)); } working = new StreamReader(_pathToLift); return LiftChangeReport.DetermineChanges(reference, working, progress); } finally { if (reference != null) { reference.Dispose(); } if (working != null) { working.Dispose(); } } } private string PathToReferenceCopy { get { return Path.Combine(_pathToCacheDir, "reference.lift"); } } } ///<summary></summary> public interface ILiftChangeReport { ///<summary></summary> LiftChangeReport.ChangeType GetChangeType(string entryId); ///<summary></summary> IList<string> IdsOfDeletedEntries { get; } } ///<summary></summary> public class LiftChangeReport : ILiftChangeReport { private IList<string> _idsOfDeletedEntries; private IList<string> _idsOfAddedEntries; private IList<string> _idsOfEditedEntries; private IList<string> _idsInOriginal; ///<summary></summary> public enum ChangeType { ///<summary></summary> None, ///<summary></summary> Editted, ///<summary></summary> New, ///<summary></summary> Deleted } ///<summary></summary> public static LiftChangeReport DetermineChanges(TextReader original, TextReader modified, IProgress progress) { LiftChangeReport detector = new LiftChangeReport(); detector.ComputeDiff(original, modified, progress); return detector; } ///<summary></summary> public ChangeType GetChangeType(string entryId) { if(_idsOfEditedEntries.Contains(entryId)) return ChangeType.Editted; if (_idsOfAddedEntries .Contains(entryId)) return ChangeType.New; //a client is probably going to use the IdsOfDeletedEntries that to give us ids of the original file, but //we do this here for completeness if (_idsOfDeletedEntries .Contains(entryId)) return ChangeType.Deleted; return ChangeType.None; } ///<summary></summary> public IList<string> IdsOfDeletedEntries { get { return _idsOfDeletedEntries; } } private void ComputeDiff(TextReader original, TextReader modified, IProgress progress) { //enchance: just get a checksum for each entry in both files, use that to determine everything else _idsOfDeletedEntries = new List<string>(); _idsOfAddedEntries = new List<string>(); _idsOfEditedEntries = new List<string>(); _idsInOriginal = new List<string>(); XPathDocument modifiedDoc = new XPathDocument(modified); XPathNavigator modifiedNav = modifiedDoc.CreateNavigator(); XPathDocument originalDoc = new XPathDocument(original); XPathNavigator originalNav = originalDoc.CreateNavigator(); XPathNodeIterator liftElement = originalNav.SelectChildren(XPathNodeType.Element); liftElement.MoveNext();//move to the one and only <lift> element if (liftElement.Current == null) return; XPathNodeIterator originalChildren = liftElement.Current.SelectChildren(XPathNodeType.Element); StringDictionary idToContentsOfModifiedEntries = new StringDictionary(); XPathNodeIterator liftOfModifiedFile = modifiedNav.SelectChildren(XPathNodeType.Element); liftOfModifiedFile.MoveNext(); if (liftOfModifiedFile.Current != null) { XPathNodeIterator modifiedChildren = liftOfModifiedFile.Current.SelectChildren(XPathNodeType.Element); while (modifiedChildren.MoveNext()) { //TODO: consider if there are benefits to using guid as the first key, then try id if (modifiedChildren.Current != null) { string id = modifiedChildren.Current.GetAttribute("id", string.Empty); idToContentsOfModifiedEntries.Add(id, modifiedChildren.Current.OuterXml); } } } while (originalChildren.MoveNext()) { if (originalChildren.Current != null) { string id = originalChildren.Current.GetAttribute("id", string.Empty); _idsInOriginal.Add(id); if(!idToContentsOfModifiedEntries.ContainsKey(id)) { _idsOfDeletedEntries.Add(id); } else { var diff = new XmlDiff(originalChildren.Current.OuterXml, idToContentsOfModifiedEntries[id]); DiffResult result = diff.Compare(); if (!result.AreEqual) { _idsOfEditedEntries.Add(id); } } } } foreach (string id in idToContentsOfModifiedEntries.Keys) { if(!_idsInOriginal.Contains(id)) _idsOfAddedEntries.Add(id); } } } ///<summary> /// Minimal interface for progress reporting. ///</summary> public interface IProgress { ///<summary> /// Get/set the status message for a progress report. ///</summary> string Status { set; get; } } ///<summary> /// Nonfunctional progress reporting class: minimal implementation of IProgress. /// (possibly useful for tests) ///</summary> public class NullProgress : IProgress { private string _status; ///<summary></summary> public string Status { get { return _status; } set { _status = value; } } } }
// // X509CertificateStore.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Collections; using System.Collections.Generic; using Org.BouncyCastle.Security; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace MimeKit.Cryptography { /// <summary> /// A store for X.509 certificates and keys. /// </summary> /// <remarks> /// A store for X.509 certificates and keys. /// </remarks> public class X509CertificateStore : IX509Store { readonly Dictionary<X509Certificate, AsymmetricKeyParameter> keys; readonly HashSet<X509Certificate> unique; readonly List<X509Certificate> certs; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Cryptography.X509CertificateStore"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="X509CertificateStore"/>. /// </remarks> public X509CertificateStore () { keys = new Dictionary<X509Certificate, AsymmetricKeyParameter> (); unique = new HashSet<X509Certificate> (); certs = new List<X509Certificate> (); } /// <summary> /// Enumerates the certificates currently in the store. /// </summary> /// <remarks> /// Enumerates the certificates currently in the store. /// </remarks> /// <value>The certificates.</value> public IEnumerable<X509Certificate> Certificates { get { return certs; } } /// <summary> /// Gets the private key for the specified certificate. /// </summary> /// <remarks> /// Gets the private key for the specified certificate, if it exists. /// </remarks> /// <returns>The private key on success; otherwise <c>null</c>.</returns> /// <param name="certificate">The certificate.</param> public AsymmetricKeyParameter GetPrivateKey (X509Certificate certificate) { AsymmetricKeyParameter key; if (!keys.TryGetValue (certificate, out key)) return null; return key; } /// <summary> /// Adds the specified certificate to the store. /// </summary> /// <remarks> /// Adds the specified certificate to the store. /// </remarks> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public void Add (X509Certificate certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); if (unique.Add (certificate)) certs.Add (certificate); } /// <summary> /// Adds the specified range of certificates to the store. /// </summary> /// <remarks> /// Adds the specified range of certificates to the store. /// </remarks> /// <param name="certificates">The certificates.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificates"/> is <c>null</c>. /// </exception> public void AddRange (IEnumerable<X509Certificate> certificates) { if (certificates == null) throw new ArgumentNullException ("certificates"); foreach (var certificate in certificates) { if (unique.Add (certificate)) certs.Add (certificate); } } /// <summary> /// Removes the specified certificate from the store. /// </summary> /// <remarks> /// Removes the specified certificate from the store. /// </remarks> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public void Remove (X509Certificate certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); if (unique.Remove (certificate)) certs.Remove (certificate); } /// <summary> /// Removes the specified range of certificates from the store. /// </summary> /// <remarks> /// Removes the specified range of certificates from the store. /// </remarks> /// <param name="certificates">The certificates.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificates"/> is <c>null</c>. /// </exception> public void RemoveRange (IEnumerable<X509Certificate> certificates) { if (certificates == null) throw new ArgumentNullException ("certificates"); foreach (var certificate in certificates) { if (unique.Remove (certificate)) certs.Remove (certificate); } } /// <summary> /// Imports the certificate(s) from the specified stream. /// </summary> /// <remarks> /// Imports the certificate(s) from the specified stream. /// </remarks> /// <param name="stream">The stream to import.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the stream. /// </exception> public void Import (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); var parser = new X509CertificateParser (); foreach (X509Certificate certificate in parser.ReadCertificates (stream)) { if (unique.Add (certificate)) certs.Add (certificate); } } #if !PORTABLE /// <summary> /// Imports the certificate(s) from the specified file. /// </summary> /// <remarks> /// Imports the certificate(s) from the specified file. /// </remarks> /// <param name="fileName">The name of the file to import.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="fileName"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.FileNotFoundException"> /// The specified file could not be found. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the file. /// </exception> public void Import (string fileName) { if (fileName == null) throw new ArgumentNullException ("fileName"); using (var stream = File.OpenRead (fileName)) Import (stream); } #endif /// <summary> /// Imports the certificate(s) from the specified byte array. /// </summary> /// <remarks> /// Imports the certificate(s) from the specified byte array. /// </remarks> /// <param name="rawData">The raw certificate data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="rawData"/> is <c>null</c>. /// </exception> public void Import (byte[] rawData) { if (rawData == null) throw new ArgumentNullException ("rawData"); using (var stream = new MemoryStream (rawData, false)) Import (stream); } /// <summary> /// Imports certificates and private keys from the specified stream. /// </summary> /// <remarks> /// <para>Imports certificates and private keys from the specified pkcs12 stream.</para> /// </remarks> /// <param name="stream">The stream to import.</param> /// <param name="password">The password to unlock the stream.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the stream. /// </exception> public void Import (Stream stream, string password) { if (stream == null) throw new ArgumentNullException ("stream"); if (password == null) throw new ArgumentNullException ("password"); var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ()); foreach (string alias in pkcs12.Aliases) { if (pkcs12.IsKeyEntry (alias)) { var chain = pkcs12.GetCertificateChain (alias); var entry = pkcs12.GetKey (alias); for (int i = 0; i < chain.Length; i++) { if (unique.Add (chain[i].Certificate)) certs.Add (chain[i].Certificate); } if (entry.Key.IsPrivate) keys.Add (chain[0].Certificate, entry.Key); } else if (pkcs12.IsCertificateEntry (alias)) { var entry = pkcs12.GetCertificate (alias); if (unique.Add (entry.Certificate)) certs.Add (entry.Certificate); } } } #if !PORTABLE /// <summary> /// Imports certificates and private keys from the specified file. /// </summary> /// <remarks> /// <para>Imports certificates and private keys from the specified pkcs12 stream.</para> /// </remarks> /// <param name="fileName">The name of the file to import.</param> /// <param name="password">The password to unlock the file.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="fileName"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="fileName"/> is a zero-length string, contains only white space, or /// contains one or more invalid characters as defined by /// <see cref="System.IO.Path.InvalidPathChars"/>. /// </exception> /// <exception cref="System.IO.FileNotFoundException"> /// The specified file could not be found. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to read the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred reading the file. /// </exception> public void Import (string fileName, string password) { if (fileName == null) throw new ArgumentNullException ("fileName"); using (var stream = File.OpenRead (fileName)) Import (stream, password); } #endif /// <summary> /// Imports certificates and private keys from the specified byte array. /// </summary> /// <remarks> /// <para>Imports certificates and private keys from the specified pkcs12 stream.</para> /// </remarks> /// <param name="rawData">The raw certificate data.</param> /// <param name="password">The password to unlock the raw data.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="rawData"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> public void Import (byte[] rawData, string password) { if (rawData == null) throw new ArgumentNullException ("rawData"); using (var stream = new MemoryStream (rawData, false)) Import (stream, password); } /// <summary> /// Exports the certificates to an unencrypted stream. /// </summary> /// <remarks> /// Exports the certificates to an unencrypted stream. /// </remarks> /// <param name="stream">The output stream.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); foreach (var certificate in certs) { var encoded = certificate.GetEncoded (); stream.Write (encoded, 0, encoded.Length); } } #if !PORTABLE /// <summary> /// Exports the certificates to an unencrypted file. /// </summary> /// <remarks> /// Exports the certificates to an unencrypted file. /// </remarks> /// <param name="fileName">The file path to write to.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="fileName"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="fileName"/> is a zero-length string, contains only white space, or /// contains one or more invalid characters as defined by /// <see cref="System.IO.Path.InvalidPathChars"/>. /// </exception> /// <exception cref="System.IO.PathTooLongException"> /// The specified path exceeds the maximum allowed path length of the system. /// </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> /// A directory in the specified path does not exist. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to create the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (string fileName) { if (fileName == null) throw new ArgumentNullException ("fileName"); using (var file = File.Create (fileName)) Export (file); } #endif /// <summary> /// Exports the specified stream and password to a pkcs12 encrypted file. /// </summary> /// <remarks> /// Exports the specified stream and password to a pkcs12 encrypted file. /// </remarks> /// <param name="stream">The output stream.</param> /// <param name="password">The password to use to lock the private keys.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (Stream stream, string password) { if (stream == null) throw new ArgumentNullException ("stream"); if (password == null) throw new ArgumentNullException ("password"); var store = new Pkcs12Store (); foreach (var certificate in certs) { if (keys.ContainsKey (certificate)) continue; var alias = certificate.GetCommonName (); if (alias == null) continue; var entry = new X509CertificateEntry (certificate); store.SetCertificateEntry (alias, entry); } foreach (var kvp in keys) { var alias = kvp.Key.GetCommonName (); if (alias == null) continue; var entry = new AsymmetricKeyEntry (kvp.Value); var cert = new X509CertificateEntry (kvp.Key); var chain = new List<X509CertificateEntry> (); chain.Add (cert); store.SetKeyEntry (alias, entry, chain.ToArray ()); } store.Save (stream, password.ToCharArray (), new SecureRandom ()); } #if !PORTABLE /// <summary> /// Exports the specified stream and password to a pkcs12 encrypted file. /// </summary> /// <remarks> /// Exports the specified stream and password to a pkcs12 encrypted file. /// </remarks> /// <param name="fileName">The file path to write to.</param> /// <param name="password">The password to use to lock the private keys.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="fileName"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="fileName"/> is a zero-length string, contains only white space, or /// contains one or more invalid characters as defined by /// <see cref="System.IO.Path.InvalidPathChars"/>. /// </exception> /// <exception cref="System.IO.PathTooLongException"> /// The specified path exceeds the maximum allowed path length of the system. /// </exception> /// <exception cref="System.IO.DirectoryNotFoundException"> /// A directory in the specified path does not exist. /// </exception> /// <exception cref="System.UnauthorizedAccessException"> /// The user does not have access to create the specified file. /// </exception> /// <exception cref="System.IO.IOException"> /// An error occurred while writing to the stream. /// </exception> public void Export (string fileName, string password) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (password == null) throw new ArgumentNullException ("password"); using (var file = File.Create (fileName)) Export (file, password); } #endif /// <summary> /// Gets an enumerator of matching X.509 certificates based on the specified selector. /// </summary> /// <remarks> /// Gets an enumerator of matching X.509 certificates based on the specified selector. /// </remarks> /// <returns>The matching certificates.</returns> /// <param name="selector">The match criteria.</param> public IEnumerable<X509Certificate> GetMatches (IX509Selector selector) { foreach (var certificate in certs) { if (selector == null || selector.Match (certificate)) yield return certificate; } yield break; } #region IX509Store implementation /// <summary> /// Gets a collection of matching X.509 certificates based on the specified selector. /// </summary> /// <remarks> /// Gets a collection of matching X.509 certificates based on the specified selector. /// </remarks> /// <returns>The matching certificates.</returns> /// <param name="selector">The match criteria.</param> ICollection IX509Store.GetMatches (IX509Selector selector) { var matches = new List<X509Certificate> (); foreach (var certificate in GetMatches (selector)) matches.Add (certificate); return matches; } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Documents; using AlreadyClosedException = Lucene.Net.Store.AlreadyClosedException; using BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput; using CloseableThreadLocal = Lucene.Net.Util.CloseableThreadLocal; using Directory = Lucene.Net.Store.Directory; using IndexInput = Lucene.Net.Store.IndexInput; using TokenStream = Lucene.Net.Analysis.TokenStream; namespace Lucene.Net.Index { /// <summary> Class responsible for access to stored document fields. /// <p/> /// It uses &lt;segment&gt;.fdt and &lt;segment&gt;.fdx; files. /// </summary> public sealed class FieldsReader { private FieldInfos fieldInfos; // The main fieldStream, used only for cloning. private IndexInput cloneableFieldsStream; // This is a clone of cloneableFieldsStream used for reading documents. // It should not be cloned outside of a synchronized context. private IndexInput fieldsStream; private IndexInput indexStream; private int numTotalDocs; private int size; private bool closed; private readonly int format; private readonly int formatSize; // The docID offset where our docs begin in the index // file. This will be 0 if we have our own private file. private int docStoreOffset; //private System.LocalDataStoreSlot fieldsStreamTL = System.Threading.Thread.AllocateDataSlot(); private CloseableThreadLocal fieldsStreamTL = new CloseableThreadLocal(); public FieldsReader(Directory d, System.String segment, FieldInfos fn) : this(d, segment, fn, BufferedIndexInput.BUFFER_SIZE, -1, 0) { } internal FieldsReader(Directory d, System.String segment, FieldInfos fn, int readBufferSize) : this(d, segment, fn, readBufferSize, -1, 0) { } internal FieldsReader(Directory d, System.String segment, FieldInfos fn, int readBufferSize, int docStoreOffset, int size) { bool success = false; try { fieldInfos = fn; cloneableFieldsStream = d.OpenInput(segment + "." + IndexFileNames.FIELDS_EXTENSION, readBufferSize); indexStream = d.OpenInput(segment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION, readBufferSize); // First version of fdx did not include a format // header, but, the first int will always be 0 in that // case int firstInt = indexStream.ReadInt(); if (firstInt == 0) format = 0; else format = firstInt; if (format > FieldsWriter.FORMAT_CURRENT) throw new CorruptIndexException("Incompatible format version: " + format + " expected " + FieldsWriter.FORMAT_CURRENT + " or lower"); if (format > FieldsWriter.FORMAT) formatSize = 4; else formatSize = 0; if (format < FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) cloneableFieldsStream.SetModifiedUTF8StringsMode(); fieldsStream = (IndexInput)cloneableFieldsStream.Clone(); long indexSize = indexStream.Length() - formatSize; if (docStoreOffset != -1) { // We read only a slice out of this shared fields file this.docStoreOffset = docStoreOffset; this.size = size; // Verify the file is long enough to hold all of our // docs System.Diagnostics.Debug.Assert(((int)(indexSize / 8)) >= size + this.docStoreOffset, "indexSize=" + indexSize + " size=" + size + docStoreOffset); } else { this.docStoreOffset = 0; this.size = (int)(indexSize >> 3); } numTotalDocs = (int)(indexSize >> 3); success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { Close(); } } } /// <throws> AlreadyClosedException if this FieldsReader is closed </throws> internal void EnsureOpen() { if (closed) { throw new AlreadyClosedException("this FieldsReader is closed"); } } /// <summary> Closes the underlying {@link Lucene.Net.Store.IndexInput} streams, including any ones associated with a /// lazy implementation of a Field. This means that the Fields values will not be accessible. /// /// </summary> /// <throws> IOException </throws> public void Close() { if (!closed) { if (fieldsStream != null) { fieldsStream.Close(); } if (cloneableFieldsStream != null) { cloneableFieldsStream.Close(); } if (indexStream != null) { indexStream.Close(); } fieldsStreamTL.Close(); closed = true; } } public int Size() { return size; } private void SeekIndex(int docID) { indexStream.Seek(formatSize + (docID + docStoreOffset) * 8L); } internal bool CanReadRawDocs() { return format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES; } public Document Doc(int n, FieldSelector fieldSelector) { SeekIndex(n); long position = indexStream.ReadLong(); fieldsStream.Seek(position); Document doc = new Document(); int numFields = fieldsStream.ReadVInt(); for (int i = 0; i < numFields; i++) { int fieldNumber = fieldsStream.ReadVInt(); FieldInfo fi = fieldInfos.FieldInfo(fieldNumber); FieldSelectorResult acceptField = fieldSelector == null ? FieldSelectorResult.LOAD : fieldSelector.Accept(fi.name); byte bits = fieldsStream.ReadByte(); System.Diagnostics.Debug.Assert(bits <= FieldsWriter.FIELD_IS_COMPRESSED + FieldsWriter.FIELD_IS_TOKENIZED + FieldsWriter.FIELD_IS_BINARY); bool compressed = (bits & FieldsWriter.FIELD_IS_COMPRESSED) != 0; bool tokenize = (bits & FieldsWriter.FIELD_IS_TOKENIZED) != 0; bool binary = (bits & FieldsWriter.FIELD_IS_BINARY) != 0; //TODO: Find an alternative approach here if this list continues to grow beyond the //list of 5 or 6 currently here. See Lucene 762 for discussion if (acceptField.Equals(FieldSelectorResult.LOAD)) { AddField(doc, fi, binary, compressed, tokenize); } else if (acceptField.Equals(FieldSelectorResult.LOAD_FOR_MERGE)) { AddFieldForMerge(doc, fi, binary, compressed, tokenize); } else if (acceptField.Equals(FieldSelectorResult.LOAD_AND_BREAK)) { AddField(doc, fi, binary, compressed, tokenize); break; //Get out of this loop } else if (acceptField.Equals(FieldSelectorResult.LAZY_LOAD)) { AddFieldLazy(doc, fi, binary, compressed, tokenize); } else if (acceptField.Equals(FieldSelectorResult.SIZE)) { SkipField(binary, compressed, AddFieldSize(doc, fi, binary, compressed)); } else if (acceptField.Equals(FieldSelectorResult.SIZE_AND_BREAK)) { AddFieldSize(doc, fi, binary, compressed); break; } else { SkipField(binary, compressed); } } return doc; } /// <summary>Returns the length in bytes of each raw document in a /// contiguous range of length numDocs starting with /// startDocID. Returns the IndexInput (the fieldStream), /// already seeked to the starting point for startDocID. /// </summary> internal IndexInput RawDocs(int[] lengths, int startDocID, int numDocs) { SeekIndex(startDocID); long startOffset = indexStream.ReadLong(); long lastOffset = startOffset; int count = 0; while (count < numDocs) { long offset; int docID = docStoreOffset + startDocID + count + 1; System.Diagnostics.Debug.Assert(docID <= numTotalDocs); if (docID < numTotalDocs) offset = indexStream.ReadLong(); else offset = fieldsStream.Length(); lengths[count++] = (int)(offset - lastOffset); lastOffset = offset; } fieldsStream.Seek(startOffset); return fieldsStream; } /// <summary> Skip the field. We still have to read some of the information about the field, but can skip past the actual content. /// This will have the most payoff on large fields. /// </summary> private void SkipField(bool binary, bool compressed) { SkipField(binary, compressed, fieldsStream.ReadVInt()); } private void SkipField(bool binary, bool compressed, int toRead) { if (format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES || binary || compressed) { fieldsStream.Seek(fieldsStream.GetFilePointer() + toRead); } else { //We need to skip chars. This will slow us down, but still better fieldsStream.SkipChars(toRead); } } private void AddFieldLazy(Document doc, FieldInfo fi, bool binary, bool compressed, bool tokenize) { if (binary) { int toRead = fieldsStream.ReadVInt(); long pointer = fieldsStream.GetFilePointer(); if (compressed) { //was: doc.add(new Fieldable(fi.name, uncompress(b), Fieldable.Store.COMPRESS)); doc.Add(new LazyField(this, fi.name, Field.Store.COMPRESS, toRead, pointer, binary)); } else { //was: doc.add(new Fieldable(fi.name, b, Fieldable.Store.YES)); doc.Add(new LazyField(this, fi.name, Field.Store.YES, toRead, pointer, binary)); } //Need to move the pointer ahead by toRead positions fieldsStream.Seek(pointer + toRead); } else { Field.Store store = Field.Store.YES; Field.Index index = GetIndexType(fi, tokenize); Field.TermVector termVector = GetTermVectorType(fi); Fieldable f; if (compressed) { store = Field.Store.COMPRESS; int toRead = fieldsStream.ReadVInt(); long pointer = fieldsStream.GetFilePointer(); f = new LazyField(this, fi.name, store, toRead, pointer, binary); //skip over the part that we aren't loading fieldsStream.Seek(pointer + toRead); f.SetOmitNorms(fi.omitNorms); } else { int length = fieldsStream.ReadVInt(); long pointer = fieldsStream.GetFilePointer(); //Skip ahead of where we are by the length of what is stored if (format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) fieldsStream.Seek(pointer + length); else fieldsStream.SkipChars(length); f = new LazyField(this, fi.name, store, index, termVector, length, pointer, binary); f.SetOmitNorms(fi.omitNorms); } doc.Add(f); } } // in merge mode we don't uncompress the data of a compressed field private void AddFieldForMerge(Document doc, FieldInfo fi, bool binary, bool compressed, bool tokenize) { object data; if (binary || compressed) { int toRead = fieldsStream.ReadVInt(); byte[] b = new byte[toRead]; fieldsStream.ReadBytes(b, 0, b.Length); data = b; } else { data = fieldsStream.ReadString(); } doc.Add(new FieldForMerge(data, fi, binary, compressed, tokenize)); } private void AddField(Document doc, FieldInfo fi, bool binary, bool compressed, bool tokenize) { //we have a binary stored field, and it may be compressed if (binary) { int toRead = fieldsStream.ReadVInt(); byte[] b = new byte[toRead]; fieldsStream.ReadBytes(b, 0, b.Length); if (compressed) doc.Add(new Field(fi.name, Uncompress(b), Field.Store.COMPRESS)); else doc.Add(new Field(fi.name, b, Field.Store.YES)); } else { Field.Store store = Field.Store.YES; Field.Index index = GetIndexType(fi, tokenize); Field.TermVector termVector = GetTermVectorType(fi); Fieldable f; if (compressed) { store = Field.Store.COMPRESS; int toRead = fieldsStream.ReadVInt(); byte[] b = new byte[toRead]; fieldsStream.ReadBytes(b, 0, b.Length); f = new Field(fi.name, System.Text.Encoding.GetEncoding("UTF-8").GetString(Uncompress(b)), store, index, termVector); f.SetOmitNorms(fi.omitNorms); } else { f = new Field(fi.name, fieldsStream.ReadString(), store, index, termVector); f.SetOmitNorms(fi.omitNorms); } doc.Add(f); } } // Add the size of field as a byte[] containing the 4 bytes of the integer byte size (high order byte first; char = 2 bytes) // Read just the size -- caller must skip the field content to continue reading fields // Return the size in bytes or chars, depending on field type private int AddFieldSize(Document doc, FieldInfo fi, bool binary, bool compressed) { int size = fieldsStream.ReadVInt(), bytesize = binary || compressed ? size : 2 * size; byte[] sizebytes = new byte[4]; sizebytes[0] = (byte)(SupportClass.Number.URShift(bytesize, 24)); sizebytes[1] = (byte)(SupportClass.Number.URShift(bytesize, 16)); sizebytes[2] = (byte)(SupportClass.Number.URShift(bytesize, 8)); sizebytes[3] = (byte)bytesize; doc.Add(new Field(fi.name, sizebytes, Field.Store.YES)); return size; } private Field.TermVector GetTermVectorType(FieldInfo fi) { Field.TermVector termVector = null; if (fi.storeTermVector) { if (fi.storeOffsetWithTermVector) { if (fi.storePositionWithTermVector) { termVector = Field.TermVector.WITH_POSITIONS_OFFSETS; } else { termVector = Field.TermVector.WITH_OFFSETS; } } else if (fi.storePositionWithTermVector) { termVector = Field.TermVector.WITH_POSITIONS; } else { termVector = Field.TermVector.YES; } } else { termVector = Field.TermVector.NO; } return termVector; } private Field.Index GetIndexType(FieldInfo fi, bool tokenize) { Field.Index index; if (fi.isIndexed && tokenize) index = Field.Index.ANALYZED; else if (fi.isIndexed && !tokenize) index = Field.Index.NOT_ANALYZED; else index = Field.Index.NO; return index; } /// <summary> A Lazy implementation of Fieldable that differs loading of fields until asked for, instead of when the Document is /// loaded. /// </summary> [Serializable] private class LazyField : AbstractField, Fieldable { private void InitBlock(FieldsReader enclosingInstance) { this.enclosingInstance = enclosingInstance; } private FieldsReader enclosingInstance; public FieldsReader Enclosing_Instance { get { return enclosingInstance; } } private int toRead; private long pointer; public LazyField(FieldsReader enclosingInstance, System.String name, Field.Store store, int toRead, long pointer, bool isBinary) : base(name, store, Field.Index.NO, Field.TermVector.NO) { InitBlock(enclosingInstance); this.toRead = toRead; this.pointer = pointer; this.isBinary = isBinary; if (isBinary) binaryLength = toRead; lazy = true; } public LazyField(FieldsReader enclosingInstance, System.String name, Field.Store store, Field.Index index, Field.TermVector termVector, int toRead, long pointer, bool isBinary) : base(name, store, index, termVector) { InitBlock(enclosingInstance); this.toRead = toRead; this.pointer = pointer; this.isBinary = isBinary; if (isBinary) binaryLength = toRead; lazy = true; } private IndexInput GetFieldStream() { IndexInput localFieldsStream = (IndexInput)Enclosing_Instance.fieldsStreamTL.Get(); if (localFieldsStream == null) { localFieldsStream = (IndexInput)Enclosing_Instance.cloneableFieldsStream.Clone(); Enclosing_Instance.fieldsStreamTL.Set(localFieldsStream); } return localFieldsStream; } /// <summary>The value of the field in Binary, or null. If null, the Reader value, /// String value, or TokenStream value is used. Exactly one of stringValue(), /// readerValue(), binaryValue(), and tokenStreamValue() must be set. /// </summary> public override byte[] BinaryValue() { return GetBinaryValue(null); } /// <summary>The value of the field as a Reader, or null. If null, the String value, /// binary value, or TokenStream value is used. Exactly one of stringValue(), /// readerValue(), binaryValue(), and tokenStreamValue() must be set. /// </summary> public override System.IO.TextReader ReaderValue() { Enclosing_Instance.EnsureOpen(); return null; } /// <summary>The value of the field as a TokesStream, or null. If null, the Reader value, /// String value, or binary value is used. Exactly one of stringValue(), /// readerValue(), binaryValue(), and tokenStreamValue() must be set. /// </summary> public override TokenStream TokenStreamValue() { Enclosing_Instance.EnsureOpen(); return null; } /// <summary>The value of the field as a String, or null. If null, the Reader value, /// binary value, or TokenStream value is used. Exactly one of stringValue(), /// readerValue(), binaryValue(), and tokenStreamValue() must be set. /// </summary> public override System.String StringValue() { Enclosing_Instance.EnsureOpen(); if (isBinary) return null; else { if (fieldsData == null) { IndexInput localFieldsStream = GetFieldStream(); try { localFieldsStream.Seek(pointer); if (isCompressed) { byte[] b = new byte[toRead]; localFieldsStream.ReadBytes(b, 0, b.Length); fieldsData = System.Text.Encoding.GetEncoding("UTF-8").GetString(Enclosing_Instance.Uncompress(b)); } else { if (Enclosing_Instance.format >= FieldsWriter.FORMAT_VERSION_UTF8_LENGTH_IN_BYTES) { byte[] bytes = new byte[toRead]; localFieldsStream.ReadBytes(bytes, 0, toRead); fieldsData = System.Text.Encoding.UTF8.GetString(bytes); } else { //read in chars b/c we already know the length we need to read char[] chars = new char[toRead]; localFieldsStream.ReadChars(chars, 0, toRead); fieldsData = new System.String(chars); } } } catch (System.IO.IOException e) { throw new FieldReaderException(e); } } } return (string)fieldsData; } public long GetPointer() { Enclosing_Instance.EnsureOpen(); return pointer; } public void SetPointer(long pointer) { Enclosing_Instance.EnsureOpen(); this.pointer = pointer; } public int GetToRead() { Enclosing_Instance.EnsureOpen(); return toRead; } public void SetToRead(int toRead) { Enclosing_Instance.EnsureOpen(); this.toRead = toRead; } public override byte[] GetBinaryValue(byte[] result) { Enclosing_Instance.EnsureOpen(); if (isBinary) { if (fieldsData == null) { // Allocate new bufer if result is null or too small byte[] b; if (result == null || result.Length < toRead) b = new byte[toRead]; else b = result; IndexInput localFieldsStream = GetFieldStream(); // Throw this IOException since IndexRead.document does so anyway, so probably not that big of a change for people // since they are already handlinig this exception when getting the document try { localFieldsStream.Seek(pointer); localFieldsStream.ReadBytes(b, 0, toRead); if (isCompressed) fieldsData = Enclosing_Instance.Uncompress(b); else fieldsData = b; } catch (System.IO.IOException e) { throw new FieldReaderException(e); } binaryOffset = 0; binaryLength = toRead; } return (byte[])fieldsData; } else return null; } } private byte[] Uncompress(byte[] input) { return SupportClass.CompressionSupport.Uncompress(input); } // Instances of this class hold field properties and data // for merge [Serializable] public sealed class FieldForMerge : AbstractField { public override System.String StringValue() { return (System.String)this.fieldsData; } public override System.IO.TextReader ReaderValue() { // not needed for merge return null; } public override byte[] BinaryValue() { return (byte[])this.fieldsData; } public override TokenStream TokenStreamValue() { // not needed for merge return null; } public FieldForMerge(object value_Renamed, FieldInfo fi, bool binary, bool compressed, bool tokenize) { this.isStored = true; this.fieldsData = value_Renamed; this.isCompressed = compressed; this.isBinary = binary; if (isBinary) binaryLength = ((byte[])value_Renamed).Length; this.isTokenized = tokenize; this.name = String.Intern(fi.name); this.isIndexed = fi.isIndexed; this.omitNorms = fi.omitNorms; this.storeOffsetWithTermVector = fi.storeOffsetWithTermVector; this.storePositionWithTermVector = fi.storePositionWithTermVector; this.storeTermVector = fi.storeTermVector; } } } }
/* Copyright (c) 2005-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.Web; using System.Xml; using System.Collections; using System.Configuration; using PHP.Core; using System.Diagnostics; namespace PHP.Library.Zlib { #region Local Configuration /// <summary> /// Script independent Zlib configuration. /// </summary> [Serializable] public sealed class ZlibLocalConfig : IPhpConfiguration, IPhpConfigurationSection { internal ZlibLocalConfig() { } /// <summary> /// Creates a deep copy of the configuration record. /// </summary> /// <returns>The copy.</returns> public IPhpConfiguration DeepCopy() { return (ZlibLocalConfig)this.MemberwiseClone(); } /// <summary> /// Loads configuration from XML. /// </summary> public bool Parse(string name, string value, XmlNode node) { switch (name) { default: return false; } //return true; } } #endregion #region Global Configuration /// <summary> /// Script dependent MSSQL configuration. /// </summary> [Serializable] public sealed class ZlibGlobalConfig : IPhpConfiguration, IPhpConfigurationSection { internal ZlibGlobalConfig() { } /// <summary> /// Loads configuration from XML. /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <param name="node"></param> /// <returns></returns> public bool Parse(string name, string value, XmlNode node) { switch (name) { default: return false; } //return true; } /// <summary> /// Creates a deep copy of the configuration record. /// </summary> /// <returns>The copy.</returns> public IPhpConfiguration DeepCopy() { return (ZlibGlobalConfig)this.MemberwiseClone(); } } #endregion /// <summary> /// Zlib extension configuration. /// </summary> public static class ZlibConfiguration { #region Legacy Configuration /// <summary> /// Gets, sets, or restores a value of a legacy configuration option. /// </summary> private static object GetSetRestore(LocalConfiguration config, string option, object value, IniAction action) { ZlibLocalConfig local = (ZlibLocalConfig)config.GetLibraryConfig(ZlibLibraryDescriptor.Singleton); ZlibLocalConfig @default = DefaultLocal; ZlibGlobalConfig global = Global; switch (option) { //// local: //case "mssql.connect_timeout": //return PhpIni.GSR(ref local.ConnectTimeout, @default.ConnectTimeout, value, action); //case "mssql.timeout": //return PhpIni.GSR(ref local.Timeout, @default.Timeout, value, action); //case "mssql.batchsize": //return PhpIni.GSR(ref local.BatchSize, @default.BatchSize, value, action); // global: case "zlib.output_compression": Debug.Assert(action == IniAction.Get, "Setting zlib.output_compression is not currently implemented."); return false; case "zlib.output_compression_level": Debug.Assert(action == IniAction.Get, "Setting zlib.output_compression_level is not currently implemented."); return -1; case "zlib.output_handler": Debug.Assert(action == IniAction.Get, "Setting zlib.output_handler is not currently implemented."); return ""; } Debug.Fail("Option '" + option + "' is not currently supported."); return null; } /// <summary> /// Writes MySql legacy options and their values to XML text stream. /// Skips options whose values are the same as default values of Phalanger. /// </summary> /// <param name="writer">XML writer.</param> /// <param name="options">A hashtable containing PHP names and option values. Consumed options are removed from the table.</param> /// <param name="writePhpNames">Whether to add "phpName" attribute to option nodes.</param> public static void LegacyOptionsToXml(XmlTextWriter writer, Hashtable options, bool writePhpNames) // GENERICS:<string,string> { if (writer == null) throw new ArgumentNullException("writer"); if (options == null) throw new ArgumentNullException("options"); ZlibLocalConfig local = new ZlibLocalConfig(); ZlibGlobalConfig global = new ZlibGlobalConfig(); PhpIniXmlWriter ow = new PhpIniXmlWriter(writer, options, writePhpNames); ow.StartSection("zlib"); //ow.WriteOption("zlib.output_compression", "OutputCompression", "Off", "Off"); //ow.WriteOption("zlib.output_compression_level", "OutputCompression", -1, -1); //// local: //ow.WriteOption("mssql.connect_timeout", "ConnectTimeout", 5, local.ConnectTimeout); //ow.WriteOption("mssql.timeout", "Timeout", 60, local.Timeout); //ow.WriteOption("mssql.batchsize", "BatchSize", 0, local.BatchSize); //// global: //ow.WriteOption("mssql.max_links", "MaxConnections", -1, global.MaxConnections); //ow.WriteOption("mssql.secure_connection", "NTAuthentication", false, global.NTAuthentication); ow.WriteEnd(); } /// <summary> /// Registers legacy ini-options. /// </summary> internal static void RegisterLegacyOptions() { const string s = ZlibLibraryDescriptor.ExtensionName; GetSetRestoreDelegate d = new GetSetRestoreDelegate(GetSetRestore); IniOptions.Register("zlib.output_compression", IniFlags.Supported | IniFlags.Global, d, s); IniOptions.Register("zlib.output_compression_level", IniFlags.Supported | IniFlags.Global, d, s); IniOptions.Register("zlib.output_handler", IniFlags.Supported | IniFlags.Global, d, s); //// global: //IniOptions.Register("mssql.max_links", IniFlags.Supported | IniFlags.Global, d, s); //IniOptions.Register("mssql.secure_connection", IniFlags.Supported | IniFlags.Global, d, s); //IniOptions.Register("mssql.allow_persistent", IniFlags.Unsupported | IniFlags.Global, d, s); //IniOptions.Register("mssql.max_persistent", IniFlags.Unsupported | IniFlags.Global, d, s); //// local: //IniOptions.Register("mssql.connect_timeout", IniFlags.Supported | IniFlags.Local, d, s); //IniOptions.Register("mssql.timeout", IniFlags.Supported | IniFlags.Local, d, s); //IniOptions.Register("mssql.batchsize", IniFlags.Supported | IniFlags.Local, d, s); //IniOptions.Register("mssql.min_error_severity", IniFlags.Unsupported | IniFlags.Local, d, s); //IniOptions.Register("mssql.min_message_severity", IniFlags.Unsupported | IniFlags.Local, d, s); //IniOptions.Register("mssql.compatability_mode", IniFlags.Unsupported | IniFlags.Local, d, s); //IniOptions.Register("mssql.textsize", IniFlags.Unsupported | IniFlags.Local, d, s); //IniOptions.Register("mssql.textlimit", IniFlags.Unsupported | IniFlags.Local, d, s); //IniOptions.Register("mssql.datetimeconvert", IniFlags.Unsupported | IniFlags.Local, d, s); //IniOptions.Register("mssql.max_procs", IniFlags.Unsupported | IniFlags.Local, d, s); } #endregion #region Configuration Getters /// <summary> /// Gets the library configuration associated with the current script context. /// </summary> public static ZlibLocalConfig Local { get { return (ZlibLocalConfig)Configuration.Local.GetLibraryConfig(ZlibLibraryDescriptor.Singleton); } } /// <summary> /// Gets the default library configuration. /// </summary> public static ZlibLocalConfig DefaultLocal { get { return (ZlibLocalConfig)Configuration.DefaultLocal.GetLibraryConfig(ZlibLibraryDescriptor.Singleton); } } /// <summary> /// Gets the global library configuration. /// </summary> public static ZlibGlobalConfig Global { get { return (ZlibGlobalConfig)Configuration.Global.GetLibraryConfig(ZlibLibraryDescriptor.Singleton); } } /// <summary> /// Gets local configuration associated with a specified script context. /// </summary> /// <param name="context">Scritp context.</param> /// <returns>Local library configuration.</returns> public static ZlibLocalConfig GetLocal(ScriptContext/*!*/ context) { if (context == null) throw new ArgumentNullException("context"); return (ZlibLocalConfig)context.Config.GetLibraryConfig(ZlibLibraryDescriptor.Singleton); } #endregion } }
using Acklann.Semver; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; namespace Acklann.Ncrement { public class Manifest : IManifest { [DataMember(IsRequired = true)] public string Id { get; set; } [DataMember(IsRequired = true)] public string Name { get; set; } public string Description { get; set; } [DataMember(IsRequired = true)] public SemanticVersion Version { get; set; } [IgnoreDataMember] public string VersionFormat { get; set; } public string Company { get; set; } [DataMember(IsRequired = true)] public string Authors { get; set; } public string Copyright { get; set; } public string License { get; set; } public string Website { get; set; } public string Repository { get; set; } public string Icon { get; set; } public string ReleaseNotes { get; set; } public string Tags { get; set; } [DataMember(IsRequired = true)] public Dictionary<string, string> BranchVersionMap { get; set; } public static Manifest CreateTemplate() { return new Manifest() { Copyright = "Copyright {year} {company}, All Rights Reserved.", License = "license.md", Icon = "icon.png", Website = "https://github.com/{company}/{name}", Repository = "https://github.com/{company}/{name}.git", ReleaseNotes = "https://github.com/{company}/{name}/blob/master/changelog.md", BranchVersionMap = new Dictionary<string, string>() { { "master", "C" }, { DEFAULT, "x.y.z-\\beta" } } }; } public static Manifest LoadFrom(string filePath) { if (!File.Exists(filePath)) throw new FileNotFoundException($"Could not find file at '{filePath}'."); using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new StreamReader(file, Encoding.UTF8)) { return ParseJson(reader.ReadToEnd()); } } public static Manifest ParseJson(string text) { if (string.IsNullOrEmpty(text)) throw new ArgumentNullException(nameof(text)); var manifest = new Manifest(); var properties = (from x in typeof(Manifest).GetMembers() where x.MemberType == MemberTypes.Property select (x as PropertyInfo)).ToDictionary(x => x.Name); using (var reader = new JsonTextReader(new StringReader(text))) { string name = null; while (reader.Read()) if (reader.TokenType == JsonToken.PropertyName) { name = ToPascal(Convert.ToString(reader.Value) ?? string.Empty); if (properties.ContainsKey(name)) switch (name) { default: properties[name].SetValue(manifest, reader.ReadAsString()); break; case nameof(Version): int x = 0, y = 0, z = 0; string p = null, b = null; reader.Read(); while (reader.Read() && reader.TokenType == JsonToken.PropertyName) switch (ToPascal(Convert.ToString(reader.Value))) { case nameof(SemanticVersion.Major): x = reader.ReadAsInt32() ?? 0; break; case nameof(SemanticVersion.Minor): y = reader.ReadAsInt32() ?? 0; break; case nameof(SemanticVersion.Patch): z = reader.ReadAsInt32() ?? 0; break; case nameof(SemanticVersion.PreRelease): p = reader.ReadAsString(); break; case nameof(SemanticVersion.Build): b = reader.ReadAsString(); break; } manifest.Version = new SemanticVersion(x, y, z, p, b); break; case nameof(BranchVersionMap): if (manifest.BranchVersionMap == null) manifest.BranchVersionMap = new Dictionary<string, string>(); reader.Read(); while (reader.Read() && reader.TokenType == JsonToken.PropertyName) { manifest.BranchVersionMap.Add(Convert.ToString(reader.Value), reader.ReadAsString()); } break; } } } return manifest; } public void SetVersionFormat(string branchName) { if (string.IsNullOrEmpty(branchName)) throw new ArgumentNullException(nameof(branchName)); if (!string.IsNullOrEmpty(VersionFormat)) return; if (BranchVersionMap == null || BranchVersionMap.Count < 1) return; if (BranchVersionMap.ContainsKey(branchName)) VersionFormat = BranchVersionMap[branchName]; else if (BranchVersionMap.ContainsKey(DEFAULT)) VersionFormat = BranchVersionMap[DEFAULT]; } public void Save(string filePath) { if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException(nameof(filePath)); switch (Path.GetExtension(filePath).ToLowerInvariant()) { default: case ".json": SaveAsJson(filePath); break; case ".xml": throw new System.NotImplementedException(); } } public void SaveAsJson(string filePath) { if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException(nameof(filePath)); string folder = Path.GetDirectoryName(filePath); if (!Directory.Exists(folder)) Directory.CreateDirectory(folder); File.WriteAllText(filePath, JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore })); } #region Backing Mebers private const string DEFAULT = "default"; private static string ToPascal(string text) { if (string.IsNullOrEmpty(text)) return text; else if (text.Length == 1) return text.ToUpperInvariant(); else { var pascal = new System.Text.StringBuilder(); ReadOnlySpan<char> span = text.AsSpan(); for (int i = 0; i < span.Length; i++) { if (span[i] == ' ' || span[i] == '_') continue; else if (i == 0) pascal.Append(char.ToUpperInvariant(span[i])); else if (span[i - 1] == ' ' || span[i - 1] == '_') pascal.Append(char.ToUpperInvariant(span[i])); else pascal.Append(span[i]); } return pascal.ToString(); } } #endregion Backing Mebers } }
using System; using System.Diagnostics; using System.Collections; namespace BplusDotNet { /// <summary> /// Chunked singly linked file with garbage collection. /// </summary> public class LinkedFile { const long NULLBUFFERPOINTER = -1; System.IO.Stream fromfile; BufferFile buffers; int buffersize; int headersize; long seekStart = 0; long FreeListHead = NULLBUFFERPOINTER; long RecentNewBufferNumber = NULLBUFFERPOINTER; bool headerDirty = true; byte FREE = 0; byte HEAD = 1; byte BODY = 2; public static byte[] HEADERPREFIX = { 98, 112, 78, 108, 102 }; public static byte VERSION = 0; public static int MINBUFFERSIZE = 20; // next pointer and indicator flag public static int BUFFEROVERHEAD = BufferFile.Longstorage + 1; public LinkedFile(int buffersize, long seekStart) { this.seekStart = seekStart; //this.buffers = buffers; this.buffersize = buffersize; // markers+version byte+buffersize+freelisthead this.headersize = HEADERPREFIX.Length + 1 + BufferFile.Intstorage + BufferFile.Longstorage; this.sanityCheck(); } public static LinkedFile SetupFromExistingStream(System.IO.Stream fromfile) { return SetupFromExistingStream(fromfile, (long)0); } public static LinkedFile SetupFromExistingStream(System.IO.Stream fromfile, long StartSeek) { LinkedFile result = new LinkedFile(100, StartSeek); // dummy buffer size for now result.fromfile = fromfile; result.readHeader(); result.buffers = BufferFile.SetupFromExistingStream(fromfile, StartSeek+result.headersize); return result; } void readHeader() { byte[] header = new byte[this.headersize]; this.fromfile.Seek(this.seekStart, System.IO.SeekOrigin.Begin); this.fromfile.Read(header, 0, this.headersize); int index = 0; // check prefix foreach (byte b in HEADERPREFIX) { if (header[index]!=b) { throw new LinkedFileException("invalid header prefix"); } index++; } // skip version (for now) index++; // read buffersize this.buffersize = BufferFile.Retrieve(header, index); index += BufferFile.Intstorage; this.FreeListHead = BufferFile.RetrieveLong(header, index); this.sanityCheck(); this.headerDirty = false; } public static LinkedFile InitializeLinkedFileInStream(System.IO.Stream fromfile, int buffersize) { return InitializeLinkedFileInStream(fromfile, buffersize, (long)0); } public static LinkedFile InitializeLinkedFileInStream(System.IO.Stream fromfile, int buffersize, long StartSeek) { LinkedFile result = new LinkedFile(buffersize, StartSeek); result.fromfile = fromfile; result.setHeader(); // buffersize should be increased by overhead... result.buffers = BufferFile.InitializeBufferFileInStream(fromfile, buffersize+BUFFEROVERHEAD, StartSeek+result.headersize); return result; } public void setHeader() { byte[] header = this.makeHeader(); this.fromfile.Seek(this.seekStart, System.IO.SeekOrigin.Begin); this.fromfile.Write(header, 0, header.Length); this.headerDirty = false; } public byte[] makeHeader() { byte[] result = new byte[this.headersize]; HEADERPREFIX.CopyTo(result, 0); result[HEADERPREFIX.Length] = VERSION; int index = HEADERPREFIX.Length+1; BufferFile.Store(this.buffersize, result, index); index += BufferFile.Intstorage; BufferFile.Store(this.FreeListHead, result, index); return result; } public void Recover(Hashtable ChunksInUse, bool FixErrors) { // find missing space and recover it this.checkStructure(ChunksInUse, FixErrors); } void sanityCheck() { if (this.seekStart<0) { throw new LinkedFileException("cannot seek negative "+this.seekStart); } if (this.buffersize<MINBUFFERSIZE) { throw new LinkedFileException("buffer size too small "+this.buffersize); } } public void Shutdown() { this.fromfile.Flush(); this.fromfile.Close(); } byte[] ParseBuffer(long bufferNumber, out byte type, out long nextBufferNumber) { byte[] thebuffer = new byte[this.buffersize]; byte[] fullbuffer = new byte[this.buffersize+BUFFEROVERHEAD]; this.buffers.GetBuffer(bufferNumber, fullbuffer, 0, fullbuffer.Length); type = fullbuffer[0]; nextBufferNumber = BufferFile.RetrieveLong(fullbuffer, 1); Array.Copy(fullbuffer, BUFFEROVERHEAD, thebuffer, 0, this.buffersize); return thebuffer; } void SetBuffer(long buffernumber, byte type, byte[] thebuffer, int start, int length, long NextBufferNumber) { //System.Diagnostics.Debug.WriteLine(" storing chunk type "+type+" at "+buffernumber); if (this.buffersize<length) { throw new LinkedFileException("buffer size too small "+this.buffersize+"<"+length); } byte[] fullbuffer = new byte[length+BUFFEROVERHEAD]; fullbuffer[0] = type; BufferFile.Store(NextBufferNumber, fullbuffer, 1); if (thebuffer!=null) { Array.Copy(thebuffer, start, fullbuffer, BUFFEROVERHEAD, length); } this.buffers.SetBuffer(buffernumber, fullbuffer, 0, fullbuffer.Length); } void DeallocateBuffer(long buffernumber) { //System.Diagnostics.Debug.WriteLine(" deallocating "+buffernumber); // should be followed by resetting the header eventually. this.SetBuffer(buffernumber, FREE, null, 0, 0, this.FreeListHead); this.FreeListHead = buffernumber; this.headerDirty = true; } long AllocateBuffer() { if (this.FreeListHead!=NULLBUFFERPOINTER) { // reallocate a freed buffer long result = this.FreeListHead; byte buffertype; long NextFree; byte[] dummy = this.ParseBuffer(result, out buffertype, out NextFree); if (buffertype!=FREE) { throw new LinkedFileException("free head buffer not marked free"); } this.FreeListHead = NextFree; this.headerDirty = true; this.RecentNewBufferNumber = NULLBUFFERPOINTER; return result; } else { // allocate a new buffer long nextbuffernumber = this.buffers.NextBufferNumber(); if (this.RecentNewBufferNumber==nextbuffernumber) { // the previous buffer has been allocated but not yet written. It must be written before the following one... nextbuffernumber++; } this.RecentNewBufferNumber = nextbuffernumber; return nextbuffernumber; } } public void checkStructure() { checkStructure(null, false); } public void checkStructure(Hashtable ChunksInUse, bool FixErrors) { Hashtable buffernumberToType = new Hashtable(); Hashtable buffernumberToNext = new Hashtable(); Hashtable visited = new Hashtable(); long LastBufferNumber = this.buffers.NextBufferNumber(); for (long buffernumber=0; buffernumber<LastBufferNumber; buffernumber++) { byte buffertype; long nextBufferNumber; this.ParseBuffer(buffernumber, out buffertype, out nextBufferNumber); buffernumberToType[buffernumber] = buffertype; buffernumberToNext[buffernumber] = nextBufferNumber; } // traverse the freelist long thisFreeBuffer = this.FreeListHead; while (thisFreeBuffer!=NULLBUFFERPOINTER) { if (visited.ContainsKey(thisFreeBuffer)) { throw new LinkedFileException("cycle in freelist "+thisFreeBuffer); } visited[thisFreeBuffer] = thisFreeBuffer; byte thetype = (byte) buffernumberToType[thisFreeBuffer]; long nextbuffernumber = (long) buffernumberToNext[thisFreeBuffer]; if (thetype!=FREE) { throw new LinkedFileException("free list element not marked free "+thisFreeBuffer); } thisFreeBuffer = nextbuffernumber; } // traverse all nodes marked head Hashtable allchunks = new Hashtable(); for (long buffernumber=0; buffernumber<LastBufferNumber; buffernumber++) { byte thetype = (byte) buffernumberToType[buffernumber]; if (thetype==HEAD) { if (visited.ContainsKey(buffernumber)) { throw new LinkedFileException("head buffer already visited "+buffernumber); } allchunks[buffernumber] = buffernumber; visited[buffernumber] = buffernumber; long bodybuffernumber = (long) buffernumberToNext[buffernumber]; while (bodybuffernumber!=NULLBUFFERPOINTER) { byte bodytype = (byte) buffernumberToType[bodybuffernumber]; long nextbuffernumber = (long) buffernumberToNext[bodybuffernumber]; if (visited.ContainsKey(bodybuffernumber)) { throw new LinkedFileException("body buffer visited twice "+bodybuffernumber); } visited[bodybuffernumber] = bodytype; if (bodytype!=BODY) { throw new LinkedFileException("body buffer not marked body "+thetype); } bodybuffernumber = nextbuffernumber; } // check retrieval this.GetChunk(buffernumber); } } // make sure all were visited for (long buffernumber=0; buffernumber<LastBufferNumber; buffernumber++) { if (!visited.ContainsKey(buffernumber)) { throw new LinkedFileException("buffer not found either as data or free "+buffernumber); } } // check against in use list if (ChunksInUse!=null) { ArrayList notInUse = new ArrayList(); foreach (DictionaryEntry d in ChunksInUse) { long buffernumber = (long)d.Key; if (!allchunks.ContainsKey(buffernumber)) { //System.Diagnostics.Debug.WriteLine("\r\n<br>allocated chunks "+allchunks.Count); //foreach (DictionaryEntry d1 in allchunks) //{ // System.Diagnostics.Debug.WriteLine("\r\n<br>found "+d1.Key); //} throw new LinkedFileException("buffer in used list not found in linked file "+buffernumber+" "+d.Value); } } foreach (DictionaryEntry d in allchunks) { long buffernumber = (long)d.Key; if (!ChunksInUse.ContainsKey(buffernumber)) { if (!FixErrors) { throw new LinkedFileException("buffer in linked file not in used list "+buffernumber); } notInUse.Add(buffernumber); } } notInUse.Sort(); notInUse.Reverse(); foreach (object thing in notInUse) { long buffernumber = (long)thing; this.ReleaseBuffers(buffernumber); } } } public byte[] GetChunk(long HeadBufferNumber) { // get the head, interpret the length byte buffertype; long nextBufferNumber; byte[] buffer = this.ParseBuffer(HeadBufferNumber, out buffertype, out nextBufferNumber); int length = BufferFile.Retrieve(buffer, 0); if (length<0) { throw new LinkedFileException("negative length block? must be garbage: "+length); } if (buffertype!=HEAD) { throw new LinkedFileException("first buffer not marked HEAD"); } byte[] result = new byte[length]; // read in the data from the first buffer int firstLength = this.buffersize-BufferFile.Intstorage; if (firstLength>length) { firstLength = length; } Array.Copy(buffer, BufferFile.Intstorage, result, 0, firstLength); int stored = firstLength; while (stored<length) { // get the next buffer long thisBufferNumber = nextBufferNumber; buffer = this.ParseBuffer(thisBufferNumber, out buffertype, out nextBufferNumber); int nextLength = this.buffersize; if (length-stored<nextLength) { nextLength = length-stored; } Array.Copy(buffer, 0, result, stored, nextLength); stored += nextLength; } return result; } public long StoreNewChunk(byte[] fromArray, int startingAt, int length) { // get the first buffer as result value long currentBufferNumber = this.AllocateBuffer(); //System.Diagnostics.Debug.WriteLine(" allocating chunk starting at "+currentBufferNumber); long result = currentBufferNumber; if (length<0 || startingAt<0) { throw new LinkedFileException("cannot store negative length chunk ("+startingAt+","+length+")"); } int endingAt = startingAt+length; // special case: zero length chunk if (endingAt>fromArray.Length) { throw new LinkedFileException("array doesn't have this much data: "+endingAt); } int index = startingAt; // store header with length information byte[] buffer = new byte[this.buffersize]; BufferFile.Store(length, buffer, 0); int fromIndex = startingAt; int firstLength = this.buffersize-BufferFile.Intstorage; int stored = 0; if (firstLength>length) { firstLength=length; } Array.Copy(fromArray, fromIndex, buffer, BufferFile.Intstorage, firstLength); stored += firstLength; fromIndex += firstLength; byte CurrentBufferType = HEAD; // store any remaining buffers (no length info) while (stored<length) { // store current buffer and get next block number long nextBufferNumber = this.AllocateBuffer(); this.SetBuffer(currentBufferNumber, CurrentBufferType, buffer, 0, buffer.Length, nextBufferNumber); currentBufferNumber = nextBufferNumber; CurrentBufferType = BODY; int nextLength = this.buffersize; if (stored+nextLength>length) { nextLength = length-stored; } Array.Copy(fromArray, fromIndex, buffer, 0, nextLength); stored += nextLength; fromIndex += nextLength; } // store final buffer this.SetBuffer(currentBufferNumber, CurrentBufferType, buffer, 0, buffer.Length, NULLBUFFERPOINTER); return result; } public void Flush() { if (this.headerDirty) { this.setHeader(); } this.buffers.Flush(); } public void ReleaseBuffers(long HeadBufferNumber) { // KISS //System.Diagnostics.Debug.WriteLine(" deallocating chunk starting at "+HeadBufferNumber); long thisbuffernumber = HeadBufferNumber; long nextbuffernumber; byte buffertype; byte[] dummy = this.ParseBuffer(HeadBufferNumber, out buffertype, out nextbuffernumber); if (buffertype!=HEAD) { throw new LinkedFileException("head buffer not marked HEAD"); } this.DeallocateBuffer(HeadBufferNumber); while (nextbuffernumber!=NULLBUFFERPOINTER) { thisbuffernumber = nextbuffernumber; dummy = this.ParseBuffer(thisbuffernumber, out buffertype, out nextbuffernumber); if (buffertype!=BODY) { throw new LinkedFileException("body buffer not marked BODY"); } this.DeallocateBuffer(thisbuffernumber); } } } public class LinkedFileException: ApplicationException { public LinkedFileException(string message): base(message) { // do nothing extra } } }
namespace Nancy.Owin.Tests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using FakeItEasy; using Nancy.Bootstrapper; using Nancy.Helpers; using Nancy.Tests; using Xunit; using AppFunc = System.Func< System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>; using MidFunc = System.Func< System.Func< System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>, System.Func< System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>>; public class NancyMiddlewareFixture { private readonly Dictionary<string, object> environment; private readonly INancyBootstrapper fakeBootstrapper; private readonly INancyEngine fakeEngine; private readonly AppFunc host; public NancyMiddlewareFixture() { this.fakeEngine = A.Fake<INancyEngine>(); this.fakeBootstrapper = A.Fake<INancyBootstrapper>(); A.CallTo(() => this.fakeBootstrapper.GetEngine()).Returns(this.fakeEngine); this.host = NancyMiddleware.UseNancy(new NancyOptions {Bootstrapper = this.fakeBootstrapper})(null); this.environment = new Dictionary<string, object> { {"owin.RequestMethod", "GET"}, {"owin.RequestPath", "/test"}, {"owin.RequestPathBase", "/root"}, {"owin.RequestQueryString", "var=value"}, {"owin.RequestBody", Stream.Null}, {"owin.RequestHeaders", new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)}, {"owin.RequestScheme", "http"}, {"owin.ResponseHeaders", new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)}, {"owin.ResponseBody", new MemoryStream()}, {"owin.ResponseReasonPhrase", string.Empty}, {"owin.Version", "1.0"}, {"owin.CallCancelled", CancellationToken.None} }; } [Fact] public void Should_immediately_invoke_nancy_if_no_request_body_delegate() { // Given var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { } }; var fakeContext = new NancyContext { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host(this.environment); // Then A.CallTo(() => this.fakeEngine.HandleRequest( A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, (CancellationToken)this.environment["owin.CallCancelled"])) .MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_set_return_code_in_response_callback() { // Given var fakeResponse = new Response {StatusCode = HttpStatusCode.OK, Contents = s => { }}; var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment); // Then ((int)this.environment["owin.ResponseStatusCode"]).ShouldEqual(200); } [Fact] public void Should_set_headers_in_response_callback() { // Given var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Headers = new Dictionary<string, string> {{"TestHeader", "TestValue"}}, Contents = s => { } }; var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment); var headers = (IDictionary<string, string[]>)this.environment["owin.ResponseHeaders"]; // Then // 2 headers because the default content-type is text/html headers.Count.ShouldEqual(2); headers["Content-Type"][0].ShouldEqual("text/html"); headers["TestHeader"][0].ShouldEqual("TestValue"); } [Fact] public void Should_send_entire_body() { // Given var data1 = Encoding.ASCII.GetBytes("Some content"); var data2 = Encoding.ASCII.GetBytes("Some more content"); var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, Contents = s => { s.Write(data1, 0, data1.Length); s.Write(data2, 0, data2.Length); } }; var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment); var data = ((MemoryStream)this.environment["owin.ResponseBody"]).ToArray(); // Then data.ShouldEqualSequence(data1.Concat(data2)); } [Fact] public void Should_dispose_context_on_completion_of_body_delegate() { // Given var data1 = Encoding.ASCII.GetBytes("Some content"); var fakeResponse = new Response {StatusCode = HttpStatusCode.OK, Contents = s => s.Write(data1, 0, data1.Length)}; var fakeContext = new NancyContext {Response = fakeResponse}; var mockDisposable = A.Fake<IDisposable>(); fakeContext.Items.Add("Test", mockDisposable); this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(environment); // Then A.CallTo(() => mockDisposable.Dispose()).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_set_cookie_with_valid_header() { // Given var fakeResponse = new Response {StatusCode = HttpStatusCode.OK}; fakeResponse.WithCookie("test", "testvalue"); fakeResponse.WithCookie("test1", "testvalue1"); var fakeContext = new NancyContext {Response = fakeResponse}; this.SetupFakeNancyCompleteCallback(fakeContext); // When this.host.Invoke(this.environment).Wait(); var respHeaders = Get<IDictionary<string, string[]>>(this.environment, "owin.ResponseHeaders"); // Then respHeaders.ContainsKey("Set-Cookie").ShouldBeTrue(); (respHeaders["Set-Cookie"][0] == "test=testvalue; path=/").ShouldBeTrue(); (respHeaders["Set-Cookie"][1] == "test1=testvalue1; path=/").ShouldBeTrue(); } [Fact] public void Should_append_setcookie_headers() { //Given var respHeaders = Get<IDictionary<string, string[]>>(this.environment, "owin.ResponseHeaders"); const string middlewareSetCookie = "other=othervalue; path=/"; respHeaders.Add("Set-Cookie", new[] { middlewareSetCookie }); var fakeResponse = new Response { StatusCode = HttpStatusCode.OK }; fakeResponse.WithCookie("test", "testvalue"); var fakeContext = new NancyContext { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); //When this.host.Invoke(this.environment).Wait(); //Then respHeaders["Set-Cookie"].Length.ShouldEqual(2); (respHeaders["Set-Cookie"][0] == middlewareSetCookie).ShouldBeTrue(); (respHeaders["Set-Cookie"][1] == "test=testvalue; path=/").ShouldBeTrue(); } /// <summary> /// Sets the fake nancy engine to execute the complete callback with the given context /// </summary> /// <param name="context">Context to return</param> private void SetupFakeNancyCompleteCallback(NancyContext context) { A.CallTo(() => this.fakeEngine.HandleRequest( A<Request>.Ignored, A<Func<NancyContext, NancyContext>>.Ignored, A<CancellationToken>.Ignored)) .Returns(TaskHelpers.GetCompletedTask(context)); } private static T Get<T>(IDictionary<string, object> env, string key) { object value; return env.TryGetValue(key, out value) && value is T ? (T)value : default(T); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Pathfinding.RVO; namespace Pathfinding { [RequireComponent(typeof(Seeker))] [AddComponentMenu("Pathfinding/AI/RichAI (3D, for navmesh)")] /** Advanced AI for navmesh based graphs. * \astarpro */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_rich_a_i.php")] public class RichAI : MonoBehaviour { public Transform target; /** Draw gizmos in the scene view */ public bool drawGizmos = true; /** Search for new paths repeatedly */ public bool repeatedlySearchPaths = false; /** Delay (seconds) between path searches */ public float repathRate = 0.5f; /** Max speed of the agent. * World units per second */ public float maxSpeed = 1; /** Max acceleration of the agent. * World units per second per second */ public float acceleration = 5; /** How much time to use for slowdown in the end of the path. * A lower value give more abrupt stops */ public float slowdownTime = 0.5f; /** Max rotation speed of the agent. * In degrees per second. */ public float rotationSpeed = 360; /** Max distance to the endpoint to consider it reached */ public float endReachedDistance = 0.01f; /** Force to avoid walls with. * The agent will try to steer away from walls slightly. */ public float wallForce = 3; /** Walls within this range will be used for avoidance. * Setting this to zero disables wall avoidance and may improve performance slightly */ public float wallDist = 1; /** Gravity to use in case no character controller is attached */ public Vector3 gravity = new Vector3(0, -9.82f, 0); /** Raycast for ground placement (when not having a CharacterController). * A raycast from position + up*#centerOffset downwards will be done and the agent will be placed at this point. */ public bool raycastingForGroundPlacement = true; /** Layer mask to use for ground placement. * Make sure this does not include the layer of any eventual colliders attached to this gameobject. */ public LayerMask groundMask = -1; public float centerOffset = 1; /** Mode for funnel simplification. * On tiled navmesh maps, but sometimes on normal ones as well, it can be good to simplify * the funnel as a post-processing step. */ public RichFunnel.FunnelSimplification funnelSimplification = RichFunnel.FunnelSimplification.None; public Animation anim; /** Use a 3rd degree equation for calculating slowdown acceleration instead of a 2nd degree. * A 3rd degree equation can also make sure that the velocity when reaching the target is roughly zero and therefore * it will have a more direct stop. In contrast solving a 2nd degree equation which will just make sure the target is reached but * will usually have a larger velocity when reaching the target and therefore look more "bouncy". */ public bool preciseSlowdown = true; /** Slow down when not facing the target direction. * Incurs at a small overhead. */ public bool slowWhenNotFacingTarget = true; /** Current velocity of the agent. * Includes eventual velocity due to gravity */ Vector3 velocity; /** Current velocity of the agent. * Includes eventual velocity due to gravity */ public Vector3 Velocity { get { return velocity; } } protected RichPath rp; protected Seeker seeker; protected Transform tr; CharacterController controller; RVOController rvoController; Vector3 lastTargetPoint; Vector3 currentTargetDirection; protected bool waitingForPathCalc; protected bool canSearchPath; protected bool delayUpdatePath; protected bool traversingSpecialPath; protected bool lastCorner; float distanceToWaypoint = 999; protected List<Vector3> buffer = new List<Vector3>(); protected List<Vector3> wallBuffer = new List<Vector3>(); bool startHasRun; protected float lastRepath = -9999; void Awake () { seeker = GetComponent<Seeker>(); controller = GetComponent<CharacterController>(); rvoController = GetComponent<RVOController>(); if (rvoController != null) rvoController.enableRotation = false; tr = transform; } /** Starts searching for paths. * If you override this function you should in most cases call base.Start () at the start of it. * \see OnEnable * \see SearchPaths */ protected virtual void Start () { startHasRun = true; OnEnable(); } /** Run at start and when reenabled. * Starts RepeatTrySearchPath. * * \see Start */ protected virtual void OnEnable () { lastRepath = -9999; waitingForPathCalc = false; canSearchPath = true; if (startHasRun) { //Make sure we receive callbacks when paths complete seeker.pathCallback += OnPathComplete; StartCoroutine(SearchPaths()); } } public void OnDisable () { // Abort calculation of path if (seeker != null && !seeker.IsDone()) seeker.GetCurrentPath().Error(); //Make sure we receive callbacks when paths complete seeker.pathCallback -= OnPathComplete; } /** Force recalculation of the current path. * If there is an ongoing path calculation, it will be canceled (so make sure you leave time for the paths to get calculated before calling this function again). */ public virtual void UpdatePath () { canSearchPath = true; waitingForPathCalc = false; Path p = seeker.GetCurrentPath(); //Cancel any eventual pending pathfinding request if (p != null && !seeker.IsDone()) { p.Error(); // Make sure it is recycled. We won't receive a callback for this one since we // replace the path directly after this p.Claim(this); p.Release(this); } waitingForPathCalc = true; lastRepath = Time.time; seeker.StartPath(tr.position, target.position); } IEnumerator SearchPaths () { while (true) { while (!repeatedlySearchPaths || waitingForPathCalc || !canSearchPath || Time.time - lastRepath < repathRate) yield return null; //canSearchPath = false; //waitingForPathCalc = true; //lastRepath = Time.time; //seeker.StartPath (tr.position, target.position); UpdatePath(); yield return null; } } void OnPathComplete (Path p) { waitingForPathCalc = false; p.Claim(this); if (p.error) { p.Release(this); return; } if (traversingSpecialPath) { delayUpdatePath = true; } else { if (rp == null) rp = new RichPath(); rp.Initialize(seeker, p, true, funnelSimplification); } p.Release(this); } public bool TraversingSpecial { get { return traversingSpecialPath; } } /** Current target point. */ public Vector3 TargetPoint { get { return lastTargetPoint; } } /** True if approaching the last waypoint in the current path */ public bool ApproachingPartEndpoint { get { return lastCorner; } } /** True if approaching the last waypoint of all parts in the current path */ public bool ApproachingPathEndpoint { get { return rp != null && ApproachingPartEndpoint && !rp.PartsLeft(); } } /** Distance to the next waypoint */ public float DistanceToNextWaypoint { get { return distanceToWaypoint; } } /** Declare that the AI has completely traversed the current part. * This will skip to the next part, or call OnTargetReached if this was the last part */ void NextPart () { rp.NextPart(); lastCorner = false; if (!rp.PartsLeft()) { //End OnTargetReached(); } } /** Smooth delta time to avoid getting overly affected by e.g GC */ static float deltaTime; /** Called when the end of the path is reached */ protected virtual void OnTargetReached () { } protected virtual Vector3 UpdateTarget (RichFunnel fn) { buffer.Clear(); /* Current position. We read and write to tr.position as few times as possible since doing so * is much slower than to read and write from/to a local variable */ Vector3 position = tr.position; bool requiresRepath; position = fn.Update(position, buffer, 2, out lastCorner, out requiresRepath); if (requiresRepath && !waitingForPathCalc) { UpdatePath(); } return position; } /** Update is called once per frame */ protected virtual void Update () { deltaTime = Mathf.Min(Time.smoothDeltaTime*2, Time.deltaTime); if (rp != null) { //System.Diagnostics.Stopwatch w = new System.Diagnostics.Stopwatch(); //w.Start(); RichPathPart pt = rp.GetCurrentPart(); var fn = pt as RichFunnel; if (fn != null) { //Clear buffers for reuse Vector3 position = UpdateTarget(fn); //tr.position = ps; //Only get walls every 5th frame to save on performance if (Time.frameCount % 5 == 0 && wallForce > 0 && wallDist > 0) { wallBuffer.Clear(); fn.FindWalls(wallBuffer, wallDist); } /*for (int i=0;i<wallBuffer.Count;i+=2) { * Debug.DrawLine (wallBuffer[i],wallBuffer[i+1],Color.magenta); * }*/ //Pick next waypoint if current is reached int tgIndex = 0; /*if (buffer.Count > 1) { * if ((buffer[tgIndex]-tr.position).sqrMagnitude < pickNextWaypointDist*pickNextWaypointDist) { * tgIndex++; * } * }*/ //Target point Vector3 tg = buffer[tgIndex]; Vector3 dir = tg-position; dir.y = 0; bool passedTarget = Vector3.Dot(dir, currentTargetDirection) < 0; //Check if passed target in another way if (passedTarget && buffer.Count-tgIndex > 1) { tgIndex++; tg = buffer[tgIndex]; } if (tg != lastTargetPoint) { currentTargetDirection = (tg - position); currentTargetDirection.y = 0; currentTargetDirection.Normalize(); lastTargetPoint = tg; //Debug.DrawRay (tr.position, Vector3.down*2,Color.blue,0.2f); } //Direction to target dir = (tg-position); dir.y = 0; float magn = dir.magnitude; //Write out for other scripts to read distanceToWaypoint = magn; //Normalize dir = magn == 0 ? Vector3.zero : dir/magn; Vector3 normdir = dir; Vector3 force = Vector3.zero; if (wallForce > 0 && wallDist > 0) { float wLeft = 0; float wRight = 0; for (int i = 0; i < wallBuffer.Count; i += 2) { Vector3 closest = VectorMath.ClosestPointOnSegment(wallBuffer[i], wallBuffer[i+1], tr.position); float dist = (closest-position).sqrMagnitude; if (dist > wallDist*wallDist) continue; Vector3 tang = (wallBuffer[i+1]-wallBuffer[i]).normalized; //Using the fact that all walls are laid out clockwise (seeing from inside) //Then left and right (ish) can be figured out like this float dot = Vector3.Dot(dir, tang) * (1 - System.Math.Max(0, (2*(dist / (wallDist*wallDist))-1))); if (dot > 0) wRight = System.Math.Max(wRight, dot); else wLeft = System.Math.Max(wLeft, -dot); } Vector3 norm = Vector3.Cross(Vector3.up, dir); force = norm*(wRight-wLeft); //Debug.DrawRay (tr.position, force, Color.cyan); } //Is the endpoint of the path (part) the current target point bool endPointIsTarget = lastCorner && buffer.Count-tgIndex == 1; if (endPointIsTarget) { //Use 2nd or 3rd degree motion equation to figure out acceleration to reach target in "exact" [slowdownTime] seconds //Clamp to avoid divide by zero if (slowdownTime < 0.001f) { slowdownTime = 0.001f; } Vector3 diff = tg - position; diff.y = 0; if (preciseSlowdown) { //{ t = slowdownTime //{ diff = vt + at^2/2 + qt^3/6 //{ 0 = at + qt^2/2 //{ solve for a dir = (6*diff - 4*slowdownTime*velocity)/(slowdownTime*slowdownTime); } else { dir = 2*(diff - slowdownTime*velocity)/(slowdownTime*slowdownTime); } dir = Vector3.ClampMagnitude(dir, acceleration); force *= System.Math.Min(magn/0.5f, 1); if (magn < endReachedDistance) { //END REACHED NextPart(); } } else { dir *= acceleration; } //Debug.DrawRay (tr.position+Vector3.up, dir*3, Color.blue); velocity += (dir + force*wallForce)*deltaTime; if (slowWhenNotFacingTarget) { float dot = (Vector3.Dot(normdir, tr.forward)+0.5f)*(1.0f/1.5f); //velocity = Vector3.ClampMagnitude (velocity, maxSpeed * Mathf.Max (dot, 0.2f) ); float xzmagn = Mathf.Sqrt(velocity.x*velocity.x + velocity.z*velocity.z); float prevy = velocity.y; velocity.y = 0; float mg = Mathf.Min(xzmagn, maxSpeed * Mathf.Max(dot, 0.2f)); velocity = Vector3.Lerp(tr.forward * mg, velocity.normalized * mg, Mathf.Clamp(endPointIsTarget ? (magn*2) : 0, 0.5f, 1.0f)); velocity.y = prevy; } else { // Clamp magnitude on the XZ axes float xzmagn = Mathf.Sqrt(velocity.x*velocity.x + velocity.z*velocity.z); xzmagn = maxSpeed/xzmagn; if (xzmagn < 1) { velocity.x *= xzmagn; velocity.z *= xzmagn; //Vector3.ClampMagnitude (velocity, maxSpeed); } } //Debug.DrawLine (tr.position, tg, lastCorner ? Color.red : Color.green); if (endPointIsTarget) { Vector3 trotdir = Vector3.Lerp(velocity, currentTargetDirection, System.Math.Max(1 - magn*2, 0)); RotateTowards(trotdir); } else { RotateTowards(velocity); } //Applied after rotation to enable proper checks on if velocity is zero velocity += deltaTime * gravity; if (rvoController != null && rvoController.enabled) { //Use RVOController tr.position = position; rvoController.Move(velocity); } else if (controller != null && controller.enabled) { //Use CharacterController tr.position = position; controller.Move(velocity * deltaTime); } else { //Use Transform float lasty = position.y; position += velocity*deltaTime; position = RaycastPosition(position, lasty); tr.position = position; } } else { if (rvoController != null && rvoController.enabled) { //Use RVOController rvoController.Move(Vector3.zero); } } if (pt is RichSpecial) { if (!traversingSpecialPath) { StartCoroutine(TraverseSpecial(pt as RichSpecial)); } } //w.Stop(); //Debug.Log ((w.Elapsed.TotalMilliseconds*1000)); } else { if (rvoController != null && rvoController.enabled) { //Use RVOController rvoController.Move(Vector3.zero); } else if (controller != null && controller.enabled) { } else { tr.position = RaycastPosition(tr.position, tr.position.y); } } } Vector3 RaycastPosition (Vector3 position, float lasty) { if (raycastingForGroundPlacement) { RaycastHit hit; float up = Mathf.Max(centerOffset, lasty-position.y+centerOffset); if (Physics.Raycast(position+Vector3.up*up, Vector3.down, out hit, up, groundMask)) { //Debug.DrawRay (tr.position+Vector3.up*centerOffset,Vector3.down*centerOffset, Color.red); if (hit.distance < up) { //grounded position = hit.point;//.up * -(hit.distance-centerOffset); velocity.y = 0; } } } return position; } /** Rotates along the Y-axis the transform towards \a trotdir */ bool RotateTowards (Vector3 trotdir) { trotdir.y = 0; if (trotdir != Vector3.zero) { Quaternion rot = tr.rotation; Vector3 trot = Quaternion.LookRotation(trotdir).eulerAngles; Vector3 eul = rot.eulerAngles; eul.y = Mathf.MoveTowardsAngle(eul.y, trot.y, rotationSpeed*deltaTime); tr.rotation = Quaternion.Euler(eul); //Magic number, should expose as variable return Mathf.Abs(eul.y-trot.y) < 5f; } return false; } public static readonly Color GizmoColorRaycast = new Color(118.0f/255, 206.0f/255, 112.0f/255); public static readonly Color GizmoColorPath = new Color(8.0f/255, 78.0f/255, 194.0f/255); public void OnDrawGizmos () { if (drawGizmos) { if (raycastingForGroundPlacement) { Gizmos.color = GizmoColorRaycast; Gizmos.DrawLine(transform.position, transform.position+Vector3.up*centerOffset); Gizmos.DrawLine(transform.position + Vector3.left*0.1f, transform.position + Vector3.right*0.1f); Gizmos.DrawLine(transform.position + Vector3.back*0.1f, transform.position + Vector3.forward*0.1f); } if (tr != null && buffer != null) { Gizmos.color = GizmoColorPath; Vector3 p = tr.position; for (int i = 0; i < buffer.Count; p = buffer[i], i++) { Gizmos.DrawLine(p, buffer[i]); } } } } IEnumerator TraverseSpecial (RichSpecial rs) { traversingSpecialPath = true; velocity = Vector3.zero; var al = rs.nodeLink as AnimationLink; if (al == null) { Debug.LogError("Unhandled RichSpecial"); yield break; } //Rotate character to face the correct direction while (!RotateTowards(rs.first.forward)) yield return null; //Reposition tr.parent.position = tr.position; tr.parent.rotation = tr.rotation; tr.localPosition = Vector3.zero; tr.localRotation = Quaternion.identity; //Set up animation speeds if (rs.reverse && al.reverseAnim) { anim[al.clip].speed = -al.animSpeed; anim[al.clip].normalizedTime = 1; anim.Play(al.clip); anim.Sample(); } else { anim[al.clip].speed = al.animSpeed; anim.Rewind(al.clip); anim.Play(al.clip); } //Fix required for animations in reverse direction tr.parent.position -= tr.position-tr.parent.position; //Wait for the animation to finish yield return new WaitForSeconds(Mathf.Abs(anim[al.clip].length/al.animSpeed)); traversingSpecialPath = false; NextPart(); //If a path completed during the time we traversed the special connection, we need to recalculate it if (delayUpdatePath) { delayUpdatePath = false; UpdatePath(); } } } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.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. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Editor.Timeline { using System; using Gtk; using Cairo; using Gdv; using TimeSpan = Gdv.TimeSpan; public class ClipTrueElement : ClipElement, ILeftAdjustable, IRightAdjustable { // Fields ////////////////////////////////////////////////////// Clip clip; // Clip we're representing Time leftCut; Time rightCut; bool leftCutValid; bool rightCutValid; bool positionValid; bool trackValid; // Properties ////////////////////////////////////////////////// public override Time CurrentPosition { get { return base.CurrentPosition; } set { TimeSpan testSpan = timeSpan; TimeSpan outSpan = timeSpan; testSpan.MoveTo (value); if (! modelRoot.Tracks.IsSpanEmptyExcluding (track, testSpan, clip)) { if (modelRoot.Tracks.SuggestPositionExcluding (track, testSpan, ref outSpan, modelRoot.Timeline.MouseOverTime, clip)) base.CurrentPosition = outSpan.Start; else return; } else base.CurrentPosition = value; positionValid = true; } } public override int CurrentTrack { get { return base.CurrentTrack; } set { // FIXME: Temporarily disabled, needs functions to remove clip // from store/clip TimeSpan testSpan = timeSpan; TimeSpan outSpan = timeSpan; if (! modelRoot.Tracks.IsSpanEmptyExcluding (value, testSpan, clip)) { if (modelRoot.Tracks.SuggestPositionExcluding (value, testSpan, ref outSpan, modelRoot.Timeline.MouseOverTime, clip)) { base.CurrentPosition = outSpan.Start; base.CurrentTrack = value; } else return; } else base.CurrentTrack = value; trackValid = true; } } public Clip Clip { get { return clip; } } public Time CurrentLeft { get { return timeSpan.Start; } set { // FIXME: Check for 1 frame min duration if (value < clip.MinTimelineIn) value = clip.MinTimelineIn; TimeSpan testSpan = timeSpan; testSpan.Start = value; Time t = Time.Zero; if (! modelRoot.Tracks.IsSpanEmptyExcluding (track, testSpan, clip)) { if (modelRoot.Tracks.SuggestLeftAdjustPosition (track, clip, ref t)) testSpan.Start = t; else return; } timeSpan = testSpan; leftCutValid = true; leftCut = testSpan.Start; Invalidate (); } } public Time CurrentLeftNoCheck { get { return timeSpan.Start; } set { // FIXME: Check for 1 frame min duration if (value < clip.MinTimelineIn) value = clip.MinTimelineIn; TimeSpan testSpan = timeSpan; testSpan.Start = value; timeSpan = testSpan; leftCutValid = true; leftCut = testSpan.Start; Invalidate (); } } public Time SavedLeft { get { return backupSpan.Start; } } public Time CurrentRight { get { return timeSpan.End; } set { // FIXME: Check for 1 frame min duration if (value > clip.MaxTimelineOut) value = clip.MaxTimelineOut; TimeSpan testSpan = timeSpan; testSpan.End = value; Time t = Time.Zero; if (! modelRoot.Tracks.IsSpanEmptyExcluding (track, testSpan, clip)) { if (modelRoot.Tracks.SuggestRightAdjustPosition (track, clip, ref t)) testSpan.End = t; else return; } timeSpan = testSpan; rightCutValid = true; rightCut = testSpan.End; Invalidate (); } } public Time CurrentRightNoCheck { get { return timeSpan.End; } set { // FIXME: Check for 1 frame min duration if (value > clip.MaxTimelineOut) value = clip.MaxTimelineOut; TimeSpan testSpan = timeSpan; testSpan.End = value; timeSpan = testSpan; rightCutValid = true; rightCut = testSpan.End; Invalidate (); } } public Time SavedRight { get { return backupSpan.End; } } // Public methods ////////////////////////////////////////////// /* CONSTRUCTOR */ public ClipTrueElement (Model.Root root, Clip clip) : base (root, clip.TimelineSpan, root.Tracks.NoByTrack (clip.Track), clip.ParentItem) { this.clip = clip; leftCutValid = false; rightCutValid = false; positionValid = false; trackValid = false; leftCut = Time.Zero; rightCut = Time.Zero; clip.Changed += OnClipChanged; } public override void SyncThyself () { // Track operation if (positionValid && trackValid) { Track track = modelRoot.Tracks.GetByNo (base.CurrentTrack); Core.ICommand cmd = new Commands.TrackClip (clip, timeSpan.Start, track); modelRoot.CommandProcessor.PushCommand (cmd); } else if (positionValid) { Core.ICommand cmd = new Commands.MoveClip (clip, timeSpan.Start); modelRoot.CommandProcessor.PushCommand (cmd); } // Left adjust operation if (leftCutValid) { Core.ICommand cmd = new Commands.LeftAdjustClip (clip, leftCut); modelRoot.CommandProcessor.PushCommand (cmd); } // Right adjust operation if (rightCutValid) { Core.ICommand cmd = new Commands.RightAdjustClip (clip, rightCut); modelRoot.CommandProcessor.PushCommand (cmd); } // Reset leftCutValid = false; rightCutValid = false; positionValid = false; trackValid = false; leftCut = Time.Zero; rightCut = Time.Zero; base.SyncThyself (); } // Private methods ///////////////////////////////////////////// public void OnClipChanged (object o, EventArgs args) { // FIXME: Should invalidate only if different // FIXME: This is one of the places where "Freezing" object notification would help timeSpan = clip.TimelineSpan; if (clip.Track != null) track = modelRoot.Tracks.NoByTrack (clip.Track); Invalidate (); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\PlayerState.h:64 namespace UnrealEngine { [ManageType("ManagePlayerState")] public partial class ManagePlayerState : APlayerState, IManageWrapper { public ManagePlayerState(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_HandleWelcomeMessage(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnDeactivated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnReactivated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_bIsInactive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_PlayerId(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_PlayerName(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_Score(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_UniqueId(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_RecalculateAvgPing(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_RegisterPlayerWithSession(IntPtr self, bool bWasFromInvite); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_UnregisterPlayerWithSession(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_UpdatePing(IntPtr self, float inPing); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_BeginPlay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_ClearCrossLevelReferences(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_Destroyed(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_ForceNetRelevant(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_ForceNetUpdate(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_GatherCurrentMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_K2_DestroyActor(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_LifeSpanExpired(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_MarkComponentsAsPendingKill(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_NotifyActorBeginCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_NotifyActorEndCursorOver(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_AttachmentReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_Instigator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_Owner(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_ReplicatedMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnRep_ReplicateMovement(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OutsideWorldBounds(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostActorCreated(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostNetInit(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostNetReceiveLocationAndRotation(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostNetReceivePhysicState(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostNetReceiveRole(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostUnregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PreInitializeComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PreRegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_RegisterActorTickFunctions(IntPtr self, bool bRegister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_RegisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_ReregisterAllComponents(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_RerunConstructionScripts(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_Reset(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_RewindForReplay(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_SetActorHiddenInGame(IntPtr self, bool bNewHidden); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_SetLifeSpan(IntPtr self, float inLifespan); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_SetReplicateMovement(IntPtr self, bool bInReplicateMovement); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_TearOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_TeleportSucceeded(IntPtr self, bool bIsATest); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_Tick(IntPtr self, float deltaSeconds); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_TornOff(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_UnregisterAllComponents(IntPtr self, bool bForReregister); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__APlayerState_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods /// <summary> /// called after receiving player name /// </summary> protected override void HandleWelcomeMessage() => E__Supper__APlayerState_HandleWelcomeMessage(this); /// <summary> /// Called on the server when the owning player has disconnected, by default this method destroys this player state /// </summary> public override void OnDeactivated() => E__Supper__APlayerState_OnDeactivated(this); /// <summary> /// Called on the server when the owning player has reconnected and this player state is added to the active players array /// </summary> public override void OnReactivated() => E__Supper__APlayerState_OnReactivated(this); public override void OnRep_bIsInactive() => E__Supper__APlayerState_OnRep_bIsInactive(this); public override void OnRep_PlayerId() => E__Supper__APlayerState_OnRep_PlayerId(this); public override void OnRep_PlayerName() => E__Supper__APlayerState_OnRep_PlayerName(this); public override void OnRep_Score() => E__Supper__APlayerState_OnRep_Score(this); public override void OnRep_UniqueId() => E__Supper__APlayerState_OnRep_UniqueId(this); /// <summary> /// Recalculates the replicated Ping value once per second (both clientside and serverside), based upon collected ping data /// </summary> public override void RecalculateAvgPing() => E__Supper__APlayerState_RecalculateAvgPing(this); /// <summary> /// Register a player with the online subsystem /// </summary> /// <param name="bWasFromInvite">was this player invited directly</param> public override void RegisterPlayerWithSession(bool bWasFromInvite) => E__Supper__APlayerState_RegisterPlayerWithSession(this, bWasFromInvite); /// <summary> /// Unregister a player with the online subsystem /// </summary> public override void UnregisterPlayerWithSession() => E__Supper__APlayerState_UnregisterPlayerWithSession(this); /// <summary> /// Receives ping updates for the client (both clientside and serverside), from the net driver /// <para>NOTE: This updates much more frequently clientside, thus the clientside ping will often be different to what the server displays </para> /// </summary> public override void UpdatePing(float inPing) => E__Supper__APlayerState_UpdatePing(this, inPing); /// <summary> /// Overridable native event for when play begins for this actor. /// </summary> protected override void BeginPlay() => E__Supper__APlayerState_BeginPlay(this); /// <summary> /// Do anything needed to clear out cross level references; Called from ULevel::PreSave /// </summary> public override void ClearCrossLevelReferences() => E__Supper__APlayerState_ClearCrossLevelReferences(this); /// <summary> /// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending /// </summary> public override void Destroyed() => E__Supper__APlayerState_Destroyed(this); /// <summary> /// Forces this actor to be net relevant if it is not already by default /// </summary> public override void ForceNetRelevant() => E__Supper__APlayerState_ForceNetRelevant(this); /// <summary> /// Force actor to be updated to clients/demo net drivers /// </summary> public override void ForceNetUpdate() => E__Supper__APlayerState_ForceNetUpdate(this); /// <summary> /// Fills ReplicatedMovement property /// </summary> public override void GatherCurrentMovement() => E__Supper__APlayerState_GatherCurrentMovement(this); /// <summary> /// Invalidates anything produced by the last lighting build. /// </summary> public override void InvalidateLightingCacheDetailed(bool bTranslationOnly) => E__Supper__APlayerState_InvalidateLightingCacheDetailed(this, bTranslationOnly); /// <summary> /// Destroy the actor /// </summary> public override void DestroyActor() => E__Supper__APlayerState_K2_DestroyActor(this); /// <summary> /// Called when the lifespan of an actor expires (if he has one). /// </summary> public override void LifeSpanExpired() => E__Supper__APlayerState_LifeSpanExpired(this); /// <summary> /// Called to mark all components as pending kill when the actor is being destroyed /// </summary> public override void MarkComponentsAsPendingKill() => E__Supper__APlayerState_MarkComponentsAsPendingKill(this); /// <summary> /// Event when this actor has the mouse moved over it with the clickable interface. /// </summary> public override void NotifyActorBeginCursorOver() => E__Supper__APlayerState_NotifyActorBeginCursorOver(this); /// <summary> /// Event when this actor has the mouse moved off of it with the clickable interface. /// </summary> public override void NotifyActorEndCursorOver() => E__Supper__APlayerState_NotifyActorEndCursorOver(this); public override void OnRep_AttachmentReplication() => E__Supper__APlayerState_OnRep_AttachmentReplication(this); public override void OnRep_Instigator() => E__Supper__APlayerState_OnRep_Instigator(this); protected override void OnRep_Owner() => E__Supper__APlayerState_OnRep_Owner(this); public override void OnRep_ReplicatedMovement() => E__Supper__APlayerState_OnRep_ReplicatedMovement(this); public override void OnRep_ReplicateMovement() => E__Supper__APlayerState_OnRep_ReplicateMovement(this); /// <summary> /// Called on the client when the replication paused value is changed /// </summary> public override void OnReplicationPausedChanged(bool bIsReplicationPaused) => E__Supper__APlayerState_OnReplicationPausedChanged(this, bIsReplicationPaused); /// <summary> /// Called when the Actor is outside the hard limit on world bounds /// </summary> public override void OutsideWorldBounds() => E__Supper__APlayerState_OutsideWorldBounds(this); /// <summary> /// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay /// <para>For actors with a root component, the location and rotation will have already been set. </para> /// This is called before calling construction scripts, but after native components have been created /// </summary> public override void PostActorCreated() => E__Supper__APlayerState_PostActorCreated(this); /// <summary> /// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay /// </summary> public override void PostInitializeComponents() => E__Supper__APlayerState_PostInitializeComponents(this); /// <summary> /// Always called immediately after spawning and reading in replicated properties /// </summary> public override void PostNetInit() => E__Supper__APlayerState_PostNetInit(this); /// <summary> /// Update location and rotation from ReplicatedMovement. Not called for simulated physics! /// </summary> public override void PostNetReceiveLocationAndRotation() => E__Supper__APlayerState_PostNetReceiveLocationAndRotation(this); /// <summary> /// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity() /// </summary> public override void PostNetReceivePhysicState() => E__Supper__APlayerState_PostNetReceivePhysicState(this); /// <summary> /// Always called immediately after a new Role is received from the remote. /// </summary> public override void PostNetReceiveRole() => E__Supper__APlayerState_PostNetReceiveRole(this); /// <summary> /// Called after all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PostRegisterAllComponents() => E__Supper__APlayerState_PostRegisterAllComponents(this); /// <summary> /// Called after all currently registered components are cleared /// </summary> public override void PostUnregisterAllComponents() => E__Supper__APlayerState_PostUnregisterAllComponents(this); /// <summary> /// Called right before components are initialized, only called during gameplay /// </summary> public override void PreInitializeComponents() => E__Supper__APlayerState_PreInitializeComponents(this); /// <summary> /// Called before all the components in the Components array are registered, called both in editor and during gameplay /// </summary> public override void PreRegisterAllComponents() => E__Supper__APlayerState_PreRegisterAllComponents(this); /// <summary> /// Calls PrestreamTextures() for all the actor's meshcomponents. /// </summary> /// <param name="seconds">Number of seconds to force all mip-levels to be resident</param> /// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param> /// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param> public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups) => E__Supper__APlayerState_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups); /// <summary> /// Virtual call chain to register all tick functions for the actor class hierarchy /// </summary> /// <param name="bRegister">true to register, false, to unregister</param> protected override void RegisterActorTickFunctions(bool bRegister) => E__Supper__APlayerState_RegisterActorTickFunctions(this, bRegister); /// <summary> /// Ensure that all the components in the Components array are registered /// </summary> public override void RegisterAllComponents() => E__Supper__APlayerState_RegisterAllComponents(this); /// <summary> /// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty. /// </summary> public override void ReregisterAllComponents() => E__Supper__APlayerState_ReregisterAllComponents(this); /// <summary> /// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location. /// </summary> public override void RerunConstructionScripts() => E__Supper__APlayerState_RerunConstructionScripts(this); /// <summary> /// Reset actor to initial state - used when restarting level without reloading. /// </summary> public override void Reset() => E__Supper__APlayerState_Reset(this); /// <summary> /// Called on the actor before checkpoint data is applied during a replay. /// <para>Only called if bReplayRewindable is set. </para> /// </summary> public override void RewindForReplay() => E__Supper__APlayerState_RewindForReplay(this); /// <summary> /// Sets the actor to be hidden in the game /// </summary> /// <param name="bNewHidden">Whether or not to hide the actor and all its components</param> public override void SetActorHiddenInGame(bool bNewHidden) => E__Supper__APlayerState_SetActorHiddenInGame(this, bNewHidden); /// <summary> /// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed. /// </summary> public override void SetLifeSpan(float inLifespan) => E__Supper__APlayerState_SetLifeSpan(this, inLifespan); /// <summary> /// Set whether this actor's movement replicates to network clients. /// </summary> /// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param> public override void SetReplicateMovement(bool bInReplicateMovement) => E__Supper__APlayerState_SetReplicateMovement(this, bInReplicateMovement); /// <summary> /// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true. /// </summary> public override void TearOff() => E__Supper__APlayerState_TearOff(this); /// <summary> /// Called from TeleportTo() when teleport succeeds /// </summary> public override void TeleportSucceeded(bool bIsATest) => E__Supper__APlayerState_TeleportSucceeded(this, bIsATest); /// <summary> /// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame. /// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para> /// </summary> /// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param> public override void Tick(float deltaSeconds) => E__Supper__APlayerState_Tick(this, deltaSeconds); /// <summary> /// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients. /// <para>@see bTearOff </para> /// </summary> public override void TornOff() => E__Supper__APlayerState_TornOff(this); /// <summary> /// Unregister all currently registered components /// </summary> /// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param> public override void UnregisterAllComponents(bool bForReregister) => E__Supper__APlayerState_UnregisterAllComponents(this, bForReregister); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__APlayerState_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__APlayerState_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__APlayerState_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__APlayerState_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__APlayerState_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__APlayerState_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__APlayerState_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__APlayerState_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__APlayerState_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__APlayerState_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__APlayerState_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__APlayerState_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__APlayerState_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__APlayerState_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__APlayerState_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManagePlayerState self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManagePlayerState(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManagePlayerState>(PtrDesc); } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using SpatialAnalysis.Data; using SpatialAnalysis.Data.Visualization; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using SpatialAnalysis.Miscellaneous; using SpatialAnalysis.Interoperability; namespace SpatialAnalysis.FieldUtility.Visualization { /// <summary> /// Interaction logic for EditActivitiesUI.xaml /// </summary> public partial class EditActivitiesUI : Window { #region _host Definition public static DependencyProperty _hostProperty = DependencyProperty.Register("_host", typeof(OSMDocument), typeof(EditActivitiesUI), new FrameworkPropertyMetadata(null, _hostPropertyChanged, _propertyCoerce)); private OSMDocument _host { get { return (OSMDocument)GetValue(_hostProperty); } set { SetValue(_hostProperty, value); } } private static void _hostPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { EditActivitiesUI createTrail = (EditActivitiesUI)obj; createTrail._host = (OSMDocument)args.NewValue; } private static object _propertyCoerce(DependencyObject obj, object value) { return value; } #endregion public EditActivitiesUI(OSMDocument host) { InitializeComponent(); this._host = host; this._availableFields.ItemsSource = this._host.AllActivities.Values; this._availableFields.DisplayMemberPath = "Name"; this._save.Click += this._save_Click; this._load.Click += _load_Click; this.OKAY.Click += OKAY_Click; this._setCosts.Click += _setCosts_Click; this._parameters.Click += _parameters_Click; } void _load_Click(object sender, RoutedEventArgs e) { var dlg = new Microsoft.Win32.OpenFileDialog(); dlg.Title = "Load Activities"; dlg.DefaultExt = ".act"; dlg.Filter = "act documents (.act)|*.act"; Nullable<bool> result = dlg.ShowDialog(this._host); string fileAddress = ""; if (result == true) { fileAddress = dlg.FileName; } else { return; } string unitString = "UNIT:"; bool unitAssigned = false; Length_Unit_Types lengthUnitTypes = Length_Unit_Types.FEET; List<string> lines = new List<string>(); using (System.IO.StreamReader sr = new System.IO.StreamReader(fileAddress)) { string line = string.Empty; while ((line = sr.ReadLine()) != null) { if (!(string.IsNullOrEmpty(line) || string.IsNullOrWhiteSpace(line))) { line = line.TrimStart(' '); if (line[0] != '#')//remove comments { if (line.Length > unitString.Length && line.Substring(0, unitString.Length).ToUpper() == unitString.ToUpper()) { string unitName = line.Substring(unitString.Length, line.Length - unitString.Length).ToUpper().Trim(' '); switch (unitName) { case "METERS": unitAssigned = true; lengthUnitTypes = Length_Unit_Types.METERS; break; case "DECIMETERS": unitAssigned = true; lengthUnitTypes = Length_Unit_Types.DECIMETERS; break; case "CENTIMETERS": unitAssigned = true; lengthUnitTypes = Length_Unit_Types.CENTIMETERS; break; case "MILLIMETERS": unitAssigned = true; lengthUnitTypes = Length_Unit_Types.MILLIMETERS; break; case "FEET": unitAssigned = true; lengthUnitTypes = Length_Unit_Types.FEET; break; case "INCHES": unitAssigned = true; lengthUnitTypes = Length_Unit_Types.METERS; break; default: MessageBox.Show("Failed to parse unit information", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } } else { lines.Add(line); } } } } } if (lines.Count == 0) { MessageBox.Show("The file includes no input", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } //find the project unit type if (!unitAssigned) { MessageBox.Show("The did not include information for 'Unit of Length'", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } int n = 7; if (this._includeGuassian.IsChecked.Value) { double _n = 0; if (!double.TryParse(this._range_guassian.Text, out _n)) { MessageBox.Show("'Neighborhood Size' should be a valid number larger than 0", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } n = (int)_n; if (n < 1) { MessageBox.Show("'Neighborhood Size' should be a valid number larger than 0", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } } double r = 0; if (!double.TryParse(this._range.Text, out r)) { MessageBox.Show("'Neighborhood Size' should be a number larger than 1", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } int range = (int)r; if (range < 1) { MessageBox.Show("'Neighborhood Size' should be a number larger than 1", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (this._host.FieldGenerator == null || this._host.FieldGenerator.Range != range) { this._host.FieldGenerator = new SpatialDataCalculator(this._host, range, OSMDocument.AbsoluteTolerance); } List<ActivityDestination> destinations = new List<ActivityDestination>(); for (int i = 0; i < lines.Count/4; i++) { try { ActivityDestination destination = ActivityDestination.FromString(lines, i * 4, lengthUnitTypes, this._host.cellularFloor); if (this._host.AllActivities.ContainsKey(destination.Name)) { MessageBox.Show("An activity with the same name exists!", "", MessageBoxButton.OK, MessageBoxImage.Error); } else { destinations.Add(destination); } } catch (Exception error) { MessageBox.Show(error.Report()); } } if (destinations.Count == 0) { return; } Dispatcher.Invoke(new Action(() => { this._report.Visibility = System.Windows.Visibility.Visible; this.grid.IsEnabled = false; this._progressBar.Maximum = destinations.Count; this._activityName.Text = string.Empty; }), System.Windows.Threading.DispatcherPriority.ContextIdle); int count = 0; foreach (var item in destinations) { Dispatcher.Invoke(new Action(() => { this._activityName.Text = item.Name; }), System.Windows.Threading.DispatcherPriority.ContextIdle); count++; try { Activity newField = null; if (this._includeAngularCost.IsChecked.Value) { //double angularVelocityWeight = 0; if (Parameter.DefaultParameters[AgentParameters.MAN_AngularDeviationCost].Value <= 0) { MessageBox.Show("Cost of angular change should be exclusively larger than zero", "Activity Generation", MessageBoxButton.OK, MessageBoxImage.Information); return; } newField = this._host.FieldGenerator.GetDynamicActivity(item, Parameter.DefaultParameters[AgentParameters.MAN_AngularDeviationCost].Value); if (!newField.TrySetEngagementTime(item.MinimumEngagementTime, item.MinimumEngagementTime)) { throw new ArgumentException("Failed to set activity engagement duration!"); } } else { newField = this._host.FieldGenerator.GetStaticActivity(item); if (!newField.TrySetEngagementTime(item.MinimumEngagementTime, item.MaximumEngagementTime)) { throw new ArgumentException("Failed to set activity engagement duration!"); } } if (this._includeGuassian.IsChecked.Value) { //update filter if (this._host.ViewBasedGaussianFilter != null) { if (this._host.ViewBasedGaussianFilter.Range != n) { try { this._host.ViewBasedGaussianFilter = new IsovistClippedGaussian(this._host.cellularFloor, n); } catch (Exception error) { MessageBox.Show(error.Report(), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } } } else { try { this._host.ViewBasedGaussianFilter = new IsovistClippedGaussian(this._host.cellularFloor, n); } catch (Exception error) { MessageBox.Show(error.Report(), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } } var data = this._host.ViewBasedGaussianFilter.GetFilteredValues(newField); newField.Potentials = data; } this._host.AddActivity(newField); } catch (Exception error) { MessageBox.Show(error.Report()); } this.updateProgressBar(count); } this.Close(); } void _parameters_Click(object sender, RoutedEventArgs e) { ParameterSetting paramSetting = new ParameterSetting(this._host, false); paramSetting.Owner = this._host; paramSetting.ShowDialog(); paramSetting = null; } void _setCosts_Click(object sender, RoutedEventArgs e) { var controlPanel = new SpatialDataControlPanel(this._host, IncludedDataTypes.SpatialData); controlPanel.Owner = this._host; controlPanel.ShowDialog(); } void OKAY_Click(object sender, RoutedEventArgs e) { if (this._availableFields.SelectedItems.Count == 0) { MessageBox.Show("Select activities to continue", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } int n = 7; if (this._includeGuassian.IsChecked.Value) { double _n = 0; if (!double.TryParse(this._range_guassian.Text, out _n)) { MessageBox.Show("'Neighborhood Size' should be a valid number larger than 0", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } n = (int)_n; if (n < 1) { MessageBox.Show("'Neighborhood Size' should be a valid number larger than 0", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } } double r = 0; if (!double.TryParse(this._range.Text, out r)) { MessageBox.Show("'Neighborhood Size' should be a number larger than 1", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } int range = (int)r; if (range < 1) { MessageBox.Show("'Neighborhood Size' should be a number larger than 1", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (this._host.FieldGenerator == null || this._host.FieldGenerator.Range != range) { this._host.FieldGenerator = new SpatialDataCalculator(this._host, range, OSMDocument.AbsoluteTolerance); } Dispatcher.Invoke(new Action(() => { this._report.Visibility = System.Windows.Visibility.Visible; this.grid.IsEnabled = false; this._progressBar.Maximum = this._availableFields.SelectedItems.Count; this._activityName.Text = string.Empty; }), System.Windows.Threading.DispatcherPriority.ContextIdle); int count = 0; foreach (var item in this._availableFields.SelectedItems) { count++; try { Activity oldField = (Activity)item; Activity newField = null; Dispatcher.Invoke(new Action(() => { this._activityName.Text = oldField.Name; }), System.Windows.Threading.DispatcherPriority.ContextIdle); if (this._includeAngularCost.IsChecked.Value) { //double angularVelocityWeight = 0; if (Parameter.DefaultParameters[AgentParameters.MAN_AngularDeviationCost].Value <= 0) { MessageBox.Show("Cost of angular change should be exclusively larger than zero", "Activity Generation", MessageBoxButton.OK, MessageBoxImage.Information); return; } newField = this._host.FieldGenerator.GetDynamicActivity(oldField.Origins, oldField.DestinationArea, oldField.DefaultState, oldField.Name, Parameter.DefaultParameters[AgentParameters.MAN_AngularDeviationCost].Value); } else { newField = this._host.FieldGenerator.GetStaticActivity(oldField.Origins, oldField.DestinationArea, oldField.DefaultState, oldField.Name); } if (!newField.TrySetEngagementTime(oldField.MinimumEngagementTime, oldField.MaximumEngagementTime)) { MessageBox.Show("Cannot Set activity engagement time", "Activity Engagement Time", MessageBoxButton.OK, MessageBoxImage.Information); } if (this._includeGuassian.IsChecked.Value) { //update filter if (this._host.ViewBasedGaussianFilter != null) { if (this._host.ViewBasedGaussianFilter.Range != n) { try { this._host.ViewBasedGaussianFilter = new IsovistClippedGaussian(this._host.cellularFloor, n); } catch (Exception error) { MessageBox.Show(error.Report(), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } } } else { try { this._host.ViewBasedGaussianFilter = new IsovistClippedGaussian(this._host.cellularFloor, n); } catch (Exception error) { MessageBox.Show(error.Report(), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Exclamation); return; } } var data = this._host.ViewBasedGaussianFilter.GetFilteredValues(oldField); this._host.AllActivities[oldField.Name].Potentials = data; } else { this._host.AllActivities[oldField.Name].Potentials = newField.Potentials; } newField = null; } catch (Exception error) { MessageBox.Show(error.Report()); } this.updateProgressBar(count); } this.Close(); } void updateProgressBar(double percent) { Dispatcher.Invoke(new Action(() => { this._progressBar.SetValue(ProgressBar.ValueProperty, percent); }), System.Windows.Threading.DispatcherPriority.ContextIdle); } void _save_Click(object sender, RoutedEventArgs e) { if (this._availableFields.SelectedItems.Count == 0) { MessageBox.Show("Select activities to continue", "Missing Input", MessageBoxButton.OK, MessageBoxImage.Information); return; } Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.Title = "Save Activities"; dlg.DefaultExt = ".act"; dlg.Filter = "ACT documents (.act)|*.act"; Nullable<bool> result = dlg.ShowDialog(this._host); string fileAddress = ""; if (result == true) { fileAddress = dlg.FileName; } else { return; } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileAddress)) { sw.WriteLine("# Comment lines in this file should start with '#' character"); sw.WriteLine(string.Empty); sw.WriteLine("# Project Unit type"); sw.WriteLine("UNIT: " + this._host.BIM_To_OSM.UnitType.ToString()); sw.WriteLine(string.Empty); foreach (var item in this._availableFields.SelectedItems) { Activity activity = (Activity)item; sw.WriteLine(activity.GetStringRepresentation()); sw.WriteLine(string.Empty); } sw.Close(); } } protected override void OnClosed(EventArgs e) { base.OnClosed(e); this._availableFields.ItemsSource = null; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet("New", "AzureRmDiskConfig", SupportsShouldProcess = true)] [OutputType(typeof(PSDisk))] public partial class NewAzureRmDiskConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)] [Alias("AccountType")] public StorageAccountTypes? SkuName { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public OperatingSystemTypes? OsType { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public int? DiskSizeGB { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public string Location { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string[] Zone { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public DiskCreateOption? CreateOption { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string StorageAccountId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public ImageDiskReference ImageReference { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SourceUri { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SourceResourceId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public bool? EncryptionSettingsEnabled { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndSecretReference DiskEncryptionKey { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndKeyReference KeyEncryptionKey { get; set; } protected override void ProcessRecord() { if (ShouldProcess("Disk", "New")) { Run(); } } private void Run() { // Sku Microsoft.Azure.Management.Compute.Models.DiskSku vSku = null; // CreationData Microsoft.Azure.Management.Compute.Models.CreationData vCreationData = null; // EncryptionSettings Microsoft.Azure.Management.Compute.Models.EncryptionSettings vEncryptionSettings = null; if (this.SkuName != null) { if (vSku == null) { vSku = new Microsoft.Azure.Management.Compute.Models.DiskSku(); } vSku.Name = this.SkuName; } if (this.CreateOption.HasValue) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.CreateOption = this.CreateOption.Value; } if (this.StorageAccountId != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.StorageAccountId = this.StorageAccountId; } if (this.ImageReference != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.ImageReference = this.ImageReference; } if (this.SourceUri != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.SourceUri = this.SourceUri; } if (this.SourceResourceId != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.SourceResourceId = this.SourceResourceId; } if (this.EncryptionSettingsEnabled != null) { if (vEncryptionSettings == null) { vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings(); } vEncryptionSettings.Enabled = this.EncryptionSettingsEnabled; } if (this.DiskEncryptionKey != null) { if (vEncryptionSettings == null) { vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings(); } vEncryptionSettings.DiskEncryptionKey = this.DiskEncryptionKey; } if (this.KeyEncryptionKey != null) { if (vEncryptionSettings == null) { vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings(); } vEncryptionSettings.KeyEncryptionKey = this.KeyEncryptionKey; } var vDisk = new PSDisk { Zones = this.Zone, OsType = this.OsType, DiskSizeGB = this.DiskSizeGB, Location = this.Location, Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value), Sku = vSku, CreationData = vCreationData, EncryptionSettings = vEncryptionSettings, }; WriteObject(vDisk); } } }
using System; using System.Diagnostics; namespace ALinq.SqlClient { internal abstract class SqlVisitor { // Fields private int nDepth; // Methods protected SqlVisitor() { } public PostBindDotNetConverter PostBindDotNetConverter { get; set; } [Conditional("DEBUG")] internal static void CheckRecursionDepth(int maxLevel, int level) { if (level > maxLevel) { throw new Exception("Infinite Descent?"); } } internal static object Eval(SqlExpression expr) { if (expr.NodeType != SqlNodeType.Value) { throw Error.UnexpectedNode(expr.NodeType); } return ((SqlValue)expr).Value; } internal bool RefersToColumn(SqlExpression exp, SqlColumn col) { if (exp != null) { switch (exp.NodeType) { case SqlNodeType.Column: return ((exp == col) || this.RefersToColumn(((SqlColumn)exp).Expression, col)); case SqlNodeType.ColumnRef: { var ref2 = (SqlColumnRef)exp; return ((ref2.Column == col) || this.RefersToColumn(ref2.Column.Expression, col)); } case SqlNodeType.ExprSet: { var set = (SqlExprSet)exp; int num = 0; int count = set.Expressions.Count; while (num < count) { if (this.RefersToColumn(set.Expressions[num], col)) { return true; } num++; } break; } case SqlNodeType.OuterJoinedValue: return this.RefersToColumn(((SqlUnary)exp).Operand, col); } } return false; } internal virtual SqlNode Visit(SqlNode node) { if (node == null) { return null; } try { this.nDepth++; switch (node.NodeType) { case SqlNodeType.Add: case SqlNodeType.And: case SqlNodeType.BitAnd: case SqlNodeType.BitOr: case SqlNodeType.BitXor: case SqlNodeType.Coalesce: case SqlNodeType.Concat: case SqlNodeType.Div: case SqlNodeType.EQ: case SqlNodeType.EQ2V: case SqlNodeType.LE: case SqlNodeType.LT: case SqlNodeType.GE: case SqlNodeType.GT: case SqlNodeType.Mod: case SqlNodeType.Mul: case SqlNodeType.NE: case SqlNodeType.NE2V: case SqlNodeType.Or: case SqlNodeType.Sub: return this.VisitBinaryOperator((SqlBinary)node); case SqlNodeType.Alias: return this.VisitAlias((SqlAlias)node); case SqlNodeType.AliasRef: return this.VisitAliasRef((SqlAliasRef)node); case SqlNodeType.Assign: return this.VisitAssign((SqlAssign)node); case SqlNodeType.Avg: case SqlNodeType.BitNot: case SqlNodeType.ClrLength: case SqlNodeType.Convert: case SqlNodeType.Count: case SqlNodeType.Covar: case SqlNodeType.IsNotNull: case SqlNodeType.IsNull: case SqlNodeType.LongCount: case SqlNodeType.Max: case SqlNodeType.Min: case SqlNodeType.Negate: case SqlNodeType.Not: case SqlNodeType.Not2V: case SqlNodeType.OuterJoinedValue: case SqlNodeType.Stddev: case SqlNodeType.Sum: case SqlNodeType.ValueOf: return this.VisitUnaryOperator((SqlUnary)node); case SqlNodeType.Between: return this.VisitBetween((SqlBetween)node); case SqlNodeType.Block: return this.VisitBlock((SqlBlock)node); case SqlNodeType.Cast: return this.VisitCast((SqlUnary)node); case SqlNodeType.ClientArray: return this.VisitClientArray((SqlClientArray)node); case SqlNodeType.ClientCase: return this.VisitClientCase((SqlClientCase)node); case SqlNodeType.ClientParameter: return this.VisitClientParameter((SqlClientParameter)node); case SqlNodeType.ClientQuery: return this.VisitClientQuery((SqlClientQuery)node); case SqlNodeType.Column: return this.VisitColumn((SqlColumn)node); case SqlNodeType.ColumnRef: var result = this.VisitColumnRef((SqlColumnRef)node); return result; case SqlNodeType.Delete: return this.VisitDelete((SqlDelete)node); case SqlNodeType.DiscriminatedType: return this.VisitDiscriminatedType((SqlDiscriminatedType)node); case SqlNodeType.DiscriminatorOf: return this.VisitDiscriminatorOf((SqlDiscriminatorOf)node); case SqlNodeType.DoNotVisit: return this.VisitDoNotVisit((SqlDoNotVisitExpression)node); case SqlNodeType.Element: case SqlNodeType.Exists: case SqlNodeType.Multiset: case SqlNodeType.ScalarSubSelect: return this.VisitSubSelect((SqlSubSelect)node); case SqlNodeType.ExprSet: return this.VisitExprSet((SqlExprSet)node); case SqlNodeType.FunctionCall: return this.VisitFunctionCall((SqlFunctionCall)node); case SqlNodeType.In: return this.VisitIn((SqlIn)node); case SqlNodeType.IncludeScope: return this.VisitIncludeScope((SqlIncludeScope)node); case SqlNodeType.Lift: return this.VisitLift((SqlLift)node); case SqlNodeType.Link: return this.VisitLink((SqlLink)node); case SqlNodeType.Like: return this.VisitLike((SqlLike)node); case SqlNodeType.Grouping: return this.VisitGrouping((SqlGrouping)node); case SqlNodeType.Insert: return this.VisitInsert((SqlInsert)node); case SqlNodeType.Join: return this.VisitJoin((SqlJoin)node); case SqlNodeType.JoinedCollection: return this.VisitJoinedCollection((SqlJoinedCollection)node); case SqlNodeType.MethodCall: return this.VisitMethodCall((SqlMethodCall)node); case SqlNodeType.Member: return this.VisitMember((SqlMember)node); case SqlNodeType.MemberAssign: return this.VisitMemberAssign((SqlMemberAssign)node); case SqlNodeType.New: return this.VisitNew((SqlNew)node); case SqlNodeType.Nop: return this.VisitNop((SqlNop)node); case SqlNodeType.ObjectType: return this.VisitObjectType((SqlObjectType)node); case SqlNodeType.OptionalValue: return this.VisitOptionalValue((SqlOptionalValue)node); case SqlNodeType.Parameter: return this.VisitParameter((SqlParameter)node); case SqlNodeType.Row: return this.VisitRow((SqlRow)node); case SqlNodeType.RowNumber: return this.VisitRowNumber((SqlRowNumber)node); case SqlNodeType.SearchedCase: return this.VisitSearchedCase((SqlSearchedCase)node); case SqlNodeType.Select: return this.VisitSelect((SqlSelect)node); case SqlNodeType.SharedExpression: return this.VisitSharedExpression((SqlSharedExpression)node); case SqlNodeType.SharedExpressionRef: return this.VisitSharedExpressionRef((SqlSharedExpressionRef)node); case SqlNodeType.SimpleCase: return this.VisitSimpleCase((SqlSimpleCase)node); case SqlNodeType.SimpleExpression: return this.VisitSimpleExpression((SqlSimpleExpression)node); case SqlNodeType.StoredProcedureCall: return this.VisitStoredProcedureCall((SqlStoredProcedureCall)node); case SqlNodeType.Table: return this.VisitTable((SqlTable)node); case SqlNodeType.TableValuedFunctionCall: return this.VisitTableValuedFunctionCall((SqlTableValuedFunctionCall)node); case SqlNodeType.Treat: return this.VisitTreat((SqlUnary)node); case SqlNodeType.TypeCase: return this.VisitTypeCase((SqlTypeCase)node); case SqlNodeType.Union: return this.VisitUnion((SqlUnion)node); case SqlNodeType.Update: return this.VisitUpdate((SqlUpdate)node); case SqlNodeType.UserColumn: return this.VisitUserColumn((SqlUserColumn)node); case SqlNodeType.UserQuery: return this.VisitUserQuery((SqlUserQuery)node); case SqlNodeType.UserRow: return this.VisitUserRow((SqlUserRow)node); case SqlNodeType.Variable: return this.VisitVariable((SqlVariable)node); case SqlNodeType.Value: return this.VisitValue((SqlValue)node); } throw Error.UnexpectedNode(node); } finally { this.nDepth--; } } internal virtual SqlAlias VisitAlias(SqlAlias a) { a.Node = this.Visit(a.Node); return a; } internal virtual SqlExpression VisitAliasRef(SqlAliasRef aref) { return aref; } internal virtual SqlStatement VisitAssign(SqlAssign sa) { sa.LValue = this.VisitExpression(sa.LValue); sa.RValue = this.VisitExpression(sa.RValue); return sa; } internal virtual SqlExpression VisitBetween(SqlBetween between) { between.Expression = this.VisitExpression(between.Expression); between.Start = this.VisitExpression(between.Start); between.End = this.VisitExpression(between.End); return between; } internal virtual SqlExpression VisitBinaryOperator(SqlBinary bo) { bo.Left = this.VisitExpression(bo.Left); bo.Right = this.VisitExpression(bo.Right); return bo; } internal virtual SqlBlock VisitBlock(SqlBlock b) { int num = 0; int count = b.Statements.Count; while (num < count) { b.Statements[num] = (SqlStatement)this.Visit(b.Statements[num]); num++; } return b; } internal virtual SqlExpression VisitCast(SqlUnary c) { c.Operand = this.VisitExpression(c.Operand); return c; } internal virtual SqlExpression VisitClientArray(SqlClientArray scar) { int num = 0; int count = scar.Expressions.Count; while (num < count) { scar.Expressions[num] = this.VisitExpression(scar.Expressions[num]); num++; } return scar; } internal virtual SqlExpression VisitClientCase(SqlClientCase c) { c.Expression = this.VisitExpression(c.Expression); int num = 0; int count = c.Whens.Count; while (num < count) { SqlClientWhen when = c.Whens[num]; when.Match = this.VisitExpression(when.Match); when.Value = this.VisitExpression(when.Value); num++; } return c; } internal virtual SqlExpression VisitClientParameter(SqlClientParameter cp) { return cp; } internal virtual SqlExpression VisitClientQuery(SqlClientQuery cq) { int num = 0; int count = cq.Arguments.Count; while (num < count) { cq.Arguments[num] = this.VisitExpression(cq.Arguments[num]); num++; } return cq; } internal virtual SqlExpression VisitColumn(SqlColumn col) { col.Expression = this.VisitExpression(col.Expression); return col; } internal virtual SqlExpression VisitColumnRef(SqlColumnRef cref) { return cref; } internal virtual SqlStatement VisitDelete(SqlDelete delete) { delete.Select = this.VisitSequence(delete.Select); return delete; } internal virtual SqlExpression VisitDiscriminatedType(SqlDiscriminatedType dt) { dt.Discriminator = this.VisitExpression(dt.Discriminator); return dt; } internal virtual SqlExpression VisitDiscriminatorOf(SqlDiscriminatorOf dof) { dof.Object = this.VisitExpression(dof.Object); return dof; } internal virtual SqlExpression VisitDoNotVisit(SqlDoNotVisitExpression expr) { return expr.Expression; } internal virtual SqlExpression VisitElement(SqlSubSelect elem) { elem.Select = this.VisitSequence(elem.Select); return elem; } internal virtual SqlExpression VisitExists(SqlSubSelect sqlExpr) { sqlExpr.Select = this.VisitSequence(sqlExpr.Select); return sqlExpr; } internal virtual SqlExpression VisitExpression(SqlExpression exp) { return (SqlExpression)this.Visit(exp); } internal virtual SqlExpression VisitExprSet(SqlExprSet xs) { int num = 0; int count = xs.Expressions.Count; while (num < count) { xs.Expressions[num] = this.VisitExpression(xs.Expressions[num]); num++; } return xs; } internal virtual SqlExpression VisitFunctionCall(SqlFunctionCall fc) { int num = 0; int count = fc.Arguments.Count; while (num < count) { fc.Arguments[num] = this.VisitExpression(fc.Arguments[num]); num++; } return fc; } internal virtual SqlExpression VisitGrouping(SqlGrouping g) { g.Key = this.VisitExpression(g.Key); g.Group = this.VisitExpression(g.Group); return g; } internal virtual SqlExpression VisitIn(SqlIn sin) { sin.Expression = this.VisitExpression(sin.Expression); int num = 0; int count = sin.Values.Count; while (num < count) { sin.Values[num] = this.VisitExpression(sin.Values[num]); num++; } return sin; } internal virtual SqlNode VisitIncludeScope(SqlIncludeScope node) { node.Child = this.Visit(node.Child); return node; } internal virtual SqlStatement VisitInsert(SqlInsert insert) { insert.Table = (SqlTable)this.Visit(insert.Table); insert.Expression = this.VisitExpression(insert.Expression); insert.Row = (SqlRow)this.Visit(insert.Row); return insert; } internal virtual SqlSource VisitJoin(SqlJoin join) { join.Left = this.VisitSource(join.Left); join.Right = this.VisitSource(join.Right); join.Condition = this.VisitExpression(join.Condition); return join; } internal virtual SqlExpression VisitJoinedCollection(SqlJoinedCollection jc) { jc.Expression = this.VisitExpression(jc.Expression); jc.Count = this.VisitExpression(jc.Count); return jc; } internal virtual SqlExpression VisitLift(SqlLift lift) { lift.Expression = this.VisitExpression(lift.Expression); return lift; } internal virtual SqlExpression VisitLike(SqlLike like) { like.Expression = this.VisitExpression(like.Expression); like.Pattern = this.VisitExpression(like.Pattern); like.Escape = this.VisitExpression(like.Escape); return like; } internal virtual SqlNode VisitLink(SqlLink link) { int num = 0; int count = link.KeyExpressions.Count; while (num < count) { link.KeyExpressions[num] = this.VisitExpression(link.KeyExpressions[num]); num++; } return link; } protected virtual SqlNode VisitMember(SqlMember m) { m.Expression = this.VisitExpression(m.Expression); return m; } internal virtual SqlMemberAssign VisitMemberAssign(SqlMemberAssign ma) { ma.Expression = this.VisitExpression(ma.Expression); return ma; } internal virtual SqlExpression VisitMethodCall(SqlMethodCall mc) { mc.Object = this.VisitExpression(mc.Object); int num = 0; int count = mc.Arguments.Count; while (num < count) { mc.Arguments[num] = this.VisitExpression(mc.Arguments[num]); num++; } return mc; } internal virtual SqlExpression VisitMultiset(SqlSubSelect sms) { sms.Select = this.VisitSequence(sms.Select); return sms; } internal virtual SqlExpression VisitNew(SqlNew sox) { int num = 0; int count = sox.Args.Count; while (num < count) { sox.Args[num] = this.VisitExpression(sox.Args[num]); num++; } int num3 = 0; int num4 = sox.Members.Count; while (num3 < num4) { sox.Members[num3].Expression = this.VisitExpression(sox.Members[num3].Expression); num3++; } return sox; } internal virtual SqlExpression VisitNop(SqlNop nop) { return nop; } internal virtual SqlExpression VisitObjectType(SqlObjectType ot) { ot.Object = this.VisitExpression(ot.Object); return ot; } internal virtual SqlExpression VisitOptionalValue(SqlOptionalValue sov) { sov.HasValue = this.VisitExpression(sov.HasValue); sov.Value = this.VisitExpression(sov.Value); return sov; } internal virtual SqlExpression VisitParameter(SqlParameter p) { return p; } internal virtual SqlRow VisitRow(SqlRow row) { int num = 0; int count = row.Columns.Count; while (num < count) { row.Columns[num].Expression = this.VisitExpression(row.Columns[num].Expression); num++; } return row; } internal virtual SqlRowNumber VisitRowNumber(SqlRowNumber rowNumber) { int num = 0; int count = rowNumber.OrderBy.Count; while (num < count) { rowNumber.OrderBy[num].Expression = this.VisitExpression(rowNumber.OrderBy[num].Expression); num++; } return rowNumber; } internal virtual SqlExpression VisitScalarSubSelect(SqlSubSelect ss) { ss.Select = this.VisitSequence(ss.Select); return ss; } internal virtual SqlExpression VisitSearchedCase(SqlSearchedCase c) { int num = 0; int count = c.Whens.Count; while (num < count) { SqlWhen when = c.Whens[num]; when.Match = this.VisitExpression(when.Match); when.Value = this.VisitExpression(when.Value); num++; } c.Else = this.VisitExpression(c.Else); return c; } internal virtual SqlSelect VisitSelect(SqlSelect select) { select = this.VisitSelectCore(select); select.Selection = this.VisitExpression(select.Selection); return select; } internal virtual SqlSelect VisitSelectCore(SqlSelect select) { select.From = this.VisitSource(select.From); select.Where = this.VisitExpression(select.Where); int num = 0; int count = select.GroupBy.Count; while (num < count) { select.GroupBy[num] = this.VisitExpression(select.GroupBy[num]); num++; } select.Having = this.VisitExpression(select.Having); int num3 = 0; int num4 = select.OrderBy.Count; while (num3 < num4) { select.OrderBy[num3].Expression = this.VisitExpression(select.OrderBy[num3].Expression); num3++; } select.Top = this.VisitExpression(select.Top); select.Row = (SqlRow)this.Visit(select.Row); return select; } internal virtual SqlSelect VisitSequence(SqlSelect sel) { return (SqlSelect)this.Visit(sel); } internal virtual SqlExpression VisitSharedExpression(SqlSharedExpression shared) { shared.Expression = this.VisitExpression(shared.Expression); return shared; } internal virtual SqlExpression VisitSharedExpressionRef(SqlSharedExpressionRef sref) { return sref; } internal virtual SqlExpression VisitSimpleCase(SqlSimpleCase c) { c.Expression = this.VisitExpression(c.Expression); int num = 0; int count = c.Whens.Count; while (num < count) { SqlWhen when = c.Whens[num]; when.Match = this.VisitExpression(when.Match); when.Value = this.VisitExpression(when.Value); num++; } return c; } internal virtual SqlExpression VisitSimpleExpression(SqlSimpleExpression simple) { simple.Expression = this.VisitExpression(simple.Expression); return simple; } internal virtual SqlSource VisitSource(SqlSource source) { return (SqlSource)this.Visit(source); } internal virtual SqlStoredProcedureCall VisitStoredProcedureCall(SqlStoredProcedureCall spc) { int num = 0; int count = spc.Arguments.Count; while (num < count) { spc.Arguments[num] = this.VisitExpression(spc.Arguments[num]); num++; } spc.Projection = this.VisitExpression(spc.Projection); int num3 = 0; int num4 = spc.Columns.Count; while (num3 < num4) { spc.Columns[num3] = (SqlUserColumn)this.Visit(spc.Columns[num3]); num3++; } return spc; } internal virtual SqlExpression VisitSubSelect(SqlSubSelect ss) { switch (ss.NodeType) { case SqlNodeType.Element: return this.VisitElement(ss); case SqlNodeType.Exists: return this.VisitExists(ss); case SqlNodeType.Multiset: return this.VisitMultiset(ss); case SqlNodeType.ScalarSubSelect: return this.VisitScalarSubSelect(ss); } throw Error.UnexpectedNode(ss.NodeType); } internal virtual SqlTable VisitTable(SqlTable tab) { return tab; } internal virtual SqlExpression VisitTableValuedFunctionCall(SqlTableValuedFunctionCall fc) { int num = 0; int count = fc.Arguments.Count; while (num < count) { fc.Arguments[num] = this.VisitExpression(fc.Arguments[num]); num++; } return fc; } internal virtual SqlExpression VisitTreat(SqlUnary t) { t.Operand = this.VisitExpression(t.Operand); return t; } internal virtual SqlExpression VisitTypeCase(SqlTypeCase tc) { tc.Discriminator = this.VisitExpression(tc.Discriminator); int num = 0; int count = tc.Whens.Count; while (num < count) { SqlTypeCaseWhen when = tc.Whens[num]; when.Match = this.VisitExpression(when.Match); when.TypeBinding = this.VisitExpression(when.TypeBinding); num++; } return tc; } internal virtual SqlExpression VisitUnaryOperator(SqlUnary uo) { uo.Operand = this.VisitExpression(uo.Operand); return uo; } internal virtual SqlNode VisitUnion(SqlUnion su) { su.Left = this.Visit(su.Left); su.Right = this.Visit(su.Right); return su; } internal virtual SqlStatement VisitUpdate(SqlUpdate update) { update.Select = this.VisitSequence(update.Select); int num = 0; int count = update.Assignments.Count; while (num < count) { update.Assignments[num] = (SqlAssign)this.Visit(update.Assignments[num]); num++; } return update; } internal virtual SqlExpression VisitUserColumn(SqlUserColumn suc) { return suc; } internal virtual SqlUserQuery VisitUserQuery(SqlUserQuery suq) { int num = 0; int count = suq.Arguments.Count; while (num < count) { suq.Arguments[num] = this.VisitExpression(suq.Arguments[num]); num++; } suq.Projection = this.VisitExpression(suq.Projection); int num3 = 0; int num4 = suq.Columns.Count; while (num3 < num4) { suq.Columns[num3] = (SqlUserColumn)this.Visit(suq.Columns[num3]); num3++; } return suq; } internal virtual SqlExpression VisitUserRow(SqlUserRow row) { return row; } internal virtual SqlExpression VisitValue(SqlValue value) { return value; } internal virtual SqlExpression VisitVariable(SqlVariable v) { return v; } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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 Spring.Context.Support; using Spring.Objects.Factory; using System; using System.Linq; using System.Abstract; using System.Collections.Generic; namespace Spring.Abstract { /// <summary> /// ISpringServiceLocator /// </summary> public interface ISpringServiceLocator : IServiceLocator { /// <summary> /// Gets the container. /// </summary> GenericApplicationContext Container { get; } } /// <summary> /// SpringServiceLocator /// </summary> [Serializable] public class SpringServiceLocator : ISpringServiceLocator, IDisposable, ServiceLocatorManager.ISetupRegistration { GenericApplicationContext _container; SpringServiceRegistrar _registrar; static SpringServiceLocator() { ServiceLocatorManager.EnsureRegistration(); } /// <summary> /// Initializes a new instance of the <see cref="SpringServiceLocator"/> class. /// </summary> public SpringServiceLocator() : this(new GenericApplicationContext()) { } /// <summary> /// Initializes a new instance of the <see cref="SpringServiceLocator"/> class. /// </summary> /// <param name="container">The container.</param> public SpringServiceLocator(object container) { if (container == null) throw new ArgumentNullException("container"); Container = (container as GenericApplicationContext); if (Container == null) throw new ArgumentOutOfRangeException("container", "Must be of type Spring.Context.Support.GenericApplicationContext"); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_container != null) { var container = _container; _container = null; _registrar = null; // prevent cyclical dispose if (container != null) container.Dispose(); } } Action<IServiceLocator, string> ServiceLocatorManager.ISetupRegistration.DefaultServiceRegistrar { get { return (locator, name) => ServiceLocatorManager.RegisterInstance<ISpringServiceLocator>(this, locator, name); } } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType">An object that specifies the type of service object to get.</param> /// <returns> /// A service object of type <paramref name="serviceType"/>. /// -or- /// null if there is no service object of type <paramref name="serviceType"/>. /// </returns> public object GetService(Type serviceType) { return Resolve(serviceType); } /// <summary> /// Creates the child. /// </summary> /// <returns></returns> public IServiceLocator CreateChild(object tag) { throw new NotSupportedException(); } /// <summary> /// Gets the underlying container. /// </summary> /// <typeparam name="TContainer">The type of the container.</typeparam> /// <returns></returns> public TContainer GetUnderlyingContainer<TContainer>() where TContainer : class { return (_container as TContainer); } // registrar /// <summary> /// Gets the registrar. /// </summary> public IServiceRegistrar Registrar { get { return _registrar; } } // Creates default object when not registered private object CreateObject(Type serviceType) { var serviceTypeConstructor = serviceType.GetConstructor(new Type[0]); var args = serviceTypeConstructor.GetParameters().Select(x => (object)Resolve(x.ParameterType)).ToArray(); return Activator.CreateInstance(serviceType, args); } // resolve /// <summary> /// Resolves this instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns></returns> public TService Resolve<TService>() where TService : class { var serviceType = typeof(TService); try { return (TService)_container.GetObject(GetName(serviceType), serviceType); } catch (NoSuchObjectDefinitionException) { return (TService)CreateObject(serviceType); } catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); } } internal static string GetName(Type serviceType) { return serviceType.FullName; } /// <summary> /// Resolves the specified name. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="name">The name.</param> /// <returns></returns> public TService Resolve<TService>(string name) where TService : class { var serviceType = typeof(TService); try { return (TService)_container.GetObject(name, serviceType); } catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); } } /// <summary> /// Resolves the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns></returns> public object Resolve(Type serviceType) { try { return _container.GetObject(GetName(serviceType), serviceType); } catch (NoSuchObjectDefinitionException) { return CreateObject(serviceType); } catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); } } /// <summary> /// Resolves the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="name">The name.</param> /// <returns></returns> public object Resolve(Type serviceType, string name) { try { return _container.GetObject(name, serviceType); } catch (Exception ex) { throw new ServiceLocatorResolutionException(serviceType, ex); } } // /// <summary> /// Resolves all. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns></returns> public IEnumerable<TService> ResolveAll<TService>() where TService : class { throw new NotSupportedException(); } /// <summary> /// Resolves all. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns></returns> public IEnumerable<object> ResolveAll(Type serviceType) { throw new NotSupportedException(); } // inject /// <summary> /// Injects the specified instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> /// <returns></returns> public TService Inject<TService>(TService instance) where TService : class { try { return (TService)_container.ConfigureObject(instance, GetName(typeof(TService))); } catch (Exception ex) { throw new ServiceLocatorResolutionException(typeof(TService), ex); } } // release and teardown /// <summary> /// Releases the specified instance. /// </summary> /// <param name="instance">The instance.</param> public void Release(object instance) { throw new NotSupportedException(); } /// <summary> /// Tears down. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> public void TearDown<TService>(TService instance) where TService : class { throw new NotSupportedException(); } #region Domain specific /// <summary> /// Gets the container. /// </summary> public GenericApplicationContext Container { get { return _container; } private set { _container = value; _registrar = new SpringServiceRegistrar(this, value); } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="SqlConnectionString.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.SqlClient { using System; using System.Collections; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using System.Security.Permissions; using System.Text; using System.Runtime.Versioning; internal sealed class SqlConnectionString : DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution internal static class DEFAULT { internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent; internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME; internal const bool Asynchronous = false; internal const string AttachDBFilename = ""; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const bool Connection_Reset = true; internal const bool Context_Connection = false; internal const string Current_Language = ""; internal const string Data_Source = ""; internal const bool Encrypt = false; internal const bool Enlist = true; internal const string FailoverPartner = ""; internal const string Initial_Catalog = ""; internal const bool Integrated_Security = false; internal const int Load_Balance_Timeout = 0; // default of 0 means don't use internal const bool MARS = false; internal const int Max_Pool_Size = 100; internal const int Min_Pool_Size = 0; internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; internal const string Network_Library = ""; internal const int Packet_Size = 8000; internal const string Password = ""; internal const bool Persist_Security_Info = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string Type_System_Version = ""; internal const string User_ID = ""; internal const bool User_Instance = false; internal const bool Replication = false; internal const int Connect_Retry_Count = 1; internal const int Connect_Retry_Interval = 10; internal static readonly SqlAuthenticationMethod Authentication = SqlAuthenticationMethod.NotSpecified; internal static readonly SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Disabled; } // SqlConnection ConnectionString Options // keys must be lowercase! internal static class KEY { internal const string ApplicationIntent = "applicationintent"; internal const string Application_Name = "application name"; internal const string AsynchronousProcessing = "asynchronous processing"; internal const string AttachDBFilename = "attachdbfilename"; internal const string ColumnEncryptionSetting = "column encryption setting"; internal const string Connect_Timeout = "connect timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; internal const string Current_Language = "current language"; internal const string Data_Source = "data source"; internal const string Encrypt = "encrypt"; internal const string Enlist = "enlist"; internal const string FailoverPartner = "failover partner"; internal const string Initial_Catalog = "initial catalog"; internal const string Integrated_Security = "integrated security"; internal const string Load_Balance_Timeout = "load balance timeout"; internal const string MARS = "multipleactiveresultsets"; internal const string Max_Pool_Size = "max pool size"; internal const string Min_Pool_Size = "min pool size"; internal const string MultiSubnetFailover = "multisubnetfailover"; internal const string Network_Library = "network library"; internal const string Packet_Size = "packet size"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Pooling = "pooling"; internal const string TransactionBinding = "transaction binding"; internal const string TrustServerCertificate = "trustservercertificate"; internal const string Type_System_Version = "type system version"; internal const string User_ID = "user id"; internal const string User_Instance = "user instance"; internal const string Workstation_Id = "workstation id"; internal const string Replication = "replication"; internal const string Connect_Retry_Count = "connectretrycount"; internal const string Connect_Retry_Interval = "connectretryinterval"; internal const string Authentication = "authentication"; } // Constant for the number of duplicate options in the connnection string private static class SYNONYM { // application name internal const string APP = "app"; internal const string Async = "async"; // attachDBFilename internal const string EXTENDED_PROPERTIES = "extended properties"; internal const string INITIAL_FILE_NAME = "initial file name"; // connect timeout internal const string CONNECTION_TIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; // current language internal const string LANGUAGE = "language"; // data source internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORK_ADDRESS = "network address"; // initial catalog internal const string DATABASE = "database"; // integrated security internal const string TRUSTED_CONNECTION = "trusted_connection"; // load balance timeout internal const string Connection_Lifetime = "connection lifetime"; // network library internal const string NET = "net"; internal const string NETWORK = "network"; // password internal const string Pwd = "pwd"; // persist security info internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; // user id internal const string UID = "uid"; internal const string User = "user"; // workstation id internal const string WSID = "wsid"; // make sure to update SynonymCount value below when adding or removing synonyms } internal const int SynonymCount = 21; // the following are all inserted as keys into the _netlibMapping hash internal static class NETLIB { internal const string AppleTalk = "dbmsadsn"; internal const string BanyanVines = "dbmsvinn"; internal const string IPXSPX = "dbmsspxn"; internal const string Multiprotocol = "dbmsrpcn"; internal const string NamedPipes = "dbnmpntw"; internal const string SharedMemory = "dbmslpcn"; internal const string TCPIP = "dbmssocn"; internal const string VIA = "dbmsgnet"; } internal enum TypeSystem { Latest = 2008, SQLServer2000 = 2000, SQLServer2005 = 2005, SQLServer2008 = 2008, SQLServer2012 = 2012, } internal static class TYPESYSTEMVERSION { internal const string Latest = "Latest"; internal const string SQL_Server_2000 = "SQL Server 2000"; internal const string SQL_Server_2005 = "SQL Server 2005"; internal const string SQL_Server_2008 = "SQL Server 2008"; internal const string SQL_Server_2012 = "SQL Server 2012"; } internal enum TransactionBindingEnum { ImplicitUnbind, ExplicitUnbind } internal static class TRANSACIONBINDING { internal const string ImplicitUnbind = "Implicit Unbind"; internal const string ExplicitUnbind = "Explicit Unbind"; } static private Hashtable _sqlClientSynonyms; static private Hashtable _netlibMapping; private readonly bool _integratedSecurity; private readonly bool _connectionReset; private readonly bool _contextConnection; private readonly bool _encrypt; private readonly bool _trustServerCertificate; private readonly bool _enlist; private readonly bool _mars; private readonly bool _persistSecurityInfo; private readonly bool _pooling; private readonly bool _replication; private readonly bool _userInstance; private readonly bool _multiSubnetFailover; private readonly SqlAuthenticationMethod _authType; private readonly SqlConnectionColumnEncryptionSetting _columnEncryptionSetting; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; private readonly int _minPoolSize; private readonly int _packetSize; private readonly int _connectRetryCount; private readonly int _connectRetryInterval; private readonly ApplicationIntent _applicationIntent; private readonly string _applicationName; private readonly string _attachDBFileName; private readonly string _currentLanguage; private readonly string _dataSource; private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB private readonly string _failoverPartner; private readonly string _initialCatalog; private readonly string _password; private readonly string _userID; private readonly string _networkLibrary; private readonly string _workstationId; private readonly TypeSystem _typeSystemVersion; private readonly Version _typeSystemAssemblyVersion; private static readonly Version constTypeSystemAsmVersion10 = new Version("10.0.0.0"); private static readonly Version constTypeSystemAsmVersion11 = new Version("11.0.0.0"); private readonly TransactionBindingEnum _transactionBinding; private readonly string _expandedAttachDBFilename; // expanded during construction so that CreatePermissionSet & Expand are consistent // SxS: reading Software\\Microsoft\\MSSQLServer\\Client\\SuperSocketNetLib\Encrypt value from registry [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms(), false) { bool runningInProc = InOutOfProcHelper.InProc; _integratedSecurity = ConvertValueToIntegratedSecurity(); ConvertValueToBoolean(KEY.AsynchronousProcessing, DEFAULT.Asynchronous); // while we don't use it anymore, we still need to verify it is true/false // SQLPT 41700: Ignore ResetConnection=False (still validate the keyword/value) _connectionReset = ConvertValueToBoolean(KEY.Connection_Reset, DEFAULT.Connection_Reset); _contextConnection = ConvertValueToBoolean(KEY.Context_Connection, DEFAULT.Context_Connection); _encrypt = ConvertValueToEncrypt(); _enlist = ConvertValueToBoolean(KEY.Enlist, ADP.IsWindowsNT); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _networkLibrary = ConvertValueToString(KEY.Network_Library, null); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); _authType = ConvertValueToAuthenticationType(); _columnEncryptionSetting = ConvertValueToColumnEncryptionSetting(); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_contextConnection) { // We have to be running in the engine for you to request a // context connection. if (!runningInProc) { throw SQL.ContextUnavailableOutOfProc(); } // When using a context connection, we need to ensure that no // other connection string keywords are specified. foreach (DictionaryEntry entry in Parsetable) { if ((string) entry.Key != KEY.Context_Connection && (string) entry.Key != KEY.Type_System_Version) { throw SQL.ContextAllowsLimitedKeywords(); } } } if (!_encrypt) { // Support legacy registry encryption settings const string folder = "Software\\Microsoft\\MSSQLServer\\Client\\SuperSocketNetLib"; const string value = "Encrypt"; Object obj = ADP.LocalMachineRegistryValue(folder, value); if ((obj is Int32) && (1 == (int)obj)) { // If the registry key exists _encrypt = true; } } if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } if (null != _networkLibrary) { // MDAC 83525 string networkLibrary = _networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture); Hashtable netlib = NetlibMapping(); if (!netlib.ContainsKey(networkLibrary)) { throw ADP.InvalidConnectionOptionValue(KEY.Network_Library); } _networkLibrary = (string) netlib[networkLibrary]; } else { _networkLibrary = DEFAULT.Network_Library; } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage , TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } // expand during construction so that CreatePermissionSet and Expand are consistent string datadir = null; _expandedAttachDBFilename = ExpandDataDirectory(KEY.AttachDBFilename, _attachDBFileName, ref datadir); if (null != _expandedAttachDBFilename) { if (0 <= _expandedAttachDBFilename.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } ValidateValueLength(_expandedAttachDBFilename, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); if (_localDBInstance == null) { // fail fast to verify LocalHost when using |DataDirectory| // still must check again at connect time string host = _dataSource; string protocol = _networkLibrary; TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol); VerifyLocalHostAndFixup(ref host, true, false /*don't fix-up*/); } } else if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } _typeSystemAssemblyVersion = constTypeSystemAsmVersion10; if (true == _userInstance && !ADP.IsEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (ADP.IsEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { if (_contextConnection) { throw SQL.ContextAllowsOnlyTypeSystem2005(); } _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; _typeSystemAssemblyVersion = constTypeSystemAsmVersion11; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (ADP.IsEmpty(transactionBindingString)) { transactionBindingString = DbConnectionStringDefaults.TransactionBinding; } if (transactionBindingString.Equals(TRANSACIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ImplicitUnbind; } else if (transactionBindingString.Equals(TRANSACIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ExplicitUnbind; } else { throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding); } if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner)) throw SQL.ROR_FailoverNotSupportedConnString(); if ((_connectRetryCount<0) || (_connectRetryCount>255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } if (Authentication != SqlAuthenticationMethod.NotSpecified && _integratedSecurity == true) { throw SQL.AuthenticationAndIntegratedSecurity(); } if (Authentication == SqlClient.SqlAuthenticationMethod.ActiveDirectoryIntegrated && (HasUserIdKeyword || HasPasswordKeyword)) { throw SQL.IntegratedWithUserIDAndPassword(); } } // This c-tor is used to create SSE and user instance connection strings when user instance is set to true // internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool? setEnlistValue) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _connectionReset = connectionOptions._connectionReset; _contextConnection = connectionOptions._contextConnection; _encrypt = connectionOptions._encrypt; if (setEnlistValue.HasValue) { _enlist = setEnlistValue.Value; } else { _enlist = connectionOptions._enlist; } _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _networkLibrary = connectionOptions._networkLibrary; _workstationId = connectionOptions._workstationId; _expandedAttachDBFilename = connectionOptions._expandedAttachDBFilename; _typeSystemVersion = connectionOptions._typeSystemVersion; _typeSystemAssemblyVersion =connectionOptions._typeSystemAssemblyVersion; _transactionBinding = connectionOptions._transactionBinding; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; _authType = connectionOptions._authType; _columnEncryptionSetting = connectionOptions._columnEncryptionSetting; ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); } internal bool IntegratedSecurity { get { return _integratedSecurity; } } // We always initialize in Async mode so that both synchronous and asynchronous methods // will work. In the future we can deprecate the keyword entirely. internal bool Asynchronous { get { return true; } } // SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security internal bool ConnectionReset { get { return true; } } internal bool ContextConnection { get { return _contextConnection; } } // internal bool EnableUdtDownload { get { return _enableUdtDownload;} } internal bool Encrypt { get { return _encrypt; } } internal bool TrustServerCertificate { get { return _trustServerCertificate; } } internal bool Enlist { get { return _enlist; } } internal bool MARS { get { return _mars; } } internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } } internal SqlAuthenticationMethod Authentication { get { return _authType; } } internal SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting { get { return _columnEncryptionSetting; } } internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } } internal bool Pooling { get { return _pooling; } } internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } internal int MinPoolSize { get { return _minPoolSize; } } internal int PacketSize { get { return _packetSize; } } internal int ConnectRetryCount { get { return _connectRetryCount; } } internal int ConnectRetryInterval { get { return _connectRetryInterval; } } internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } } internal string ApplicationName { get { return _applicationName; } } internal string AttachDBFilename { get { return _attachDBFileName; } } internal string CurrentLanguage { get { return _currentLanguage; } } internal string DataSource { get { return _dataSource; } } internal string LocalDBInstance { get { return _localDBInstance; } } internal string FailoverPartner { get { return _failoverPartner; } } internal string InitialCatalog { get { return _initialCatalog; } } internal string NetworkLibrary { get { return _networkLibrary; } } internal string Password { get { return _password; } } internal string UserID { get { return _userID; } } internal string WorkstationId { get { return _workstationId; } } internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } } internal Version TypeSystemAssemblyVersion { get { return _typeSystemAssemblyVersion; } } internal TransactionBindingEnum TransactionBinding { get { return _transactionBinding; } } internal bool EnforceLocalHost { get { // so tdsparser.connect can determine if SqlConnection.UserConnectionOptions // needs to enfoce local host after datasource alias lookup return (null != _expandedAttachDBFilename) && (null == _localDBInstance); } } protected internal override System.Security.PermissionSet CreatePermissionSet() { System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None); permissionSet.AddPermission(new SqlClientPermission(this)); return permissionSet; } protected internal override string Expand() { if (null != _expandedAttachDBFilename) { return ExpandKeyword(KEY.AttachDBFilename, _expandedAttachDBFilename); } else { return base.Expand(); } } private static bool CompareHostName(ref string host, string name, bool fixup) { // same computer name or same computer name + "\named instance" bool equal = false; if (host.Equals(name, StringComparison.OrdinalIgnoreCase)) { if (fixup) { host = "."; } equal = true; } else if (host.StartsWith(name+@"\", StringComparison.OrdinalIgnoreCase)) { if (fixup) { host = "." + host.Substring(name.Length); } equal = true; } return equal; } // this hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string internal static Hashtable GetParseSynonyms() { Hashtable hash = _sqlClientSynonyms; if (null == hash) { hash = new Hashtable(SqlConnectionStringBuilder.KeywordsCount + SynonymCount); hash.Add(KEY.ApplicationIntent, KEY.ApplicationIntent); hash.Add(KEY.Application_Name, KEY.Application_Name); hash.Add(KEY.AsynchronousProcessing, KEY.AsynchronousProcessing); hash.Add(KEY.AttachDBFilename, KEY.AttachDBFilename); hash.Add(KEY.Connect_Timeout, KEY.Connect_Timeout); hash.Add(KEY.Connection_Reset, KEY.Connection_Reset); hash.Add(KEY.Context_Connection, KEY.Context_Connection); hash.Add(KEY.Current_Language, KEY.Current_Language); hash.Add(KEY.Data_Source, KEY.Data_Source); hash.Add(KEY.Encrypt, KEY.Encrypt); hash.Add(KEY.Enlist, KEY.Enlist); hash.Add(KEY.FailoverPartner, KEY.FailoverPartner); hash.Add(KEY.Initial_Catalog, KEY.Initial_Catalog); hash.Add(KEY.Integrated_Security, KEY.Integrated_Security); hash.Add(KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout); hash.Add(KEY.MARS, KEY.MARS); hash.Add(KEY.Max_Pool_Size, KEY.Max_Pool_Size); hash.Add(KEY.Min_Pool_Size, KEY.Min_Pool_Size); hash.Add(KEY.MultiSubnetFailover, KEY.MultiSubnetFailover); hash.Add(KEY.Network_Library, KEY.Network_Library); hash.Add(KEY.Packet_Size, KEY.Packet_Size); hash.Add(KEY.Password, KEY.Password); hash.Add(KEY.Persist_Security_Info, KEY.Persist_Security_Info); hash.Add(KEY.Pooling, KEY.Pooling); hash.Add(KEY.Replication, KEY.Replication); hash.Add(KEY.TrustServerCertificate, KEY.TrustServerCertificate); hash.Add(KEY.TransactionBinding, KEY.TransactionBinding); hash.Add(KEY.Type_System_Version, KEY.Type_System_Version); hash.Add(KEY.ColumnEncryptionSetting, KEY.ColumnEncryptionSetting); hash.Add(KEY.User_ID, KEY.User_ID); hash.Add(KEY.User_Instance, KEY.User_Instance); hash.Add(KEY.Workstation_Id, KEY.Workstation_Id); hash.Add(KEY.Connect_Retry_Count, KEY.Connect_Retry_Count); hash.Add(KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval); hash.Add(KEY.Authentication, KEY.Authentication); hash.Add(SYNONYM.APP, KEY.Application_Name); hash.Add(SYNONYM.Async, KEY.AsynchronousProcessing); hash.Add(SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename); hash.Add(SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename); hash.Add(SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.LANGUAGE, KEY.Current_Language); hash.Add(SYNONYM.ADDR, KEY.Data_Source); hash.Add(SYNONYM.ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.NETWORK_ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.SERVER, KEY.Data_Source); hash.Add(SYNONYM.DATABASE, KEY.Initial_Catalog); hash.Add(SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security); hash.Add(SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout); hash.Add(SYNONYM.NET, KEY.Network_Library); hash.Add(SYNONYM.NETWORK, KEY.Network_Library); hash.Add(SYNONYM.Pwd, KEY.Password); hash.Add(SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info); hash.Add(SYNONYM.UID, KEY.User_ID); hash.Add(SYNONYM.User, KEY.User_ID); hash.Add(SYNONYM.WSID, KEY.Workstation_Id); Debug.Assert(SqlConnectionStringBuilder.KeywordsCount + SynonymCount == hash.Count, "incorrect initial ParseSynonyms size"); _sqlClientSynonyms = hash; } return hash; } internal string ObtainWorkstationId() { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. string result = WorkstationId; if (null == result) { // permission to obtain Environment.MachineName is Asserted // since permission to open the connection has been granted // the information is shared with the server, but not directly with the user result = ADP.MachineName(); ValidateValueLength(result, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } return result; } static internal Hashtable NetlibMapping() { const int NetLibCount = 8; Hashtable hash = _netlibMapping; if (null == hash) { hash = new Hashtable(NetLibCount); hash.Add(NETLIB.TCPIP, TdsEnums.TCP); hash.Add(NETLIB.NamedPipes, TdsEnums.NP); hash.Add(NETLIB.Multiprotocol, TdsEnums.RPC); hash.Add(NETLIB.BanyanVines, TdsEnums.BV); hash.Add(NETLIB.AppleTalk, TdsEnums.ADSP); hash.Add(NETLIB.IPXSPX, TdsEnums.SPX); hash.Add(NETLIB.VIA, TdsEnums.VIA); hash.Add(NETLIB.SharedMemory, TdsEnums.LPC); Debug.Assert(NetLibCount == hash.Count, "incorrect initial NetlibMapping size"); _netlibMapping = hash; } return hash; } static internal bool ValidProtocal (string protocal) { switch (protocal) { case TdsEnums.TCP : case TdsEnums.NP : case TdsEnums.VIA : case TdsEnums.LPC : return true; // case TdsEnums.RPC : Invalid Protocals // case TdsEnums.BV : // case TdsEnums.ADSP : // case TdsEnums.SPX : default : return false; } } private void ValidateValueLength (string value, int limit, string key) { if (limit < value.Length) { throw ADP.InvalidConnectionOptionValueLength(key, limit); } } internal static void VerifyLocalHostAndFixup(ref string host, bool enforceLocalHost, bool fixup) { if (ADP.IsEmpty(host)) { if (fixup) { host = "."; } } else if (!CompareHostName(ref host, @".", fixup) && !CompareHostName(ref host, @"(local)", fixup)) { // Fix-up completed in CompareHostName if return value true. string name = ADP.GetComputerNameDnsFullyQualified(); // i.e, machine.location.corp.company.com if (!CompareHostName(ref host, name, fixup)) { int separatorPos = name.IndexOf('.'); // to compare just 'machine' part if ((separatorPos <= 0) || !CompareHostName(ref host, name.Substring(0, separatorPos), fixup)) { if (enforceLocalHost) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } } } } } internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent() { object value = base.Parsetable[KEY.ApplicationIntent]; if (value == null) { return DEFAULT.ApplicationIntent; } // when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor, // wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool) try { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } // ArgumentException and other types are raised as is (no wrapping) } internal SqlAuthenticationMethod ConvertValueToAuthenticationType() { object value = base.Parsetable[KEY.Authentication]; string valStr = value as string; if (valStr == null) { return DEFAULT.Authentication; } try { return DbConnectionStringBuilderUtil.ConvertToAuthenticationType(KEY.Authentication, valStr); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.Authentication, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.Authentication, e); } } /// <summary> /// Convert the value to SqlConnectionColumnEncryptionSetting. /// </summary> /// <returns></returns> internal SqlConnectionColumnEncryptionSetting ConvertValueToColumnEncryptionSetting() { object value = base.Parsetable[KEY.ColumnEncryptionSetting]; string valStr = value as string; if (valStr == null) { return DEFAULT.ColumnEncryptionSetting; } try { return DbConnectionStringBuilderUtil.ConvertToColumnEncryptionSetting(KEY.ColumnEncryptionSetting, valStr); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ColumnEncryptionSetting, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ColumnEncryptionSetting, e); } } internal bool ConvertValueToEncrypt() { // If the Authentication keyword is provided, default to Encrypt=true; // otherwise keep old default for backwards compatibility object authValue = base.Parsetable[KEY.Authentication]; bool defaultEncryptValue = (authValue == null) ? DEFAULT.Encrypt : true; return ConvertValueToBoolean(KEY.Encrypt, defaultEncryptValue); } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using UnityEngine; using UnityEditor; using System; using System.Collections.Generic; namespace AmplifyShaderEditor { [Serializable] [NodeAttributes( "Substance Sample", "Textures", "Samples a procedural material", KeyCode.None, true, 0, typeof( SubstanceArchive ), typeof( ProceduralMaterial ) )] public sealed class SubstanceSamplerNode : PropertyNode { private const string GlobalVarDecStr = "uniform sampler2D {0};"; private const string PropertyDecStr = "{0}(\"{0}\", 2D) = \"white\""; private const string AutoNormalStr = "Auto-Normal"; private const string SubstanceStr = "Substance"; private float TexturePreviewSizeX = 128; private float TexturePreviewSizeY = 128; private float PickerPreviewSizeX = 128; private float PickerPreviewSizeY = 17; private float PickerPreviewWidthAdjust = 18; private CacheNodeConnections m_cacheNodeConnections; [SerializeField] private int m_firstOutputConnected = 0; [SerializeField] private ProceduralMaterial m_proceduralMaterial; [SerializeField] private int m_textureCoordSet = 0; [SerializeField] private ProceduralOutputType[] m_textureTypes; [SerializeField] private bool m_autoNormal = true; private Type m_type; private List<int> m_outputConns = new List<int>(); protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); AddInputPort( WirePortDataType.FLOAT2, false, "UV" ); AddOutputPort( WirePortDataType.COLOR, Constants.EmptyPortValue ); m_insideSize.Set( TexturePreviewSizeX + PickerPreviewWidthAdjust, TexturePreviewSizeY + PickerPreviewSizeY + 5 ); m_type = typeof( ProceduralMaterial ); m_currentParameterType = PropertyType.Property; m_freeType = false; m_freeName = false; m_autoWrapProperties = true; m_customPrefix = "Substance Sample "; m_drawPrecisionUI = false; m_showPreview = true; m_selectedLocation = PreviewLocation.TopCenter; m_cacheNodeConnections = new CacheNodeConnections(); } public override void OnOutputPortConnected( int portId, int otherNodeId, int otherPortId ) { base.OnOutputPortConnected( portId, otherNodeId, otherPortId ); m_firstOutputConnected = -1; } public override void OnOutputPortDisconnected( int portId ) { base.OnOutputPortDisconnected( portId ); m_firstOutputConnected = -1; } void CalculateFirstOutputConnected() { m_outputConns.Clear(); int count = m_outputPorts.Count; for ( int i = 0; i < count; i++ ) { if ( m_outputPorts[ i ].IsConnected ) { if ( m_firstOutputConnected < 0 ) m_firstOutputConnected = i; m_outputConns.Add( i ); } } if ( m_firstOutputConnected < 0 ) m_firstOutputConnected = 0; } public override void Draw( DrawInfo drawInfo ) { base.Draw( drawInfo ); Rect previewArea = m_remainingBox; previewArea.width = TexturePreviewSizeX * drawInfo.InvertedZoom; previewArea.height = TexturePreviewSizeY * drawInfo.InvertedZoom; previewArea.x += 0.5f * m_remainingBox.width - 0.5f * previewArea.width; GUI.Box( previewArea, string.Empty, UIUtils.ObjectFieldThumb ); Rect pickerArea = previewArea; pickerArea.width = PickerPreviewSizeX * drawInfo.InvertedZoom; pickerArea.height = PickerPreviewSizeY * drawInfo.InvertedZoom; pickerArea.y += previewArea.height; Texture[] textures = m_proceduralMaterial != null ? m_proceduralMaterial.GetGeneratedTextures() : null; if ( textures != null ) { if ( m_firstOutputConnected < 0 ) { CalculateFirstOutputConnected(); } else if ( textures.Length != m_textureTypes.Length ) { OnNewSubstanceSelected( textures ); } int texCount = m_outputConns.Count; previewArea.height /= texCount; for ( int i = 0; i < texCount; i++ ) { EditorGUI.DrawPreviewTexture( previewArea, textures[ m_outputConns[ i ] ], null, ScaleMode.ScaleAndCrop ); previewArea.y += previewArea.height; } } EditorGUI.BeginChangeCheck(); m_proceduralMaterial = EditorGUIObjectField( pickerArea, m_proceduralMaterial, m_type, false ) as ProceduralMaterial; if ( EditorGUI.EndChangeCheck() ) { textures = m_proceduralMaterial != null ? m_proceduralMaterial.GetGeneratedTextures() : null; OnNewSubstanceSelected( textures ); } } void OnNewSubstanceSelected( Texture[] textures ) { CacheCurrentSettings(); ConfigPortsFromMaterial( true, textures ); ConnectFromCache(); m_requireMaterialUpdate = true; CalculateFirstOutputConnected(); UIUtils.CurrentWindow.RequestRepaint(); } public override void DrawProperties() { base.DrawProperties(); EditorGUI.BeginChangeCheck(); m_proceduralMaterial = EditorGUILayoutObjectField( SubstanceStr, m_proceduralMaterial, m_type, false ) as ProceduralMaterial ; if ( EditorGUI.EndChangeCheck() ) { Texture[] textures = m_proceduralMaterial != null ? m_proceduralMaterial.GetGeneratedTextures() : null; if ( textures != null ) { OnNewSubstanceSelected( textures ); } } m_textureCoordSet = EditorGUILayoutIntPopup( Constants.AvailableUVSetsLabel, m_textureCoordSet, Constants.AvailableUVSetsStr, Constants.AvailableUVSets ); EditorGUI.BeginChangeCheck(); m_autoNormal = EditorGUILayoutToggle( AutoNormalStr, m_autoNormal ); if ( EditorGUI.EndChangeCheck() ) { for ( int i = 0; i < m_textureTypes.Length; i++ ) { WirePortDataType portType = ( m_autoNormal && m_textureTypes[ i ] == ProceduralOutputType.Normal ) ? WirePortDataType.FLOAT3 : WirePortDataType.COLOR; if ( m_outputPorts[ i ].DataType != portType ) { m_outputPorts[ i ].ChangeType( portType, false ); } } } } private void CacheCurrentSettings() { m_cacheNodeConnections.Clear(); for ( int portId = 0; portId < m_outputPorts.Count; portId++ ) { if ( m_outputPorts[ portId ].IsConnected ) { int connCount = m_outputPorts[ portId ].ConnectionCount; for ( int connIdx = 0; connIdx < connCount; connIdx++ ) { WireReference connection = m_outputPorts[ portId ].GetConnection( connIdx ); m_cacheNodeConnections.Add( m_outputPorts[ portId ].Name, new NodeCache( connection.NodeId, connection.PortId ) ); } } } } private void ConnectFromCache() { for ( int i = 0; i < m_outputPorts.Count; i++ ) { List<NodeCache> connections = m_cacheNodeConnections.GetList( m_outputPorts[ i ].Name ); if ( connections != null ) { int count = connections.Count; for ( int connIdx = 0; connIdx < count; connIdx++ ) { UIUtils.SetConnection( connections[ connIdx ].TargetNodeId, connections[ connIdx ].TargetPortId, m_uniqueId, i ); } } } } private void ConfigPortsFromMaterial( bool invalidateConnections = false, Texture[] newTextures = null ) { //PreviewSizeX = ( m_proceduralMaterial != null ) ? UIUtils.ObjectField.CalcSize( new GUIContent( m_proceduralMaterial.name ) ).x + 15 : 110; m_insideSize.x = TexturePreviewSizeX + 5; SetAdditonalTitleText( ( m_proceduralMaterial != null ) ? string.Format( Constants.PropertyValueLabel, m_proceduralMaterial.name ) : string.Empty ); Texture[] textures = newTextures != null ? newTextures : ( ( m_proceduralMaterial != null ) ? m_proceduralMaterial.GetGeneratedTextures() : null ); if ( textures != null ) { string nameToRemove = m_proceduralMaterial.name + "_"; m_textureTypes = new ProceduralOutputType[ textures.Length ]; for ( int i = 0; i < textures.Length; i++ ) { ProceduralTexture procTex = textures[ i ] as ProceduralTexture; m_textureTypes[ i ] = procTex.GetProceduralOutputType(); WirePortDataType portType = ( m_autoNormal && m_textureTypes[ i ] == ProceduralOutputType.Normal ) ? WirePortDataType.FLOAT3 : WirePortDataType.COLOR; string newName = textures[ i ].name.Replace( nameToRemove, string.Empty ); char firstLetter = Char.ToUpper( newName[ 0 ] ); newName = firstLetter.ToString() + newName.Substring( 1 ); if ( i < m_outputPorts.Count ) { m_outputPorts[ i ].ChangeProperties( newName, portType, false ); if ( invalidateConnections ) { m_outputPorts[ i ].FullDeleteConnections(); } } else { AddOutputPort( portType, newName ); } } if ( textures.Length < m_outputPorts.Count ) { int itemsToRemove = m_outputPorts.Count - textures.Length; for ( int i = 0; i < itemsToRemove; i++ ) { int idx = m_outputPorts.Count - 1; if ( m_outputPorts[ idx ].IsConnected ) { m_outputPorts[ idx ].ForceClearConnection(); } RemoveOutputPort( idx ); } } } else { int itemsToRemove = m_outputPorts.Count - 1; m_outputPorts[ 0 ].ChangeProperties( Constants.EmptyPortValue, WirePortDataType.COLOR, false ); m_outputPorts[ 0 ].ForceClearConnection(); for ( int i = 0; i < itemsToRemove; i++ ) { int idx = m_outputPorts.Count - 1; if ( m_outputPorts[ idx ].IsConnected ) { m_outputPorts[ idx ].ForceClearConnection(); } RemoveOutputPort( idx ); } } m_sizeIsDirty = true; m_isDirty = true; Event.current.Use(); } private void ConfigFromObject( UnityEngine.Object obj ) { ProceduralMaterial newMat = AssetDatabase.LoadAssetAtPath<ProceduralMaterial>( AssetDatabase.GetAssetPath( obj ) ); if ( newMat != null ) { m_proceduralMaterial = newMat; ConfigPortsFromMaterial(); } } public override void OnObjectDropped( UnityEngine.Object obj ) { ConfigFromObject( obj ); } public override void SetupFromCastObject( UnityEngine.Object obj ) { ConfigFromObject( obj ); } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar ) { if ( m_proceduralMaterial == null ) { return "(0).xxxx"; } if ( m_outputPorts[ outputId ].IsLocalValue ) { return m_outputPorts[ outputId ].LocalValue; } Texture[] textures = m_proceduralMaterial.GetGeneratedTextures(); string uvPropertyName = string.Empty; for ( int i = 0; i < m_outputPorts.Count; i++ ) { if ( m_outputPorts[ i ].IsConnected ) { uvPropertyName = textures[ i ].name; break; } } string name = textures[ outputId ].name + m_uniqueId; dataCollector.AddToUniforms( m_uniqueId, string.Format( GlobalVarDecStr, textures[ outputId ].name ) ); dataCollector.AddToProperties( m_uniqueId, string.Format( PropertyDecStr, textures[ outputId ].name ) + "{}", -1 ); bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ); string value = string.Format( "tex2D{0}( {1}, {2})", ( isVertex ? "lod" : string.Empty ), textures[ outputId ].name, GetUVCoords( ref dataCollector, ignoreLocalvar, uvPropertyName ) ); if ( m_autoNormal && m_textureTypes[ outputId ] == ProceduralOutputType.Normal ) { value = string.Format( Constants.UnpackNormal, value ); } dataCollector.AddPropertyNode( this ); RegisterLocalVariable( outputId, value, ref dataCollector, name ); return m_outputPorts[ outputId ].LocalValue; } public string GetUVCoords( ref MasterNodeDataCollector dataCollector, bool ignoreLocalVar, string propertyName ) { bool isVertex = ( dataCollector.PortCategory == MasterNodePortCategory.Vertex || dataCollector.PortCategory == MasterNodePortCategory.Tessellation ); if ( m_inputPorts[ 0 ].IsConnected ) { return m_inputPorts[ 0 ].GenerateShaderForOutput( ref dataCollector, isVertex ? WirePortDataType.FLOAT4 : WirePortDataType.FLOAT2, ignoreLocalVar, true ); } else { string vertexCoords = Constants.VertexShaderInputStr + ".texcoord"; if ( m_textureCoordSet > 0 ) { vertexCoords += m_textureCoordSet.ToString(); } string uvChannelName = IOUtils.GetUVChannelName( propertyName, m_textureCoordSet ); string dummyPropUV = "_texcoord" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ); string dummyUV = "uv" + ( m_textureCoordSet > 0 ? ( m_textureCoordSet + 1 ).ToString() : "" ) + dummyPropUV; dataCollector.AddToUniforms( m_uniqueId, "uniform float4 " + propertyName + "_ST;" ); dataCollector.AddToProperties( m_uniqueId, "[HideInInspector] " + dummyPropUV + "( \"\", 2D ) = \"white\" {}", 100 ); dataCollector.AddToInput( m_uniqueId, "float2 " + dummyUV, true ); if ( isVertex ) { dataCollector.AddToVertexLocalVariables( m_uniqueId, "float4 " + uvChannelName + " = float4(" + vertexCoords + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw, 0 ,0);" ); return uvChannelName; } else dataCollector.AddToLocalVariables( m_uniqueId, PrecisionType.Float, WirePortDataType.FLOAT2, uvChannelName, Constants.InputVarStr + "." + dummyUV + " * " + propertyName + "_ST.xy + " + propertyName + "_ST.zw" ); return uvChannelName; } } public override void UpdateMaterial( Material mat ) { base.UpdateMaterial( mat ); if ( m_proceduralMaterial != null ) { Texture[] textures = m_proceduralMaterial.GetGeneratedTextures(); for ( int i = 0; i < textures.Length; i++ ) { if ( mat.HasProperty( textures[ i ].name ) ) { mat.SetTexture( textures[ i ].name, textures[ i ] ); } } } } public override bool UpdateShaderDefaults( ref Shader shader, ref TextureDefaultsDataColector defaultCol ) { if ( m_proceduralMaterial != null ) { Texture[] textures = m_proceduralMaterial.GetGeneratedTextures(); for ( int i = 0; i < textures.Length; i++ ) { defaultCol.AddValue( textures[ i ].name, textures[ i ] ); } } return true; } public override void Destroy() { base.Destroy(); m_proceduralMaterial = null; m_cacheNodeConnections.Clear(); m_cacheNodeConnections = null; m_outputConns.Clear(); m_outputConns = null; } public override string GetPropertyValStr() { return m_proceduralMaterial ? m_proceduralMaterial.name : string.Empty; } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); string guid = GetCurrentParam( ref nodeParams ); m_textureCoordSet = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); m_autoNormal = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ); if ( guid.Length > 1 ) { m_proceduralMaterial = AssetDatabase.LoadAssetAtPath<ProceduralMaterial>( AssetDatabase.GUIDToAssetPath( guid ) ); if ( m_proceduralMaterial != null ) { ConfigPortsFromMaterial(); } else { UIUtils.ShowMessage( "Substance not found ", MessageSeverity.Error ); } } } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); string guid = ( m_proceduralMaterial != null ) ? AssetDatabase.AssetPathToGUID( AssetDatabase.GetAssetPath( m_proceduralMaterial ) ) : "0"; IOUtils.AddFieldValueToString( ref nodeInfo, guid ); IOUtils.AddFieldValueToString( ref nodeInfo, m_textureCoordSet ); IOUtils.AddFieldValueToString( ref nodeInfo, m_autoNormal ); } } }
using System; using Csla; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D09_Region_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="D09_Region_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D08_Region"/> collection. /// </remarks> [Serializable] public partial class D09_Region_ReChild : BusinessBase<D09_Region_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name"); /// <summary> /// Gets or sets the Cities Child Name. /// </summary> /// <value>The Cities Child Name.</value> public string Region_Child_Name { get { return GetProperty(Region_Child_NameProperty); } set { SetProperty(Region_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D09_Region_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="D09_Region_ReChild"/> object.</returns> internal static D09_Region_ReChild NewD09_Region_ReChild() { return DataPortal.CreateChild<D09_Region_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="D09_Region_ReChild"/> object, based on given parameters. /// </summary> /// <param name="region_ID2">The Region_ID2 parameter of the D09_Region_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="D09_Region_ReChild"/> object.</returns> internal static D09_Region_ReChild GetD09_Region_ReChild(int region_ID2) { return DataPortal.FetchChild<D09_Region_ReChild>(region_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D09_Region_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D09_Region_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D09_Region_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D09_Region_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="region_ID2">The Region ID2.</param> protected void Child_Fetch(int region_ID2) { var args = new DataPortalHookArgs(region_ID2); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<ID09_Region_ReChildDal>(); var data = dal.Fetch(region_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } /// <summary> /// Loads a <see cref="D09_Region_ReChild"/> object from the given <see cref="D09_Region_ReChildDto"/>. /// </summary> /// <param name="data">The D09_Region_ReChildDto to use.</param> private void Fetch(D09_Region_ReChildDto data) { // Value properties LoadProperty(Region_Child_NameProperty, data.Region_Child_Name); var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D09_Region_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D08_Region parent) { var dto = new D09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<ID09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="D09_Region_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(D08_Region parent) { if (!IsDirty) return; var dto = new D09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<ID09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="D09_Region_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(D08_Region parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<ID09_Region_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Region_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #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.Runtime.InteropServices; namespace System.Buffers.Text { public static partial class CustomParser { public static bool TryParseByte(ReadOnlySpan<byte> text, out byte value, out int bytesConsumed, StandardFormat format = default, SymbolTable symbolTable = null) { symbolTable = symbolTable ?? SymbolTable.InvariantUtf8; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (symbolTable == SymbolTable.InvariantUtf8) { if (Parsers.IsHexFormat(format)) { return Utf8Parser.TryParse(text, out value, out bytesConsumed, 'X'); } else { return Utf8Parser.TryParse(text, out value, out bytesConsumed); } } else if (symbolTable == SymbolTable.InvariantUtf16) { ReadOnlySpan<char> utf16Text = MemoryMarshal.Cast<byte, char>(text); int charactersConsumed; bool result; if (Parsers.IsHexFormat(format)) { result = Utf16Parser.Hex.TryParseByte(utf16Text, out value, out charactersConsumed); } else { result = Utf16Parser.TryParseByte(utf16Text, out value, out charactersConsumed); } bytesConsumed = charactersConsumed * sizeof(char); return result; } if (Parsers.IsHexFormat(format)) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } if (!symbolTable.TryParse(text, out SymbolTable.Symbol nextSymbol, out int thisSymbolConsumed)) { value = default; bytesConsumed = 0; return false; } if (nextSymbol > SymbolTable.Symbol.D9) { value = default; bytesConsumed = 0; return false; } uint parsedValue = (uint)nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > SymbolTable.Symbol.D9) { bytesConsumed = index; value = (byte)parsedValue; return true; } // If parsedValue > (byte.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (byte.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > byte.MaxValue / 10 || (parsedValue == byte.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5)) { bytesConsumed = 0; value = default; return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + (uint)nextSymbol; } bytesConsumed = text.Length; value = (byte)parsedValue; return true; } public static bool TryParseUInt16(ReadOnlySpan<byte> text, out ushort value, out int bytesConsumed, StandardFormat format = default, SymbolTable symbolTable = null) { symbolTable = symbolTable ?? SymbolTable.InvariantUtf8; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (symbolTable == SymbolTable.InvariantUtf8) { if (Parsers.IsHexFormat(format)) { return Utf8Parser.TryParse(text, out value, out bytesConsumed, 'X'); } else { return Utf8Parser.TryParse(text, out value, out bytesConsumed); } } else if (symbolTable == SymbolTable.InvariantUtf16) { ReadOnlySpan<char> utf16Text = MemoryMarshal.Cast<byte, char>(text); int charactersConsumed; bool result; if (Parsers.IsHexFormat(format)) { result = Utf16Parser.Hex.TryParseUInt16(utf16Text, out value, out charactersConsumed); } else { result = Utf16Parser.TryParseUInt16(utf16Text, out value, out charactersConsumed); } bytesConsumed = charactersConsumed * sizeof(char); return result; } if (Parsers.IsHexFormat(format)) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } if (!symbolTable.TryParse(text, out SymbolTable.Symbol nextSymbol, out int thisSymbolConsumed)) { value = default; bytesConsumed = 0; return false; } if (nextSymbol > SymbolTable.Symbol.D9) { value = default; bytesConsumed = 0; return false; } uint parsedValue = (uint)nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > SymbolTable.Symbol.D9) { bytesConsumed = index; value = (ushort)parsedValue; return true; } // If parsedValue > (ushort.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (ushort.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > ushort.MaxValue / 10 || (parsedValue == ushort.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5)) { bytesConsumed = 0; value = default; return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + (uint)nextSymbol; } bytesConsumed = text.Length; value = (ushort)parsedValue; return true; } public static bool TryParseUInt32(ReadOnlySpan<byte> text, out uint value, out int bytesConsumed, StandardFormat format = default, SymbolTable symbolTable = null) { symbolTable = symbolTable ?? SymbolTable.InvariantUtf8; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (symbolTable == SymbolTable.InvariantUtf8) { if (Parsers.IsHexFormat(format)) { return Utf8Parser.TryParse(text, out value, out bytesConsumed, 'X'); } else { return Utf8Parser.TryParse(text, out value, out bytesConsumed); } } else if (symbolTable == SymbolTable.InvariantUtf16) { ReadOnlySpan<char> utf16Text = MemoryMarshal.Cast<byte, char>(text); int charactersConsumed; bool result; if (Parsers.IsHexFormat(format)) { result = Utf16Parser.Hex.TryParseUInt32(utf16Text, out value, out charactersConsumed); } else { result = Utf16Parser.TryParseUInt32(utf16Text, out value, out charactersConsumed); } bytesConsumed = charactersConsumed * sizeof(char); return result; } if (Parsers.IsHexFormat(format)) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } if (!symbolTable.TryParse(text, out SymbolTable.Symbol nextSymbol, out int thisSymbolConsumed)) { value = default; bytesConsumed = 0; return false; } if (nextSymbol > SymbolTable.Symbol.D9) { value = default; bytesConsumed = 0; return false; } uint parsedValue = (uint)nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > SymbolTable.Symbol.D9) { bytesConsumed = index; value = (uint)parsedValue; return true; } // If parsedValue > (uint.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (uint.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > uint.MaxValue / 10 || (parsedValue == uint.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5)) { bytesConsumed = 0; value = default; return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + (uint)nextSymbol; } bytesConsumed = text.Length; value = (uint)parsedValue; return true; } public static bool TryParseUInt64(ReadOnlySpan<byte> text, out ulong value, out int bytesConsumed, StandardFormat format = default, SymbolTable symbolTable = null) { symbolTable = symbolTable ?? SymbolTable.InvariantUtf8; if (!format.IsDefault && format.HasPrecision) { throw new NotImplementedException("Format with precision not supported."); } if (symbolTable == SymbolTable.InvariantUtf8) { if (Parsers.IsHexFormat(format)) { return Utf8Parser.TryParse(text, out value, out bytesConsumed, 'X'); } else { return Utf8Parser.TryParse(text, out value, out bytesConsumed); } } else if (symbolTable == SymbolTable.InvariantUtf16) { ReadOnlySpan<char> utf16Text = MemoryMarshal.Cast<byte, char>(text); int charactersConsumed; bool result; if (Parsers.IsHexFormat(format)) { result = Utf16Parser.Hex.TryParseUInt64(utf16Text, out value, out charactersConsumed); } else { result = Utf16Parser.TryParseUInt64(utf16Text, out value, out charactersConsumed); } bytesConsumed = charactersConsumed * sizeof(char); return result; } if (Parsers.IsHexFormat(format)) { throw new NotImplementedException("The only supported encodings for hexadecimal parsing are InvariantUtf8 and InvariantUtf16."); } if (!(format.IsDefault || format.Symbol == 'G' || format.Symbol == 'g')) { throw new NotImplementedException(String.Format("Format '{0}' not supported.", format.Symbol)); } if (!symbolTable.TryParse(text, out SymbolTable.Symbol nextSymbol, out int thisSymbolConsumed)) { value = default; bytesConsumed = 0; return false; } if (nextSymbol > SymbolTable.Symbol.D9) { value = default; bytesConsumed = 0; return false; } ulong parsedValue = (uint)nextSymbol; int index = thisSymbolConsumed; while (index < text.Length) { bool success = symbolTable.TryParse(text.Slice(index), out nextSymbol, out thisSymbolConsumed); if (!success || nextSymbol > SymbolTable.Symbol.D9) { bytesConsumed = index; value = (ulong)parsedValue; return true; } // If parsedValue > (ulong.MaxValue / 10), any more appended digits will cause overflow. // if parsedValue == (ulong.MaxValue / 10), any nextDigit greater than 5 implies overflow. if (parsedValue > ulong.MaxValue / 10 || (parsedValue == ulong.MaxValue / 10 && nextSymbol > SymbolTable.Symbol.D5)) { bytesConsumed = 0; value = default; return false; } index += thisSymbolConsumed; parsedValue = parsedValue * 10 + (uint)nextSymbol; } bytesConsumed = text.Length; value = (ulong)parsedValue; return true; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// The List OS Images operation response. /// </summary> public partial class VirtualMachineImageListResponse : OperationResponse, IEnumerable<VirtualMachineImageListResponse.VirtualMachineImage> { private IList<VirtualMachineImageListResponse.VirtualMachineImage> _images; /// <summary> /// The virtual machine images associated with your subscription. /// </summary> public IList<VirtualMachineImageListResponse.VirtualMachineImage> Images { get { return this._images; } set { this._images = value; } } /// <summary> /// Initializes a new instance of the VirtualMachineImageListResponse /// class. /// </summary> public VirtualMachineImageListResponse() { this._images = new List<VirtualMachineImageListResponse.VirtualMachineImage>(); } /// <summary> /// Gets the sequence of Images. /// </summary> public IEnumerator<VirtualMachineImageListResponse.VirtualMachineImage> GetEnumerator() { return this.Images.GetEnumerator(); } /// <summary> /// Gets the sequence of Images. /// </summary> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// A virtual machine image associated with your subscription. /// </summary> public partial class VirtualMachineImage { private string _affinityGroup; /// <summary> /// The affinity in which the media is located. The AffinityGroup /// value is derived from storage account that contains the blob /// in which the media is located. If the storage account does not /// belong to an affinity group the value is NULL and the element /// is not displayed in the response. This value is NULL for /// platform images. /// </summary> public string AffinityGroup { get { return this._affinityGroup; } set { this._affinityGroup = value; } } private string _category; /// <summary> /// The repository classification of the image. All user images /// have the category User. /// </summary> public string Category { get { return this._category; } set { this._category = value; } } private string _description; /// <summary> /// Specifies the description of the image. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _eula; /// <summary> /// Specifies the End User License Agreement that is associated /// with the image. The value for this element is a string, but it /// is recommended that the value be a URL that points to a EULA. /// </summary> public string Eula { get { return this._eula; } set { this._eula = value; } } private string _imageFamily; /// <summary> /// Specifies a value that can be used to group images. /// </summary> public string ImageFamily { get { return this._imageFamily; } set { this._imageFamily = value; } } private bool? _isPremium; /// <summary> /// Indicates whether the image contains software or associated /// services that will incur charges above the core price for the /// virtual machine. For additional details, see the /// PricingDetailLink element. /// </summary> public bool? IsPremium { get { return this._isPremium; } set { this._isPremium = value; } } private string _label; /// <summary> /// An identifier for the image. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _language; /// <summary> /// Specifies the language of the image. The Language element is /// only available using version 2013-03-01 or higher. /// </summary> public string Language { get { return this._language; } set { this._language = value; } } private string _location; /// <summary> /// The geo-location in which this media is located. The Location /// value is derived from storage account that contains the blob /// in which the media is located. If the storage account belongs /// to an affinity group the value is NULL. If the version is set /// to 2012-08-01 or later, the locations are returned for /// platform images; otherwise, this value is NULL for platform /// images. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private double _logicalSizeInGB; /// <summary> /// The size, in GB, of the image. /// </summary> public double LogicalSizeInGB { get { return this._logicalSizeInGB; } set { this._logicalSizeInGB = value; } } private Uri _mediaLinkUri; /// <summary> /// The location of the blob in Windows Azure storage. The blob /// location belongs to a storage account in the subscription /// specified by the SubscriptionId value in the operation call. /// Example: /// http://example.blob.core.windows.net/disks/myimage.vhd /// </summary> public Uri MediaLinkUri { get { return this._mediaLinkUri; } set { this._mediaLinkUri = value; } } private string _name; /// <summary> /// The name of the operating system image. This is the name that /// is used when creating one or more virtual machines using the /// image. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _operatingSystemType; /// <summary> /// The operating system type of the OS image. Possible values are: /// Linux, Windows. /// </summary> public string OperatingSystemType { get { return this._operatingSystemType; } set { this._operatingSystemType = value; } } private Uri _pricingDetailUri; /// <summary> /// Specifies a URL for an image with IsPremium set to true, which /// contains the pricing details for a virtual machine that is /// created from the image. The PricingDetailLink element is only /// available using version 2012-12-01 or higher. /// </summary> public Uri PricingDetailUri { get { return this._pricingDetailUri; } set { this._pricingDetailUri = value; } } private Uri _privacyUri; /// <summary> /// Specifies the URI that points to a document that contains the /// privacy policy related to the image. /// </summary> public Uri PrivacyUri { get { return this._privacyUri; } set { this._privacyUri = value; } } private DateTime _publishedDate; /// <summary> /// Specifies the date when the image was added to the image /// repository. /// </summary> public DateTime PublishedDate { get { return this._publishedDate; } set { this._publishedDate = value; } } private string _publisherName; /// <summary> /// The name of the publisher of this OS Image in Windows Azure. /// </summary> public string PublisherName { get { return this._publisherName; } set { this._publisherName = value; } } private string _recommendedVMSize; /// <summary> /// Optional. Specifies the size to use for the virtual machine /// that is created from the OS image. /// </summary> public string RecommendedVMSize { get { return this._recommendedVMSize; } set { this._recommendedVMSize = value; } } private Uri _smallIconUri; /// <summary> /// Specifies the URI to the small icon that is displayed when the /// image is presented in the Windows Azure Management Portal. /// The SmallIconUri element is only available using version /// 2013-03-01 or higher. /// </summary> public Uri SmallIconUri { get { return this._smallIconUri; } set { this._smallIconUri = value; } } /// <summary> /// Initializes a new instance of the VirtualMachineImage class. /// </summary> public VirtualMachineImage() { } } } }
using System; using System.Collections; using System.Web; using System.Xml; using StackExchange.Profiling; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Web; using Umbraco.Core.Profiling; using Umbraco.Core.Strings; namespace umbraco { /// <summary> /// /// </summary> public class item { private String _fieldContent = ""; private readonly String _fieldName; public String FieldContent { get { return _fieldContent; } } public item(string itemValue, IDictionary attributes) { _fieldContent = itemValue; ParseItem(attributes); } /// <summary> /// Creates a new Legacy item /// </summary> /// <param name="elements"></param> /// <param name="attributes"></param> public item(IDictionary elements, IDictionary attributes) : this(null, elements, attributes) { } /// <summary> /// Creates an Item with a publishedContent item in order to properly recurse and return the value. /// </summary> /// <param name="publishedContent"></param> /// <param name="elements"></param> /// <param name="attributes"></param> /// <remarks> /// THIS ENTIRE CLASS WILL BECOME LEGACY, THE FIELD RENDERING NEEDS TO BE REPLACES SO THAT IS WHY THIS /// CTOR IS INTERNAL. /// </remarks> internal item(IPublishedContent publishedContent, IDictionary elements, IDictionary attributes) { _fieldName = helper.FindAttribute(attributes, "field"); if (_fieldName.StartsWith("#")) { _fieldContent = library.GetDictionaryItem(_fieldName.Substring(1, _fieldName.Length - 1)); } else { // Loop through XML children we need to find the fields recursive var recursive = helper.FindAttribute(attributes, "recursive") == "true"; if (publishedContent == null) { if (recursive) { var recursiveVal = GetRecursiveValueLegacy(elements); _fieldContent = recursiveVal.IsNullOrWhiteSpace() ? _fieldContent : recursiveVal; } } //check for published content and get its value using that if (publishedContent != null && (publishedContent.HasProperty(_fieldName) || recursive)) { var pval = publishedContent.GetPropertyValue(_fieldName, recursive); var rval = pval == null ? string.Empty : pval.ToString(); _fieldContent = rval.IsNullOrWhiteSpace() ? _fieldContent : rval; } else { //get the vaue the legacy way (this will not parse locallinks, etc... since that is handled with ipublishedcontent) var elt = elements[_fieldName]; if (elt != null && string.IsNullOrEmpty(elt.ToString()) == false) _fieldContent = elt.ToString().Trim(); } //now we check if the value is still empty and if so we'll check useIfEmpty if (string.IsNullOrEmpty(_fieldContent)) { var altFieldName = helper.FindAttribute(attributes, "useIfEmpty"); if (string.IsNullOrEmpty(altFieldName) == false) { if (publishedContent != null && (publishedContent.HasProperty(altFieldName) || recursive)) { var pval = publishedContent.GetPropertyValue(altFieldName, recursive); var rval = pval == null ? string.Empty : pval.ToString(); _fieldContent = rval.IsNullOrWhiteSpace() ? _fieldContent : rval; } else { //get the vaue the legacy way (this will not parse locallinks, etc... since that is handled with ipublishedcontent) var elt = elements[altFieldName]; if (elt != null && string.IsNullOrEmpty(elt.ToString()) == false) _fieldContent = elt.ToString().Trim(); } } } } ParseItem(attributes); } /// <summary> /// Returns the recursive value using a legacy strategy of looking at the xml cache and the splitPath in the elements collection /// </summary> /// <param name="elements"></param> /// <returns></returns> private string GetRecursiveValueLegacy(IDictionary elements) { using (DisposableTimer.DebugDuration<item>("Checking recusively")) { var content = ""; var umbracoXml = presentation.UmbracoContext.Current.GetXml(); var splitpath = (String[])elements["splitpath"]; for (int i = 0; i < splitpath.Length - 1; i++) { XmlNode element = umbracoXml.GetElementById(splitpath[splitpath.Length - i - 1]); if (element == null) continue; var xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "./{0}"; var currentNode = element.SelectSingleNode(string.Format(xpath, _fieldName)); //continue if all is null if (currentNode == null || currentNode.FirstChild == null || string.IsNullOrEmpty(currentNode.FirstChild.Value) || string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim())) continue; HttpContext.Current.Trace.Write("item.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]); content = currentNode.FirstChild.Value; break; } return content; } } private void ParseItem(IDictionary attributes) { using (DisposableTimer.DebugDuration<item>("Start parsing " + _fieldName)) { HttpContext.Current.Trace.Write("item", "Start parsing '" + _fieldName + "'"); if (helper.FindAttribute(attributes, "textIfEmpty") != "" && _fieldContent == "") _fieldContent = helper.FindAttribute(attributes, "textIfEmpty"); _fieldContent = _fieldContent.Trim(); // DATE FORMATTING FUNCTIONS if (helper.FindAttribute(attributes, "formatAsDateWithTime") == "true") { if (_fieldContent == "") _fieldContent = DateTime.Now.ToString(); _fieldContent = Convert.ToDateTime(_fieldContent).ToLongDateString() + helper.FindAttribute(attributes, "formatAsDateWithTimeSeparator") + Convert.ToDateTime(_fieldContent).ToShortTimeString(); } else if (helper.FindAttribute(attributes, "formatAsDate") == "true") { if (_fieldContent == "") _fieldContent = DateTime.Now.ToString(); _fieldContent = Convert.ToDateTime(_fieldContent).ToLongDateString(); } // TODO: Needs revision to check if parameter-tags has attributes if (helper.FindAttribute(attributes, "stripParagraph") == "true" && _fieldContent.Length > 5) { _fieldContent = _fieldContent.Trim(); string fieldContentLower = _fieldContent.ToLower(); // the field starts with an opening p tag if (fieldContentLower.Substring(0, 3) == "<p>" // it ends with a closing p tag && fieldContentLower.Substring(_fieldContent.Length - 4, 4) == "</p>" // it doesn't contain multiple p-tags && fieldContentLower.IndexOf("<p>", 1) < 0) { _fieldContent = _fieldContent.Substring(3, _fieldContent.Length - 7); } } // CASING if (helper.FindAttribute(attributes, "case") == "lower") _fieldContent = _fieldContent.ToLower(); else if (helper.FindAttribute(attributes, "case") == "upper") _fieldContent = _fieldContent.ToUpper(); else if (helper.FindAttribute(attributes, "case") == "title") _fieldContent = _fieldContent.ToCleanString(CleanStringType.Ascii | CleanStringType.Alias | CleanStringType.PascalCase); // OTHER FORMATTING FUNCTIONS // If we use masterpages, this is moved to the ItemRenderer to add support for before/after in inline XSLT if (!UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages) { if (_fieldContent != "" && helper.FindAttribute(attributes, "insertTextBefore") != "") _fieldContent = HttpContext.Current.Server.HtmlDecode(helper.FindAttribute(attributes, "insertTextBefore")) + _fieldContent; if (_fieldContent != "" && helper.FindAttribute(attributes, "insertTextAfter") != "") _fieldContent += HttpContext.Current.Server.HtmlDecode(helper.FindAttribute(attributes, "insertTextAfter")); } if (helper.FindAttribute(attributes, "urlEncode") == "true") _fieldContent = HttpUtility.UrlEncode(_fieldContent); if (helper.FindAttribute(attributes, "htmlEncode") == "true") _fieldContent = HttpUtility.HtmlEncode(_fieldContent); if (helper.FindAttribute(attributes, "convertLineBreaks") == "true") _fieldContent = _fieldContent.Replace("\n", "<br/>\n"); HttpContext.Current.Trace.Write("item", "Done parsing '" + _fieldName + "'"); } } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.IO; using System.Reflection; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VsSDK.UnitTestLibrary; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using MSBuild = Microsoft.Build.BuildEngine; using OleServiceProvider = Microsoft.VsSDK.UnitTestLibrary.OleServiceProvider; namespace Microsoft.VisualStudio.Project.Samples.NestedProject.UnitTests { /// <summary> ///This is a test class for VisualStudio.Project.Samples.NestedProject.NestedProjectNode and is intended ///to contain all VisualStudio.Project.Samples.NestedProject.NestedProjectNode Unit Tests ///</summary> [TestClass()] public class NestedProjectNodeTest : BaseTest { [ClassInitialize] public static void TestClassInitialize(TestContext context) { fullPathToClassTemplateFile = Path.Combine(context.TestDeploymentDir, fullPathToClassTemplateFile); fullPathToProjectFile = Path.Combine(context.TestDeploymentDir, fullPathToProjectFile); fullPathToTargetFile = Path.Combine(context.TestDeploymentDir, fullPathToTargetFile); } #region Test Methods /// <summary> ///A test for AddFileFromTemplate (string, string) ///</summary> [TestMethod()] public void AddFileFromTemplateTest() { NestedProjectNode target = projectNode; target.AddFileFromTemplate(fullPathToClassTemplateFile, fullPathToTargetFile); } /// <summary> ///A test for GetAutomationObject () ///</summary> [TestMethod()] public void GetAutomationObjectTest() { NestedProjectNode target = projectNode; object actual = target.GetAutomationObject(); Assert.IsNotNull(actual, "Failed to initialize an AutomationObject for " + "NestedProjectNode within GetAutomationObject method"); } /// <summary> ///A test for GetConfigurationDependentPropertyPages () ///</summary> [TestMethod()] public void GetConfigurationDependentPropertyPagesTest() { NestedProjectNode target = projectNode; VisualStudio_Project_Samples_NestedProjectNodeAccessor accessor = new VisualStudio_Project_Samples_NestedProjectNodeAccessor(target); Guid[] expected = new Guid[] { new Guid("C43AD3DC-7468-48e1-B4D2-AAC0C74A0109") }; Guid[] actual; actual = accessor.GetConfigurationDependentPropertyPages(); CollectionAssert.AreEqual(expected, actual, "Microsoft.VisualStudio.Project.Samples.NestedProject.NestedProjectNode.GetConfigurationDepe" + "ndentPropertyPages did not return the expected value."); } /// <summary> ///A test for GetConfigurationIndependentPropertyPages () ///</summary> [TestMethod()] public void GetConfigurationIndependentPropertyPagesTest() { NestedProjectNode target = new NestedProjectNode(); VisualStudio_Project_Samples_NestedProjectNodeAccessor accessor = new VisualStudio_Project_Samples_NestedProjectNodeAccessor(target); Guid[] actual; actual = accessor.GetConfigurationIndependentPropertyPages(); Assert.IsTrue(actual != null && actual.Length > 0, "The result of GetConfigurationIndependentPropertyPages was unexpected."); Assert.IsTrue(actual[0].Equals(typeof(GeneralPropertyPage).GUID), "The value of collection returned by GetConfigurationIndependentPropertyPages is unexpected."); } /// <summary> ///A test for GetFormatList (out string) ///</summary> [TestMethod()] public void GetFormatListTest() { NestedProjectNode target = new NestedProjectNode(); string ppszFormatList; int expected = VSConstants.S_OK; int actual; actual = target.GetFormatList(out ppszFormatList); Assert.IsFalse(String.IsNullOrEmpty(ppszFormatList), "[out] ppszFormatList in GetFormatList() method was not set correctly."); Assert.AreEqual(expected, actual, "Microsoft.VisualStudio.Project.Samples.NestedProject.NestedProjectNode.GetFormatList did no" + "t return the expected value."); } /// <summary> ///A test for GetPriorityProjectDesignerPages () ///</summary> [TestMethod()] public void GetPriorityProjectDesignerPagesTest() { NestedProjectNode target = new NestedProjectNode(); VisualStudio_Project_Samples_NestedProjectNodeAccessor accessor = new VisualStudio_Project_Samples_NestedProjectNodeAccessor(target); Guid[] actual; actual = accessor.GetPriorityProjectDesignerPages(); Assert.IsTrue(actual != null && actual.Length > 0, "The result of GetConfigurationIndependentPropertyPages was unexpected."); Assert.IsTrue(actual[0].Equals(typeof(GeneralPropertyPage).GUID), "The value of collection returned by GetConfigurationIndependentPropertyPages is unexpected."); } /// <summary> ///A test for NestedProjectNode () ///</summary> [TestMethod()] public void ConstructorTest() { NestedProjectNode target = new NestedProjectNode(); Assert.IsNotNull(target, "Failed to initialize new instance of NestedProjectNode"); } /// <summary> ///A test for ProjectGuid ///</summary> [TestMethod()] public void ProjectGuidTest() { NestedProjectNode target = projectNode; Guid val = new Guid(GuidStrings.GuidNestedProjectFactory); Assert.AreEqual(val, target.ProjectGuid, "NestedProjectNode.ProjectGuid was not set correctly."); } /// <summary> ///A test for ProjectType ///</summary> [TestMethod()] public void ProjectTypeTest() { NestedProjectNode target = new NestedProjectNode(); string val = typeof(NestedProjectNode).Name; Assert.AreEqual(val, target.ProjectType, "Microsoft.VisualStudio.Project.Samples.NestedProject.NestedProjectNode.ProjectType was not " + "set correctly."); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------------------------ // </copyright> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System.Reflection; using System.Collections; using System.IO; using System.Xml.Schema; using System; using System.Text; using System.Threading; using System.Globalization; using System.Security; using System.Diagnostics; using System.CodeDom.Compiler; using System.Collections.Generic; using Hashtable = System.Collections.IDictionary; using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants; using XmlDeserializationEvents = System.Object; /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' /> ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public abstract class XmlSerializerImplementation { /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' /> public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' /> public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' /> public virtual IDictionary ReadMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' /> public virtual IDictionary WriteMethods { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' /> public virtual IDictionary TypedSerializers { get { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' /> public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' /> public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlSerializer { private TempAssembly _tempAssembly; private bool _typedSerializer; private Type _primitiveType; private XmlMapping _mapping; private XmlDeserializationEvents _events = new XmlDeserializationEvents(); #if NET_NATIVE private XmlSerializer innerSerializer; private readonly Type rootType; #endif private static TempAssemblyCache s_cache = new TempAssemblyCache(); private static volatile XmlSerializerNamespaces s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get { if (s_defaultNamespaces == null) { XmlSerializerNamespaces nss = new XmlSerializerNamespaces(); nss.AddInternal("xsi", XmlSchema.InstanceNamespace); nss.AddInternal("xsd", XmlSchema.Namespace); if (s_defaultNamespaces == null) { s_defaultNamespaces = nss; } } return s_defaultNamespaces; } } private static InternalHashtable s_xmlSerializerTable = new InternalHashtable(); /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' /> ///<internalonly/> protected XmlSerializer() { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> #if !NET_NATIVE public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null, null) #else public XmlSerializer(Type type, Type[] extraTypes) : this(type) #endif // NET_NATIVE { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null, null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(XmlTypeMapping xmlTypeMapping) { _tempAssembly = GenerateTempAssembly(xmlTypeMapping); _mapping = xmlTypeMapping; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type) : this(type, (string)null) { } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, string defaultNamespace) { if (type == null) throw new ArgumentNullException("type"); // The ctor is not supported, but we cannot throw PNSE unconditionally // because the ctor is used by ctor(Type) which passes in a null defaultNamespace. if (!string.IsNullOrEmpty(defaultNamespace)) { throw new PlatformNotSupportedException(); } #if NET_NATIVE rootType = type; #endif _mapping = GetKnownMapping(type, defaultNamespace); if (_mapping != null) { _primitiveType = type; return; } #if !NET_NATIVE _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { lock (s_cache) { _tempAssembly = s_cache[defaultNamespace, type]; if (_tempAssembly == null) { { // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); } } s_cache.Add(defaultNamespace, type, _tempAssembly); } } if (_mapping == null) { _mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace); } #else XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly(); if (contract != null) { this.innerSerializer = contract.GetSerializer(type); } #endif } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence) { throw new PlatformNotSupportedException(); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) { if (xmlMapping == null) throw new ArgumentNullException("xmlMapping"); return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, null, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o) { Serialize(textWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings); Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o) { Serialize(stream, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; XmlWriter xmlWriter = XmlWriter.Create(stream, settings); Serialize(xmlWriter, o, namespaces); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o) { Serialize(xmlWriter, o, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { Serialize(xmlWriter, o, namespaces, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' /> internal void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) { try { if (_primitiveType != null) { SerializePrimitive(xmlWriter, o, namespaces); } #if !NET_NATIVE else if (_tempAssembly == null || _typedSerializer) { XmlSerializationWriter writer = CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); try { Serialize(o, writer); } finally { writer.Dispose(); } } else _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); #else else { if (this.innerSerializer == null) { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name)); } XmlSerializationWriter writer = this.innerSerializer.CreateWriter(); writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); try { this.innerSerializer.Serialize(o, writer); } finally { writer.Dispose(); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; throw new InvalidOperationException(SR.XmlGenError, e); } xmlWriter.Flush(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(Stream stream) { XmlReaderSettings settings = new XmlReaderSettings(); // WhitespaceHandling.Significant means that you only want events for *significant* whitespace // resulting from elements marked with xml:space="preserve". All other whitespace // (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not // reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true. settings.IgnoreWhitespace = true; settings.DtdProcessing = (DtdProcessing) 2; /* DtdProcessing.Parse */ // Normalization = true, that's the default for the readers created with XmlReader.Create(). // The XmlTextReader has as default a non-conformant mode according to the XML spec // which skips some of the required processing for new lines, hence the need for the explicit // Normalization = true. The mode is no-longer exposed on XmlReader.Create() XmlReader xmlReader = XmlReader.Create(stream, settings); return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(TextReader textReader) { XmlReaderSettings settings = new XmlReaderSettings(); // WhitespaceHandling.Significant means that you only want events for *significant* whitespace // resulting from elements marked with xml:space="preserve". All other whitespace // (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not // reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true. settings.IgnoreWhitespace = true; settings.DtdProcessing = (DtdProcessing) 2; /* DtdProcessing.Parse */ // Normalization = true, that's the default for the readers created with XmlReader.Create(). // The XmlTextReader has as default a non-conformant mode according to the XML spec // which skips some of the required processing for new lines, hence the need for the explicit // Normalization = true. The mode is no-longer exposed on XmlReader.Create() XmlReader xmlReader = XmlReader.Create(textReader, settings); return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> internal object Deserialize(XmlReader xmlReader, string encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' /> internal object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) { try { if (_primitiveType != null) { return DeserializePrimitive(xmlReader, events); } #if !NET_NATIVE else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); try { return Deserialize(reader); } finally { reader.Dispose(); } } else { return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } #else else { if (this.innerSerializer == null) { throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name)); } XmlSerializationReader reader = this.innerSerializer.CreateReader(); reader.Init(xmlReader, encodingStyle); try { return this.innerSerializer.Deserialize(reader); } finally { reader.Dispose(); } } #endif } catch (Exception e) { if (e is TargetInvocationException) e = e.InnerException; if (xmlReader is IXmlLineInfo) { IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader; throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e); } else { throw new InvalidOperationException(SR.XmlSerializeError, e); } } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); } else if (_tempAssembly != null) { return _tempAssembly.CanRead(_mapping, xmlReader); } else { return false; } } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { return FromMappings(mappings, (Type)null); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (mappings == null || mappings.Length == 0) return new XmlSerializer[0]; XmlSerializerImplementation contract = null; TempAssembly tempAssembly = null; { if (XmlMapping.IsShallow(mappings)) { return new XmlSerializer[0]; } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } return serializers; } else { // Use XmlSerializer cache when the type is not null. return GetSerializersFromCache(mappings, type); } } } } private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; InternalHashtable typedMappingTable = null; lock (s_xmlSerializerTable) { typedMappingTable = s_xmlSerializerTable[type] as InternalHashtable; if (typedMappingTable == null) { typedMappingTable = new InternalHashtable(); s_xmlSerializerTable[type] = typedMappingTable; } } lock (typedMappingTable) { InternalHashtable pendingKeys = new InternalHashtable(); for (int i = 0; i < mappings.Length; i++) { XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]); serializers[i] = typedMappingTable[mappingKey] as XmlSerializer; if (serializers[i] == null) { pendingKeys.Add(mappingKey, i); } } if (pendingKeys.Count > 0) { XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count]; int index = 0; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { pendingMappings[index++] = mappingKey.Mapping; } TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null, null); XmlSerializerImplementation contract = tempAssembly.Contract; foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = (int)pendingKeys[mappingKey]; serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key]; serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping); typedMappingTable[mappingKey] = serializers[index]; } } } return serializers; } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSerializer[] FromTypes(Type[] types) { if (types == null) return new XmlSerializer[0]; XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } return FromMappings(mappings); } #if NET_NATIVE // this the global XML serializer contract introduced for multi-file private static XmlSerializerImplementation xmlSerializerContract; internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly() { // hack to pull in SetXmlSerializerContract which is only referenced from the // code injected by MainMethodInjector transform // there's probably also a way to do this via [DependencyReductionRoot], // but I can't get the compiler to find that... if (xmlSerializerContract == null) SetXmlSerializerContract(null); // this method body used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method return xmlSerializerContract; } public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation) { xmlSerializerContract = xmlSerializerImplementation; } #endif /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' /> ///<internalonly/> protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' /> ///<internalonly/> protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' /> ///<internalonly/> protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); } /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' /> ///<internalonly/> protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { _tempAssembly = tempAssembly; _mapping = mapping; _typedSerializer = true; } private static XmlTypeMapping GetKnownMapping(Type type, string ns) { if (ns != null && ns != string.Empty) return null; TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); element.Name = typeDesc.DataType.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); switch (_primitiveType.GetTypeCode()) { case TypeCode.String: writer.Write_string(o); break; case TypeCode.Int32: writer.Write_int(o); break; case TypeCode.Boolean: writer.Write_boolean(o); break; case TypeCode.Int16: writer.Write_short(o); break; case TypeCode.Int64: writer.Write_long(o); break; case TypeCode.Single: writer.Write_float(o); break; case TypeCode.Double: writer.Write_double(o); break; case TypeCode.Decimal: writer.Write_decimal(o); break; case TypeCode.DateTime: writer.Write_dateTime(o); break; case TypeCode.Char: writer.Write_char(o); break; case TypeCode.Byte: writer.Write_unsignedByte(o); break; case TypeCode.SByte: writer.Write_byte(o); break; case TypeCode.UInt16: writer.Write_unsignedShort(o); break; case TypeCode.UInt32: writer.Write_unsignedInt(o); break; case TypeCode.UInt64: writer.Write_unsignedLong(o); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { writer.Write_QName(o); } else if (_primitiveType == typeof(byte[])) { writer.Write_base64Binary(o); } else if (_primitiveType == typeof(Guid)) { writer.Write_guid(o); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } } private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); object o; switch (_primitiveType.GetTypeCode()) { case TypeCode.String: o = reader.Read_string(); break; case TypeCode.Int32: o = reader.Read_int(); break; case TypeCode.Boolean: o = reader.Read_boolean(); break; case TypeCode.Int16: o = reader.Read_short(); break; case TypeCode.Int64: o = reader.Read_long(); break; case TypeCode.Single: o = reader.Read_float(); break; case TypeCode.Double: o = reader.Read_double(); break; case TypeCode.Decimal: o = reader.Read_decimal(); break; case TypeCode.DateTime: o = reader.Read_dateTime(); break; case TypeCode.Char: o = reader.Read_char(); break; case TypeCode.Byte: o = reader.Read_unsignedByte(); break; case TypeCode.SByte: o = reader.Read_byte(); break; case TypeCode.UInt16: o = reader.Read_unsignedShort(); break; case TypeCode.UInt32: o = reader.Read_unsignedInt(); break; case TypeCode.UInt64: o = reader.Read_unsignedLong(); break; default: if (_primitiveType == typeof(XmlQualifiedName)) { o = reader.Read_QName(); } else if (_primitiveType == typeof(byte[])) { o = reader.Read_base64Binary(); } else if (_primitiveType == typeof(Guid)) { o = reader.Read_guid(); } else { throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); } break; } return o; } private class XmlSerializerMappingKey { public XmlMapping Mapping; public XmlSerializerMappingKey(XmlMapping mapping) { this.Mapping = mapping; } public override bool Equals(object obj) { XmlSerializerMappingKey other = obj as XmlSerializerMappingKey; if (other == null) return false; if (this.Mapping.Key != other.Mapping.Key) return false; if (this.Mapping.ElementName != other.Mapping.ElementName) return false; if (this.Mapping.Namespace != other.Mapping.Namespace) return false; if (this.Mapping.IsSoap != other.Mapping.IsSoap) return false; return true; } public override int GetHashCode() { int hashCode = this.Mapping.IsSoap ? 0 : 1; if (this.Mapping.Key != null) hashCode ^= this.Mapping.Key.GetHashCode(); if (this.Mapping.ElementName != null) hashCode ^= this.Mapping.ElementName.GetHashCode(); if (this.Mapping.Namespace != null) hashCode ^= this.Mapping.Namespace.GetHashCode(); return hashCode; } } } }
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using System; using ArcGISRuntime.Samples.Managers; using CoreGraphics; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Rasters; using Esri.ArcGISRuntime.UI.Controls; using Foundation; using UIKit; namespace ArcGISRuntime.Samples.RasterHillshade { [Register("RasterHillshade")] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("134d60f50e184e8fa56365f44e5ce3fb")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Raster hillshade renderer", category: "Layers", description: "Use a hillshade renderer on a raster.", instructions: "Configure the options for rendering, then tap 'Apply hillshade'.", tags: new[] { "Visualization", "hillshade", "raster", "shadow", "slope" })] public class RasterHillshade : UIViewController { // Hold references to UI controls. private MapView _myMapView; private HillshadeSettingsController _settingsVC; private UIBarButtonItem _configureButton; // Store a reference to the raster layer. private RasterLayer _rasterLayer; public RasterHillshade() { Title = "Raster hillshade"; } private async void Initialize() { // Create a map with a streets basemap. Map map = new Map(BasemapStyle.ArcGISStreets); // Get the file name for the local raster dataset. string filepath = DataManager.GetDataFolder("134d60f50e184e8fa56365f44e5ce3fb", "srtm-hillshade", "srtm.tiff"); // Load the raster file. Raster rasterFile = new Raster(filepath); try { // Create and load a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); await _rasterLayer.LoadAsync(); // Set up the settings controls. _settingsVC = new HillshadeSettingsController(_rasterLayer); // Set the initial viewpoint to the raster's full extent. map.InitialViewpoint = new Viewpoint(_rasterLayer.FullExtent); // Add the layer to the map. map.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. _myMapView.Map = map; } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate) null, "OK", null).Show(); } } private void HandleSettings_Clicked(object sender, EventArgs e) { UINavigationController controller = new UINavigationController(_settingsVC); controller.ModalPresentationStyle = UIModalPresentationStyle.Popover; controller.PreferredContentSize = new CGSize(300, 250); UIPopoverPresentationController pc = controller.PopoverPresentationController; if (pc != null) { pc.BarButtonItem = (UIBarButtonItem) sender; pc.PermittedArrowDirections = UIPopoverArrowDirection.Down; pc.Delegate = new PpDelegate(); } PresentViewController(controller, true, null); } public override void ViewDidLoad() { base.ViewDidLoad(); Initialize(); } public override void LoadView() { // Create the views. View = new UIView {BackgroundColor = ApplicationTheme.BackgroundColor}; _myMapView = new MapView(); _myMapView.TranslatesAutoresizingMaskIntoConstraints = false; _configureButton = new UIBarButtonItem(); _configureButton.Title = "Configure hillshade"; UIToolbar toolbar = new UIToolbar(); toolbar.TranslatesAutoresizingMaskIntoConstraints = false; toolbar.Items = new[] { new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace), _configureButton }; // Add the views. View.AddSubviews(_myMapView, toolbar); // Lay out the views. NSLayoutConstraint.ActivateConstraints(new[] { _myMapView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor), _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), _myMapView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor), toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor), toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor), toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor) }); } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _configureButton.Clicked += HandleSettings_Clicked; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _configureButton.Clicked -= HandleSettings_Clicked; } // Force popover to display on iPhone. private class PpDelegate : UIPopoverPresentationControllerDelegate { public override UIModalPresentationStyle GetAdaptivePresentationStyle( UIPresentationController forPresentationController) => UIModalPresentationStyle.None; public override UIModalPresentationStyle GetAdaptivePresentationStyle(UIPresentationController controller, UITraitCollection traitCollection) => UIModalPresentationStyle.None; } } public class HillshadeSettingsController : UIViewController { private readonly RasterLayer _rasterLayer; private UISegmentedControl _slopeTypePicker; private UISlider _altitudeSlider; private UISlider _azimuthSlider; public HillshadeSettingsController(RasterLayer rasterLayer) { _rasterLayer = rasterLayer; Title = "Hillshade settings"; } public override void LoadView() { View = new UIView() { BackgroundColor = ApplicationTheme.BackgroundColor }; UIScrollView scrollView = new UIScrollView(); scrollView.TranslatesAutoresizingMaskIntoConstraints = false; View.AddSubviews(scrollView); scrollView.TopAnchor.ConstraintEqualTo(View.TopAnchor).Active = true; scrollView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor).Active = true; scrollView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor).Active = true; scrollView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor).Active = true; UIStackView formContainer = new UIStackView(); formContainer.TranslatesAutoresizingMaskIntoConstraints = false; formContainer.Spacing = 8; formContainer.LayoutMarginsRelativeArrangement = true; formContainer.Alignment = UIStackViewAlignment.Fill; formContainer.LayoutMargins = new UIEdgeInsets(8, 8, 8, 8); formContainer.Axis = UILayoutConstraintAxis.Vertical; formContainer.WidthAnchor.ConstraintEqualTo(300).Active = true; UILabel slopeTypeLabel = new UILabel(); slopeTypeLabel.TranslatesAutoresizingMaskIntoConstraints = false; slopeTypeLabel.Text = "Slope type:"; formContainer.AddArrangedSubview(slopeTypeLabel); _slopeTypePicker = new UISegmentedControl("Degree", "% Rise", "Scaled", "None"); _slopeTypePicker.TranslatesAutoresizingMaskIntoConstraints = false; formContainer.AddArrangedSubview(_slopeTypePicker); UILabel altitudeLabel = new UILabel(); altitudeLabel.TranslatesAutoresizingMaskIntoConstraints = false; altitudeLabel.Text = "Altitude:"; formContainer.AddArrangedSubview(altitudeLabel); _altitudeSlider = new UISlider(); _altitudeSlider.TranslatesAutoresizingMaskIntoConstraints = false; _altitudeSlider.MinValue = 0; _altitudeSlider.MaxValue = 90; _altitudeSlider.Value = 45; formContainer.AddArrangedSubview(_altitudeSlider); UILabel azimuthLabel = new UILabel(); azimuthLabel.TranslatesAutoresizingMaskIntoConstraints = false; azimuthLabel.Text = "Azimuth:"; formContainer.AddArrangedSubview(azimuthLabel); _azimuthSlider = new UISlider(); _azimuthSlider.TranslatesAutoresizingMaskIntoConstraints = false; _azimuthSlider.MinValue = 0; _azimuthSlider.MaxValue = 360; _azimuthSlider.Value = 270; formContainer.AddArrangedSubview(_azimuthSlider); scrollView.AddSubview(formContainer); formContainer.TopAnchor.ConstraintEqualTo(scrollView.TopAnchor).Active = true; formContainer.LeadingAnchor.ConstraintEqualTo(scrollView.LeadingAnchor).Active = true; formContainer.TrailingAnchor.ConstraintEqualTo(scrollView.TrailingAnchor).Active = true; formContainer.BottomAnchor.ConstraintEqualTo(scrollView.BottomAnchor).Active = true; } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); // Subscribe to events. _azimuthSlider.ValueChanged += UpdateSettings; _altitudeSlider.ValueChanged += UpdateSettings; _slopeTypePicker.ValueChanged += UpdateSettings; } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); // Unsubscribe from events, per best practice. _azimuthSlider.ValueChanged -= UpdateSettings; _altitudeSlider.ValueChanged -= UpdateSettings; _slopeTypePicker.ValueChanged -= UpdateSettings; } private void UpdateSettings(object sender, EventArgs e) { SlopeType type = SlopeType.None; switch (_slopeTypePicker.SelectedSegment) { case 0: type = SlopeType.Degree; break; case 1: type = SlopeType.PercentRise; break; case 2: type = SlopeType.Scaled; break; } HillshadeRenderer renderer = new HillshadeRenderer( altitude: _altitudeSlider.Value, azimuth: _azimuthSlider.Value, zfactor: 1, slopeType: type, pixelSizeFactor: 1, pixelSizePower: 1, nbits: 8); _rasterLayer.Renderer = renderer; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.ServiceModel { public partial class BasicHttpBinding : System.ServiceModel.HttpBindingBase { public BasicHttpBinding() { } public BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode securityMode) { } public System.ServiceModel.BasicHttpSecurity Security { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public enum BasicHttpMessageCredentialType { Certificate = 1, UserName = 0, } public sealed partial class BasicHttpMessageSecurity { public BasicHttpMessageSecurity() { } public System.ServiceModel.BasicHttpMessageCredentialType ClientCredentialType { get { return default; } set { } } public System.ServiceModel.Security.SecurityAlgorithmSuite AlgorithmSuite { get { return default; } set { } } } public sealed partial class BasicHttpSecurity { public BasicHttpSecurity() { } public System.ServiceModel.BasicHttpSecurityMode Mode { get { return default; } set { } } public System.ServiceModel.HttpTransportSecurity Transport { get { return default; } set { } } public System.ServiceModel.BasicHttpMessageSecurity Message { get { return default; } set { } } } public enum BasicHttpSecurityMode { None = 0, Transport = 1, Message = 2, TransportWithMessageCredential = 3, TransportCredentialOnly = 4, } public partial class BasicHttpsBinding : System.ServiceModel.HttpBindingBase { public BasicHttpsBinding() { } public BasicHttpsBinding(System.ServiceModel.BasicHttpsSecurityMode securityMode) { } public System.ServiceModel.BasicHttpsSecurity Security { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public sealed partial class BasicHttpsSecurity { internal BasicHttpsSecurity() { } public System.ServiceModel.BasicHttpsSecurityMode Mode { get { return default; } set { } } public System.ServiceModel.HttpTransportSecurity Transport { get { return default; } set { } } } public enum BasicHttpsSecurityMode { Transport = 0, TransportWithMessageCredential = 1, } public abstract partial class HttpBindingBase : System.ServiceModel.Channels.Binding { internal HttpBindingBase() { } [System.ComponentModel.DefaultValueAttribute(false)] public bool AllowCookies { get { return default; } set { } } [System.ComponentModel.DefaultValue(false)] public bool BypassProxyOnLocal { get { return default; } set { } } public System.ServiceModel.EnvelopeVersion EnvelopeVersion { get { return default; } } [System.ComponentModel.DefaultValueAttribute((long)524288)] public long MaxBufferPoolSize { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(65536)] public int MaxBufferSize { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((long)65536)] public long MaxReceivedMessageSize { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] [System.ComponentModel.TypeConverter(typeof(System.UriTypeConverter))] public System.Uri ProxyAddress { get { return default; } set { } } public System.Xml.XmlDictionaryReaderQuotas ReaderQuotas { get { return default; } set { } } public override string Scheme { get { return default; } } public System.Text.Encoding TextEncoding { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.TransferMode)(0))] public System.ServiceModel.TransferMode TransferMode { get { return default; } set { } } [System.ComponentModel.DefaultValue(true)] public bool UseDefaultWebProxy { get { return default; } set { } } } public enum HttpClientCredentialType { Basic = 1, Certificate = 5, Digest = 2, InheritedFromHost = 6, None = 0, Ntlm = 3, Windows = 4, } public enum HttpProxyCredentialType { None, Basic, Digest, Ntlm, Windows, } public sealed partial class HttpTransportSecurity { public HttpTransportSecurity() { } public System.ServiceModel.HttpClientCredentialType ClientCredentialType { get { return default; } set { } } public System.ServiceModel.HttpProxyCredentialType ProxyCredentialType { get { return default; } set { } } public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionPolicy { get { return default; } set { } } } public partial class NetHttpBinding : System.ServiceModel.HttpBindingBase { public NetHttpBinding() { } public NetHttpBinding(System.ServiceModel.BasicHttpSecurityMode securityMode) { } public NetHttpBinding(System.ServiceModel.BasicHttpSecurityMode securityMode, bool reliableSessionEnabled) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public NetHttpBinding(string configurationName) { } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.NetHttpMessageEncoding)(0))] public System.ServiceModel.NetHttpMessageEncoding MessageEncoding { get { return default; } set { } } public System.ServiceModel.BasicHttpSecurity Security { get { return default; } set { } } public System.ServiceModel.OptionalReliableSession ReliableSession { get; set; } public System.ServiceModel.Channels.WebSocketTransportSettings WebSocketSettings { get { return default; } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public partial class NetHttpsBinding : System.ServiceModel.HttpBindingBase { public NetHttpsBinding() { } public NetHttpsBinding(System.ServiceModel.BasicHttpsSecurityMode securityMode) { } public NetHttpsBinding(System.ServiceModel.BasicHttpsSecurityMode securityMode, bool reliableSessionEnabled) { } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.NetHttpMessageEncoding)(0))] public System.ServiceModel.NetHttpMessageEncoding MessageEncoding { get { return default; } set { } } public System.ServiceModel.BasicHttpsSecurity Security { get { return default; } set { } } public System.ServiceModel.OptionalReliableSession ReliableSession { get; set; } public System.ServiceModel.Channels.WebSocketTransportSettings WebSocketSettings { get { return default; } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } } public enum NetHttpMessageEncoding { Binary = 0, Text = 1, Mtom = 2, } public abstract partial class WSHttpBindingBase : System.ServiceModel.Channels.Binding { protected WSHttpBindingBase() { } protected WSHttpBindingBase(bool reliableSessionEnabled) { } public bool BypassProxyOnLocal { get { return default; } set { } } public bool TransactionFlow { get { return default; } set { } } //public System.ServiceModel.HostNameComparisonMode HostNameComparisonMode { get { return default; } set { } } public long MaxBufferPoolSize { get { return default; } set { } } public long MaxReceivedMessageSize { get { return default; } set { } } //public System.ServiceModel.WSMessageEncoding MessageEncoding { get { return default; } set { } } public Uri ProxyAddress { get { return default; } set { } } public System.Xml.XmlDictionaryReaderQuotas ReaderQuotas { get { return default; } set { } } public System.ServiceModel.OptionalReliableSession ReliableSession { get { return default; } set { } } public override string Scheme { get { return default; } } public System.ServiceModel.EnvelopeVersion EnvelopeVersion { get { return default; } set { } } public System.Text.Encoding TextEncoding { get { return default; } set { } } public bool UseDefaultWebProxy { get { return default; } set { } } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } protected abstract System.ServiceModel.Channels.TransportBindingElement GetTransport(); protected abstract System.ServiceModel.Channels.SecurityBindingElement CreateMessageSecurity(); } public partial class WSHttpBinding : System.ServiceModel.WSHttpBindingBase { public WSHttpBinding() { } public WSHttpBinding(System.ServiceModel.SecurityMode securityMode) { } public WSHttpBinding(System.ServiceModel.SecurityMode securityMode, bool reliableSessionEnabled) { } public bool AllowCookies { get { return default; } set { } } public System.ServiceModel.WSHttpSecurity Security { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingParameterCollection parameters) { return default; } public override System.ServiceModel.Channels.BindingElementCollection CreateBindingElements() { return default; } protected override System.ServiceModel.Channels.TransportBindingElement GetTransport() { return default; } protected override System.ServiceModel.Channels.SecurityBindingElement CreateMessageSecurity() { return default; } } public class WS2007HttpBinding : WSHttpBinding { public WS2007HttpBinding() { } public WS2007HttpBinding(System.ServiceModel.SecurityMode securityMode) { } public WS2007HttpBinding(System.ServiceModel.SecurityMode securityMode, bool reliableSessionEnabled) { } protected override System.ServiceModel.Channels.SecurityBindingElement CreateMessageSecurity() { return default; } } public sealed partial class WSHttpSecurity { public WSHttpSecurity() { } public System.ServiceModel.SecurityMode Mode { get { return default; } set { } } public System.ServiceModel.HttpTransportSecurity Transport { get { return default; } set { } } public System.ServiceModel.NonDualMessageSecurityOverHttp Message { get { return default; } set { } } } public sealed class NonDualMessageSecurityOverHttp : System.ServiceModel.MessageSecurityOverHttp { public NonDualMessageSecurityOverHttp() { } public bool EstablishSecurityContext { get { return default; } set { } } protected override bool IsSecureConversationEnabled() { return default; } } public class MessageSecurityOverHttp { public MessageSecurityOverHttp() { } public System.ServiceModel.MessageCredentialType ClientCredentialType { get { return default; } set { } } public bool NegotiateServiceCredential { get { return default; } set { } } public System.ServiceModel.Security.SecurityAlgorithmSuite AlgorithmSuite { get { return default; } set { } } protected virtual bool IsSecureConversationEnabled() { return default; } } //public enum WSMessageEncoding //{ // Text = 0, // Mtom, //} } namespace System.ServiceModel.Channels { public sealed partial class HttpRequestMessageProperty : System.ServiceModel.Channels.IMessageProperty { public HttpRequestMessageProperty() { } public System.Net.WebHeaderCollection Headers { get { return default; } } public string Method { get { return default; } set { } } public static string Name { get { return default; } } public string QueryString { get { return default; } set { } } public bool SuppressEntityBody { get { return default; } set { } } System.ServiceModel.Channels.IMessageProperty System.ServiceModel.Channels.IMessageProperty.CreateCopy() { return default; } } public sealed partial class HttpResponseMessageProperty : System.ServiceModel.Channels.IMessageProperty { public HttpResponseMessageProperty() { } public System.Net.WebHeaderCollection Headers { get { return default; } } public static string Name { get { return default; } } public System.Net.HttpStatusCode StatusCode { get { return default; } set { } } public string StatusDescription { get { return default; } set { } } System.ServiceModel.Channels.IMessageProperty System.ServiceModel.Channels.IMessageProperty.CreateCopy() { return default; } } public partial class HttpsTransportBindingElement : System.ServiceModel.Channels.HttpTransportBindingElement { public HttpsTransportBindingElement() { } protected HttpsTransportBindingElement(System.ServiceModel.Channels.HttpsTransportBindingElement elementToBeCloned) { } public bool RequireClientCertificate { get { return default; } set { } } public override string Scheme { get { return default; } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public override System.ServiceModel.Channels.BindingElement Clone() { return default; } public override T GetProperty<T>(System.ServiceModel.Channels.BindingContext context) { return default; } } public partial class HttpTransportBindingElement : System.ServiceModel.Channels.TransportBindingElement { public HttpTransportBindingElement() { } protected HttpTransportBindingElement(System.ServiceModel.Channels.HttpTransportBindingElement elementToBeCloned) { } [System.ComponentModel.DefaultValueAttribute(false)] public bool AllowCookies { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.Net.AuthenticationSchemes)(32768))] public System.Net.AuthenticationSchemes AuthenticationScheme { get { return default; } set { } } [System.ComponentModel.DefaultValue(false)] public bool BypassProxyOnLocal { get { return default; } set { } } public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionPolicy { get; set; } [System.ComponentModel.DefaultValueAttribute(65536)] public int MaxBufferSize { get { return default; } set { } } [System.ComponentModel.DefaultValue(null)] [System.ComponentModel.TypeConverter(typeof(System.UriTypeConverter))] public System.Uri ProxyAddress { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.Net.AuthenticationSchemes)(32768))] public System.Net.AuthenticationSchemes ProxyAuthenticationScheme { get { return default; } set { } } public System.Net.IWebProxy Proxy { get { return default; } set { } } public override string Scheme { get { return default; } } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.TransferMode)(0))] public System.ServiceModel.TransferMode TransferMode { get { return default; } set { } } public System.ServiceModel.Channels.WebSocketTransportSettings WebSocketSettings { get { return default; } set { } } [System.ComponentModel.DefaultValue(true)] public bool UseDefaultWebProxy { get { return default; } set { } } [System.ComponentModel.DefaultValue(true)] public bool KeepAliveEnabled { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public override bool CanBuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public override System.ServiceModel.Channels.BindingElement Clone() { return default; } public override T GetProperty<T>(System.ServiceModel.Channels.BindingContext context) { return default; } } public partial interface IHttpCookieContainerManager { System.Net.CookieContainer CookieContainer { get; set; } } public sealed partial class WebSocketTransportSettings : System.IEquatable<System.ServiceModel.Channels.WebSocketTransportSettings> { public const string BinaryMessageReceivedAction = "http://schemas.microsoft.com/2011/02/websockets/onbinarymessage"; public const string TextMessageReceivedAction = "http://schemas.microsoft.com/2011/02/websockets/ontextmessage"; public WebSocketTransportSettings() { } [System.ComponentModel.DefaultValueAttribute(false)] public bool DisablePayloadMasking { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(typeof(System.TimeSpan), "00:00:00")] public System.TimeSpan KeepAliveInterval { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute(null)] public string SubProtocol { get { return default; } set { } } [System.ComponentModel.DefaultValueAttribute((System.ServiceModel.Channels.WebSocketTransportUsage)(2))] public System.ServiceModel.Channels.WebSocketTransportUsage TransportUsage { get { return default; } set { } } public override bool Equals(object obj) { return default; } public bool Equals(System.ServiceModel.Channels.WebSocketTransportSettings other) { return default; } public override int GetHashCode() { return default; } } public enum WebSocketTransportUsage { Always = 1, Never = 2, WhenDuplex = 0, } }
namespace PublicApiGenerator.Tool { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml.Linq; using Process = System.Diagnostics.Process; /// <summary> /// Program for dotnet tool /// </summary> public static class Program { /// <summary> /// Public API generator tool that is useful for semantic versioning /// </summary> /// <param name="targetFrameworks">Target frameworks to use to restore packages in. Must be a suitable target framework for executables like netcoreapp2.1. It is possible to specify multiple target frameworks like netcoreapp2.1;net461</param> /// <param name="assembly">The assembly name including the extension (i.ex. PublicApiGenerator.dll) to generate a public API from in case in differs from the package name.</param> /// <param name="projectPath">The path to the csproj that should be used to build the public API.</param> /// <param name="package">The package name from which a public API should be created. The tool assumes the package name equals the assembly name. If the assembly name is different specify <paramref name="assembly"/></param> /// <param name="packageVersion">The version of the package defined in <paramref name="package"/> to be used.</param> /// <param name="packageSource">Package source or feed to use (multiple allowed).</param> /// <param name="generatorVersion">The version of the PublicApiGenerator package to use.</param> /// <param name="workingDirectory">The working directory to be used for temporary work artifacts. A temporary directory will be created inside the working directory and deleted once the process is done. If no working directory is specified the users temp directory is used.</param> /// <param name="outputDirectory">The output directory where the generated public APIs should be moved.</param> /// <param name="verbose"></param> /// <param name="leaveArtifacts">Instructs to leave the temporary artifacts around for debugging and troubleshooting purposes.</param> /// <param name="waitTimeInSeconds">The number of seconds to wait for the API generation process to end. If multiple target frameworks are used the wait time is applied per target framework.</param> /// <returns></returns> static int Main(string targetFrameworks, string? assembly = null, string? projectPath = null, string? package = null, string? packageVersion = null, ICollection<string>? packageSource = null, string? generatorVersion = null, string? workingDirectory = null, string? outputDirectory = null, bool verbose = false, bool leaveArtifacts = false, int waitTimeInSeconds = 60) { var logError = Console.Error; var logVerbose = verbose ? Console.Error : TextWriter.Null; var workingArea = !string.IsNullOrEmpty(workingDirectory) ? Path.Combine(workingDirectory, Path.GetRandomFileName()) : Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); logVerbose.WriteLine($"Working area: {workingArea}"); try { AssertInputParameters(targetFrameworks, projectPath, package, packageVersion, workingArea, assembly); var frameworks = targetFrameworks.Split(";"); if (string.IsNullOrEmpty(outputDirectory) && frameworks.Length > 1) { outputDirectory = Environment.CurrentDirectory; } if (string.IsNullOrEmpty(generatorVersion)) { generatorVersion = $"{typeof(Program).Assembly.GetName().Version.Major}.*"; } var project = CreateProject(targetFrameworks, projectPath, package, packageVersion, packageSource, generatorVersion!); SaveProject(workingArea, project, logVerbose); foreach (var framework in frameworks) { GeneratePublicApi(assembly, package, workingArea, framework, outputDirectory, waitTimeInSeconds, logVerbose, logError); } return 0; } catch (InvalidOperationException e) { logError.WriteLine($"Configuration error: {e.Message}"); return 1; } catch (Exception e) { logError.WriteLine($"Failed: {e}"); return 1; } finally { if (Directory.Exists(workingArea) && !leaveArtifacts) { Directory.Delete(workingArea, true); } } } private static void GeneratePublicApi(string? assembly, string? package, string workingArea, string framework, string? outputDirectory, int waitTimeInSeconds, TextWriter logVerbose, TextWriter logError) { var relativePath = Path.Combine(workingArea, "bin", "Release", framework); var name = !string.IsNullOrEmpty(assembly) ? $"{assembly}" : $"{package}.dll"; relativePath = Path.Combine(relativePath, name); var assemblyPath = Path.GetFullPath(relativePath); var apiFilePath = outputDirectory != null ? Path.Combine(workingArea, $"{Path.GetFileNameWithoutExtension(name)}.{framework}.received.txt") : null; try { // Because we run in different appdomain we can always unload RunDotnet(workingArea, waitTimeInSeconds, logVerbose, apiFilePath != null ? null : Console.Out, "run", "--configuration", "Release", "--framework", framework, "--", assemblyPath, apiFilePath ?? "-"); } catch (FileNotFoundException) { logError.WriteLine($"Unable to find {assemblyPath}. Consider specifying --assembly"); throw; } if (outputDirectory == null || apiFilePath == null) { return; } logVerbose.WriteLine($"Public API file: {apiFilePath}"); logVerbose.WriteLine(); var destinationFilePath = Path.Combine(outputDirectory, Path.GetFileName(apiFilePath)); if (File.Exists(destinationFilePath)) File.Delete(destinationFilePath); File.Move(apiFilePath, destinationFilePath); Console.WriteLine(Path.GetFullPath(destinationFilePath)); } private static void RunDotnet(string workingArea, int waitTimeInSeconds, TextWriter logVerbose, TextWriter? stdout, params string[] arguments) { var psi = new ProcessStartInfo { FileName = "dotnet", WorkingDirectory = workingArea, RedirectStandardOutput = true, RedirectStandardError = true }; logVerbose.WriteLine($"Invoking dotnet with arguments:"); foreach (var (i, arg) in arguments.Select((arg, i) => (i + 1, arg))) { logVerbose.WriteLine($"{i,4}. {arg}"); psi.ArgumentList.Add(arg); } logVerbose.WriteLine(); logVerbose.WriteLine($"Proces timeout: '{waitTimeInSeconds}' seconds."); using var process = Process.Start(psi); if (stdout == null) { logVerbose.WriteLine("Dotnet output:"); } const string indent = " "; process.OutputDataReceived += DataReceivedEventHandler(stdout ?? logVerbose, stdout == null ? indent : null); process.ErrorDataReceived += DataReceivedEventHandler(logVerbose, indent); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (stdout == null) { logVerbose.WriteLine(); } if (!process.WaitForExit(waitTimeInSeconds * 1000)) { throw new TimeoutException($"Process \"{psi.FileName}\" ({process.Id}) took too long to run (timeout exceeded {waitTimeInSeconds} seconds)."); } if (process.ExitCode != 0) { var pseudoCommandLine = string.Join(" ", from arg in arguments select arg.IndexOf('"') >= 0 ? $"\"{arg.Replace("\"", "\"\"")}\"" : arg); throw new Exception( $"dotnet exit code {process.ExitCode}. Directory: {workingArea}. Args: {pseudoCommandLine}."); } static DataReceivedEventHandler DataReceivedEventHandler(TextWriter writer, string? prefix = null) => (_, args) => { if (args.Data == null) { return; // EOI } writer.WriteLine(prefix + args.Data); }; } private static void SaveProject(string workingArea, XElement project, TextWriter logVerbose) { Directory.CreateDirectory(workingArea); var fullPath = Path.Combine(workingArea, "project.csproj"); using (var output = File.CreateText(fullPath)) { logVerbose.WriteLine($"Project output path: {fullPath}"); logVerbose.WriteLine($"Project template: {project}"); logVerbose.WriteLine(); output.Write(project); } var programMain = typeof(Program).GetManifestResourceText("SubProgram.cs"); fullPath = Path.Combine(workingArea, "Program.cs"); using (var output = File.CreateText(fullPath)) { logVerbose.WriteLine($"Program output path: {fullPath}"); logVerbose.WriteLine($"Program template: {programMain}"); logVerbose.WriteLine(); output.Write(programMain); } } private static string GetManifestResourceText(this Type type, string name, Encoding? encoding = null) { using var stream = type.Assembly.GetManifestResourceStream(type, name); if (stream == null) { throw new Exception($"Resource named \"{type.Namespace}.{name}\" not found."); } using var reader = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding); return reader.ReadToEnd(); } private static XElement CreateProject(string targetFrameworks, string? project, string? package, string? packageVersion, ICollection<string>? packageSource, string generatorVersion) { return new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), new XElement("PropertyGroup", new XElement("OutputType", "Exe"), new XElement("TargetFrameworks", targetFrameworks), new XElement("CopyLocalLockFileAssemblies", "true"), packageSource?.Count > 0 ? new XElement("RestoreAdditionalProjectSources", string.Join(";", packageSource)) : null), new XElement("ItemGroup", PackageReference(nameof(PublicApiGenerator), generatorVersion), !string.IsNullOrEmpty(package) ? PackageReference(package!, packageVersion!) : null, !string.IsNullOrEmpty(project) ? new XElement("ProjectReference", new XAttribute("Include", project)) : null)); static XElement PackageReference(string id, string version) => new XElement("PackageReference", new XAttribute("Include", id), new XAttribute("Version", version)); } private static void AssertInputParameters(string targetFrameworks, string? project, string? package, string? packageVersion, string workingArea, string? assembly) { if (string.IsNullOrEmpty(targetFrameworks)) { throw new InvalidOperationException("Specify the target frameworks like 'netcoreapp2.1;net461' or 'netcoreapp2.1'."); } if (!string.IsNullOrEmpty(package) && string.IsNullOrEmpty(packageVersion)) { throw new InvalidOperationException("When using the package switch the package-version switch needs to be specified."); } if (!string.IsNullOrEmpty(package) && !string.IsNullOrEmpty(project)) { throw new InvalidOperationException( "When using the package name the project-path switch cannot be used or vice versa."); } if (!string.IsNullOrEmpty(project) && string.IsNullOrEmpty(assembly)) { throw new InvalidOperationException( "When using the project-path switch the output assembly name has to be specified with --assembly."); } if (File.Exists(workingArea) || Directory.Exists(workingArea)) { throw new InvalidOperationException($"{workingArea} already exists"); } } } }
using System; using Terraria; using Terraria.ModLoader; namespace ExampleMod.NPCs { //ported from my tAPI mod because I'm lazy public abstract class Hover : ModNPC { protected float speed = 2f; protected float acceleration = 0.1f; protected float speedY = 1.5f; protected float accelerationY = 0.04f; public override void AI() { if (!ShouldMove(npc.ai[3])) { CustomBehavior(ref npc.ai[3]); return; } bool flag33 = false; if (npc.justHit) { npc.ai[2] = 0f; } if (npc.ai[2] >= 0f) { int num379 = 16; bool flag34 = false; bool flag35 = false; if (npc.position.X > npc.ai[0] - (float)num379 && npc.position.X < npc.ai[0] + (float)num379) { flag34 = true; } else if ((npc.velocity.X < 0f && npc.direction > 0) || (npc.velocity.X > 0f && npc.direction < 0)) { flag34 = true; } num379 += 24; if (npc.position.Y > npc.ai[1] - (float)num379 && npc.position.Y < npc.ai[1] + (float)num379) { flag35 = true; } if (flag34 && flag35) { npc.ai[2] += 1f; if (npc.ai[2] >= 30f && num379 == 16) { flag33 = true; } if (npc.ai[2] >= 60f) { npc.ai[2] = -200f; npc.direction *= -1; npc.velocity.X *= -1f; npc.collideX = false; } } else { npc.ai[0] = npc.position.X; npc.ai[1] = npc.position.Y; npc.ai[2] = 0f; } npc.TargetClosest(true); } else { npc.ai[2] += 1f; if (Main.player[npc.target].position.X + (float)(Main.player[npc.target].width / 2) > npc.position.X + (float)(npc.width / 2)) { npc.direction = -1; } else { npc.direction = 1; } } int num380 = (int)((npc.position.X + (float)(npc.width / 2)) / 16f) + npc.direction * 2; int num381 = (int)((npc.position.Y + (float)npc.height) / 16f); bool flag36 = true; bool flag37 = false; int num382 = 3; for (int num404 = num381; num404 < num381 + num382; num404++) { if (Main.tile[num380, num404] == null) { Main.tile[num380, num404] = new Tile(); } if ((Main.tile[num380, num404].nactive() && Main.tileSolid[(int)Main.tile[num380, num404].type]) || Main.tile[num380, num404].liquid > 0) { if (num404 <= num381 + 1) { flag37 = true; } flag36 = false; break; } } if (flag33) { flag37 = false; flag36 = true; } if (flag36) { npc.velocity.Y += Math.Max(0.2f, 2.5f * accelerationY); if (npc.velocity.Y > Math.Max(2f, speedY)) { npc.velocity.Y = Math.Max(2f, speedY); } } else { if ((npc.directionY < 0 && npc.velocity.Y > 0f) || flag37) { npc.velocity.Y -= 0.2f; } if (npc.velocity.Y < -4f) { npc.velocity.Y = -4f; } } if (npc.collideX) { npc.velocity.X = npc.oldVelocity.X * -0.4f; if (npc.direction == -1 && npc.velocity.X > 0f && npc.velocity.X < 1f) { npc.velocity.X = 1f; } if (npc.direction == 1 && npc.velocity.X < 0f && npc.velocity.X > -1f) { npc.velocity.X = -1f; } } if (npc.collideY) { npc.velocity.Y = npc.oldVelocity.Y * -0.25f; if (npc.velocity.Y > 0f && npc.velocity.Y < 1f) { npc.velocity.Y = 1f; } if (npc.velocity.Y < 0f && npc.velocity.Y > -1f) { npc.velocity.Y = -1f; } } if (npc.direction == -1 && npc.velocity.X > -speed) { npc.velocity.X -= acceleration; if (npc.velocity.X > speed) { npc.velocity.X -= acceleration; } else if (npc.velocity.X > 0f) { npc.velocity.X += acceleration / 2f; } if (npc.velocity.X < -speed) { npc.velocity.X = -speed; } } else if (npc.direction == 1 && npc.velocity.X < speed) { npc.velocity.X += acceleration; if (npc.velocity.X < -speed) { npc.velocity.X += acceleration; } else if (npc.velocity.X < 0f) { npc.velocity.X -= acceleration / 2f; } if (npc.velocity.X > speed) { npc.velocity.X = speed; } } if (npc.directionY == -1 && (double)npc.velocity.Y > -speedY) { npc.velocity.Y -= accelerationY; if ((double)npc.velocity.Y > speedY) { npc.velocity.Y -= accelerationY * 1.25f; } else if (npc.velocity.Y > 0f) { npc.velocity.Y += accelerationY * 0.75f; } if ((double)npc.velocity.Y < -speedY) { npc.velocity.Y = -speedY; } } else if (npc.directionY == 1 && (double)npc.velocity.Y < speedY) { npc.velocity.Y += accelerationY; if ((double)npc.velocity.Y < -speedY) { npc.velocity.Y += accelerationY * 1.25f; } else if (npc.velocity.Y < 0f) { npc.velocity.Y -= accelerationY * 0.75f; } if ((double)npc.velocity.Y > speedY) { npc.velocity.Y = speedY; } } CustomBehavior(ref npc.ai[3]); } public virtual void CustomBehavior(ref float ai) { } public virtual bool ShouldMove(float ai) { return 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.Collections.Generic; using System.Dynamic; using System.Linq.Expressions; using Microsoft.CSharp.RuntimeBinder; using Xunit; namespace System.Runtime.CompilerServices.Tests { public class CallSiteCachingTests { [Fact] public void InlineCache() { var callSite = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, "A", typeof(CallSiteCachingTests), new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); var initialTarget = callSite.Target; Assert.Equal((object)initialTarget, callSite.Update); object newExpando = CallSiteCachingTests.GetNewExpando(123); callSite.Target(callSite, newExpando); var newTarget = callSite.Target; for (int i = 0; i < 10; i++) { callSite.Target(callSite, newExpando); // rule should not be changing Assert.Equal((object)newTarget, callSite.Target); } } [Fact] public void L1Cache() { var callSite = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, "A", typeof(CallSiteCachingTests), new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); ObjAndRule[] t = new ObjAndRule[200]; for (int i = 0; i < 10; i++) { object newExpando = CallSiteCachingTests.GetNewExpando(i); callSite.Target(callSite, newExpando); t[i].obj = newExpando; t[i].rule = callSite.Target; if (i > 0) { // must not reuse rules for new expandos Assert.NotEqual((object)t[i].rule, t[i - 1].rule); } } for (int i = 0; i < 10; i++) { var L1 = CallSiteOps.GetRules((dynamic)callSite); // L1 must contain rules Assert.Equal((object)t[9 - i].rule, L1[i]); } } [Fact] public void L2Cache() { var callSite = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, "A", typeof(CallSiteCachingTests), new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); ObjAndRule[] t = new ObjAndRule[200]; for (int i = 0; i < 100; i++) { object newExpando = CallSiteCachingTests.GetNewExpando(i); callSite.Target(callSite, newExpando); t[i].obj = newExpando; t[i].rule = callSite.Target; if (i > 0) { // must not reuse rules for new expandos Assert.NotEqual((object)t[i].rule, t[i - 1].rule); } } for (int i = 0; i < 100; i++) { object newExpando = CallSiteCachingTests.GetNewExpando(i); callSite.Target(callSite, newExpando); // must reuse rules from L2 cache Assert.Equal((object)t[i].rule, callSite.Target); } } private static dynamic GetNewExpando(int i) { dynamic e = new ExpandoObject(); e.A = i; var d = e as IDictionary<string, object>; d.Add(i.ToString(), i); return e; } private struct ObjAndRule { public object obj; public object rule; } private class TestClass01 { public static void BindThings() { dynamic i = 1; dynamic l = (long)2; dynamic d = 1.1; // will bind int + int i = i + i; // will bind long + long i = l + l; // will bind double + double d = d + d; } public static void TryGetMember() { dynamic d = "AAA"; try { d = d.BBBB; } catch { } } } [Fact] public void BinderCacheAddition() { CSharpArgumentInfo x = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null); CSharpArgumentInfo y = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null); CallSiteBinder binder = Binder.BinaryOperation( CSharpBinderFlags.None, System.Linq.Expressions.ExpressionType.Add, typeof(TestClass01), new[] { x, y }); var site = CallSite<Func<CallSite, object, object, object>>.Create(binder); Func<CallSite, object, object, object> targ = site.Target; object res = targ(site, 1, 2); Assert.Equal(3, res); var rulesCnt = CallSiteOps.GetCachedRules(CallSiteOps.GetRuleCache((dynamic)site)).Length; Assert.Equal(1, rulesCnt); TestClass01.BindThings(); rulesCnt = CallSiteOps.GetCachedRules(CallSiteOps.GetRuleCache((dynamic)site)).Length; Assert.Equal(3, rulesCnt); } [Fact] public void BinderCacheFlushWhenTooBig() { var callSite1 = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, "A", typeof(TestClass01), new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); var rules1 = CallSiteOps.GetRuleCache((dynamic)callSite1); var callSite2 = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, "A", typeof(TestClass01), new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); var rules2 = CallSiteOps.GetRuleCache((dynamic)callSite2); Assert.Equal(rules1, rules2); // blast through callsite cache for (int i = 0; i < 10000; i++) { var callSiteN = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, i.ToString(), typeof(TestClass01), new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); } var callSite3 = CallSite<Func<CallSite, object, object>>.Create(Binder.GetMember(CSharpBinderFlags.None, "A", typeof(TestClass01), new CSharpArgumentInfo[1] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) })); var rules3 = CallSiteOps.GetRuleCache((dynamic)callSite3); Assert.NotEqual(rules1, rules3); } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// ItemCCBill /// </summary> [DataContract] public partial class ItemCCBill : IEquatable<ItemCCBill>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ItemCCBill" /> class. /// </summary> /// <param name="ccbillAllowedCurrencies">Allowed currencies.</param> /// <param name="ccbillAllowedTypes">Allowed types.</param> /// <param name="ccbillCurrencyCode">Currency code.</param> /// <param name="ccbillFormName">Form name.</param> /// <param name="ccbillSubaccountId">Sub-account id.</param> /// <param name="ccbillSubscriptionTypeId">Subscription type id.</param> public ItemCCBill(string ccbillAllowedCurrencies = default(string), string ccbillAllowedTypes = default(string), string ccbillCurrencyCode = default(string), string ccbillFormName = default(string), string ccbillSubaccountId = default(string), string ccbillSubscriptionTypeId = default(string)) { this.CcbillAllowedCurrencies = ccbillAllowedCurrencies; this.CcbillAllowedTypes = ccbillAllowedTypes; this.CcbillCurrencyCode = ccbillCurrencyCode; this.CcbillFormName = ccbillFormName; this.CcbillSubaccountId = ccbillSubaccountId; this.CcbillSubscriptionTypeId = ccbillSubscriptionTypeId; } /// <summary> /// Allowed currencies /// </summary> /// <value>Allowed currencies</value> [DataMember(Name="ccbill_allowed_currencies", EmitDefaultValue=false)] public string CcbillAllowedCurrencies { get; set; } /// <summary> /// Allowed types /// </summary> /// <value>Allowed types</value> [DataMember(Name="ccbill_allowed_types", EmitDefaultValue=false)] public string CcbillAllowedTypes { get; set; } /// <summary> /// Currency code /// </summary> /// <value>Currency code</value> [DataMember(Name="ccbill_currency_code", EmitDefaultValue=false)] public string CcbillCurrencyCode { get; set; } /// <summary> /// Form name /// </summary> /// <value>Form name</value> [DataMember(Name="ccbill_form_name", EmitDefaultValue=false)] public string CcbillFormName { get; set; } /// <summary> /// Sub-account id /// </summary> /// <value>Sub-account id</value> [DataMember(Name="ccbill_subaccount_id", EmitDefaultValue=false)] public string CcbillSubaccountId { get; set; } /// <summary> /// Subscription type id /// </summary> /// <value>Subscription type id</value> [DataMember(Name="ccbill_subscription_type_id", EmitDefaultValue=false)] public string CcbillSubscriptionTypeId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ItemCCBill {\n"); sb.Append(" CcbillAllowedCurrencies: ").Append(CcbillAllowedCurrencies).Append("\n"); sb.Append(" CcbillAllowedTypes: ").Append(CcbillAllowedTypes).Append("\n"); sb.Append(" CcbillCurrencyCode: ").Append(CcbillCurrencyCode).Append("\n"); sb.Append(" CcbillFormName: ").Append(CcbillFormName).Append("\n"); sb.Append(" CcbillSubaccountId: ").Append(CcbillSubaccountId).Append("\n"); sb.Append(" CcbillSubscriptionTypeId: ").Append(CcbillSubscriptionTypeId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ItemCCBill); } /// <summary> /// Returns true if ItemCCBill instances are equal /// </summary> /// <param name="input">Instance of ItemCCBill to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemCCBill input) { if (input == null) return false; return ( this.CcbillAllowedCurrencies == input.CcbillAllowedCurrencies || (this.CcbillAllowedCurrencies != null && this.CcbillAllowedCurrencies.Equals(input.CcbillAllowedCurrencies)) ) && ( this.CcbillAllowedTypes == input.CcbillAllowedTypes || (this.CcbillAllowedTypes != null && this.CcbillAllowedTypes.Equals(input.CcbillAllowedTypes)) ) && ( this.CcbillCurrencyCode == input.CcbillCurrencyCode || (this.CcbillCurrencyCode != null && this.CcbillCurrencyCode.Equals(input.CcbillCurrencyCode)) ) && ( this.CcbillFormName == input.CcbillFormName || (this.CcbillFormName != null && this.CcbillFormName.Equals(input.CcbillFormName)) ) && ( this.CcbillSubaccountId == input.CcbillSubaccountId || (this.CcbillSubaccountId != null && this.CcbillSubaccountId.Equals(input.CcbillSubaccountId)) ) && ( this.CcbillSubscriptionTypeId == input.CcbillSubscriptionTypeId || (this.CcbillSubscriptionTypeId != null && this.CcbillSubscriptionTypeId.Equals(input.CcbillSubscriptionTypeId)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.CcbillAllowedCurrencies != null) hashCode = hashCode * 59 + this.CcbillAllowedCurrencies.GetHashCode(); if (this.CcbillAllowedTypes != null) hashCode = hashCode * 59 + this.CcbillAllowedTypes.GetHashCode(); if (this.CcbillCurrencyCode != null) hashCode = hashCode * 59 + this.CcbillCurrencyCode.GetHashCode(); if (this.CcbillFormName != null) hashCode = hashCode * 59 + this.CcbillFormName.GetHashCode(); if (this.CcbillSubaccountId != null) hashCode = hashCode * 59 + this.CcbillSubaccountId.GetHashCode(); if (this.CcbillSubscriptionTypeId != null) hashCode = hashCode * 59 + this.CcbillSubscriptionTypeId.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using System; using NPOI.HSSF.Record; using NPOI.HSSF.Record.Aggregates; using NPOI.SS.Util; using NPOI.SS.UserModel; /// <summary> /// The Conditional Formatting facet of HSSFSheet /// @author Dmitriy Kumshayev /// </summary> public class HSSFSheetConditionalFormatting : ISheetConditionalFormatting { //private HSSFWorkbook _workbook; private HSSFSheet _sheet; private ConditionalFormattingTable _conditionalFormattingTable; /* package */ //public HSSFSheetConditionalFormatting(HSSFWorkbook workbook, InternalSheet sheet) //{ // _workbook = workbook; // _conditionalFormattingTable = sheet.ConditionalFormattingTable; //} public HSSFSheetConditionalFormatting(HSSFSheet sheet) { _sheet = sheet; _conditionalFormattingTable = sheet.Sheet.ConditionalFormattingTable; } /// <summary> /// A factory method allowing to Create a conditional formatting rule /// with a cell comparison operator /// TODO - formulas containing cell references are currently not Parsed properly /// </summary> /// <param name="comparisonOperation">a constant value from HSSFConditionalFormattingRule.ComparisonOperator</param> /// <param name="formula1">formula for the valued, Compared with the cell</param> /// <param name="formula2">second formula (only used with HSSFConditionalFormattingRule#COMPARISON_OPERATOR_BETWEEN /// and HSSFConditionalFormattingRule#COMPARISON_OPERATOR_NOT_BETWEEN operations)</param> /// <returns></returns> public IConditionalFormattingRule CreateConditionalFormattingRule( ComparisonOperator comparisonOperation, String formula1, String formula2) { CFRuleRecord rr = CFRuleRecord.Create(_sheet, (byte)comparisonOperation, formula1, formula2); return new HSSFConditionalFormattingRule(_sheet, rr); } public IConditionalFormattingRule CreateConditionalFormattingRule( ComparisonOperator comparisonOperation, String formula1) { CFRuleRecord rr = CFRuleRecord.Create(_sheet, (byte)comparisonOperation, formula1, null); return new HSSFConditionalFormattingRule(_sheet, rr); } /// <summary> /// A factory method allowing to Create a conditional formatting rule with a formula. /// The formatting rules are applied by Excel when the value of the formula not equal to 0. /// TODO - formulas containing cell references are currently not Parsed properly /// </summary> /// <param name="formula">formula for the valued, Compared with the cell</param> /// <returns></returns> public IConditionalFormattingRule CreateConditionalFormattingRule(String formula) { CFRuleRecord rr = CFRuleRecord.Create(_sheet, formula); return new HSSFConditionalFormattingRule(_sheet, rr); } /** * A factory method allowing the creation of conditional formatting * rules using an Icon Set / Multi-State formatting. * The thresholds for it will be created, but will be empty * and require configuring with * {@link HSSFConditionalFormattingRule#getMultiStateFormatting()} * then * {@link HSSFIconMultiStateFormatting#getThresholds()} */ public IConditionalFormattingRule CreateConditionalFormattingRule( IconSet iconSet) { CFRule12Record rr = CFRule12Record.Create(_sheet, iconSet); return new HSSFConditionalFormattingRule(_sheet, rr); } /** * Create a Databar conditional formatting rule. * <p>The thresholds and colour for it will be created, but will be * empty and require configuring with * {@link HSSFConditionalFormattingRule#getDataBarFormatting()} * then * {@link HSSFDataBarFormatting#getMinThreshold()} * and * {@link HSSFDataBarFormatting#getMaxThreshold()} */ public HSSFConditionalFormattingRule CreateConditionalFormattingRule(HSSFExtendedColor color) { CFRule12Record rr = CFRule12Record.Create(_sheet, color.ExtendedColor); return new HSSFConditionalFormattingRule(_sheet, rr); } public IConditionalFormattingRule CreateConditionalFormattingRule(ExtendedColor color) { return CreateConditionalFormattingRule((HSSFExtendedColor)color); } /** * Create a Color Scale / Color Gradient conditional formatting rule. * <p>The thresholds and colours for it will be created, but will be * empty and require configuring with * {@link HSSFConditionalFormattingRule#getColorScaleFormatting()} * then * {@link HSSFColorScaleFormatting#getThresholds()} * and * {@link HSSFColorScaleFormatting#getColors()} */ public IConditionalFormattingRule CreateConditionalFormattingColorScaleRule() { CFRule12Record rr = CFRule12Record.CreateColorScale(_sheet); return new HSSFConditionalFormattingRule(_sheet, rr); } /// <summary> /// Adds a copy of HSSFConditionalFormatting object to the sheet /// This method could be used to copy HSSFConditionalFormatting object /// from one sheet to another. /// </summary> /// <param name="cf">HSSFConditionalFormatting object</param> /// <returns>index of the new Conditional Formatting object</returns> /// <example> /// HSSFConditionalFormatting cf = sheet.GetConditionalFormattingAt(index); /// newSheet.AddConditionalFormatting(cf); /// </example> public int AddConditionalFormatting(HSSFConditionalFormatting cf) { CFRecordsAggregate cfraClone = cf.CFRecordsAggregate.CloneCFAggregate(); return _conditionalFormattingTable.Add(cfraClone); } public int AddConditionalFormatting(IConditionalFormatting cf) { return AddConditionalFormatting((HSSFConditionalFormatting)cf); } /// <summary> /// Allows to Add a new Conditional Formatting Set to the sheet. /// </summary> /// <param name="regions">list of rectangular regions to apply conditional formatting rules</param> /// <param name="cfRules">Set of up to three conditional formatting rules</param> /// <returns>index of the newly Created Conditional Formatting object</returns> public int AddConditionalFormatting(CellRangeAddress[] regions, IConditionalFormattingRule[] cfRules) { if (regions == null) { throw new ArgumentException("regions must not be null"); } if (cfRules == null) { throw new ArgumentException("cfRules must not be null"); } if (cfRules.Length == 0) { throw new ArgumentException("cfRules must not be empty"); } if (cfRules.Length > 3) { throw new ArgumentException("Number of rules must not exceed 3"); } CFRuleBase[] rules = new CFRuleBase[cfRules.Length]; for (int i = 0; i != cfRules.Length; i++) { rules[i] = ((HSSFConditionalFormattingRule)cfRules[i]).CfRuleRecord; } CFRecordsAggregate cfra = new CFRecordsAggregate(regions, rules); return _conditionalFormattingTable.Add(cfra); } public int AddConditionalFormatting(CellRangeAddress[] regions, HSSFConditionalFormattingRule rule1) { return AddConditionalFormatting(regions, rule1 == null ? null : new HSSFConditionalFormattingRule[] { rule1 }); } /// <summary> /// Adds the conditional formatting. /// </summary> /// <param name="regions">The regions.</param> /// <param name="rule1">The rule1.</param> /// <returns></returns> public int AddConditionalFormatting(CellRangeAddress[] regions, IConditionalFormattingRule rule1) { return AddConditionalFormatting(regions, (HSSFConditionalFormattingRule)rule1); } /// <summary> /// Adds the conditional formatting. /// </summary> /// <param name="regions">The regions.</param> /// <param name="rule1">The rule1.</param> /// <param name="rule2">The rule2.</param> /// <returns></returns> public int AddConditionalFormatting(CellRangeAddress[] regions, IConditionalFormattingRule rule1, IConditionalFormattingRule rule2) { return AddConditionalFormatting(regions, new HSSFConditionalFormattingRule[] { (HSSFConditionalFormattingRule)rule1, (HSSFConditionalFormattingRule)rule2 }); } /// <summary> /// Gets Conditional Formatting object at a particular index /// @param index /// of the Conditional Formatting object to fetch /// </summary> /// <param name="index">Conditional Formatting object</param> /// <returns></returns> public IConditionalFormatting GetConditionalFormattingAt(int index) { CFRecordsAggregate cf = _conditionalFormattingTable.Get(index); if (cf == null) { return null; } return new HSSFConditionalFormatting(_sheet, cf); } /// <summary> /// the number of Conditional Formatting objects of the sheet /// </summary> /// <value>The num conditional formattings.</value> public int NumConditionalFormattings { get { return _conditionalFormattingTable.Count; } } /// <summary> /// Removes a Conditional Formatting object by index /// </summary> /// <param name="index">index of a Conditional Formatting object to Remove</param> public void RemoveConditionalFormatting(int index) { _conditionalFormattingTable.Remove(index); } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// PermissionProfile /// </summary> [DataContract] public partial class PermissionProfile : IEquatable<PermissionProfile>, IValidatableObject { public PermissionProfile() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="PermissionProfile" /> class. /// </summary> /// <param name="ModifiedByUsername">.</param> /// <param name="ModifiedDateTime">.</param> /// <param name="PermissionProfileId">.</param> /// <param name="PermissionProfileName">.</param> /// <param name="Settings">Settings.</param> /// <param name="UserCount">.</param> /// <param name="Users">.</param> public PermissionProfile(string ModifiedByUsername = default(string), string ModifiedDateTime = default(string), string PermissionProfileId = default(string), string PermissionProfileName = default(string), AccountRoleSettings Settings = default(AccountRoleSettings), string UserCount = default(string), List<UserInformation> Users = default(List<UserInformation>)) { this.ModifiedByUsername = ModifiedByUsername; this.ModifiedDateTime = ModifiedDateTime; this.PermissionProfileId = PermissionProfileId; this.PermissionProfileName = PermissionProfileName; this.Settings = Settings; this.UserCount = UserCount; this.Users = Users; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="modifiedByUsername", EmitDefaultValue=false)] public string ModifiedByUsername { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="modifiedDateTime", EmitDefaultValue=false)] public string ModifiedDateTime { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="permissionProfileId", EmitDefaultValue=false)] public string PermissionProfileId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="permissionProfileName", EmitDefaultValue=false)] public string PermissionProfileName { get; set; } /// <summary> /// Gets or Sets Settings /// </summary> [DataMember(Name="settings", EmitDefaultValue=false)] public AccountRoleSettings Settings { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="userCount", EmitDefaultValue=false)] public string UserCount { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="users", EmitDefaultValue=false)] public List<UserInformation> Users { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class PermissionProfile {\n"); sb.Append(" ModifiedByUsername: ").Append(ModifiedByUsername).Append("\n"); sb.Append(" ModifiedDateTime: ").Append(ModifiedDateTime).Append("\n"); sb.Append(" PermissionProfileId: ").Append(PermissionProfileId).Append("\n"); sb.Append(" PermissionProfileName: ").Append(PermissionProfileName).Append("\n"); sb.Append(" Settings: ").Append(Settings).Append("\n"); sb.Append(" UserCount: ").Append(UserCount).Append("\n"); sb.Append(" Users: ").Append(Users).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as PermissionProfile); } /// <summary> /// Returns true if PermissionProfile instances are equal /// </summary> /// <param name="other">Instance of PermissionProfile to be compared</param> /// <returns>Boolean</returns> public bool Equals(PermissionProfile other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ModifiedByUsername == other.ModifiedByUsername || this.ModifiedByUsername != null && this.ModifiedByUsername.Equals(other.ModifiedByUsername) ) && ( this.ModifiedDateTime == other.ModifiedDateTime || this.ModifiedDateTime != null && this.ModifiedDateTime.Equals(other.ModifiedDateTime) ) && ( this.PermissionProfileId == other.PermissionProfileId || this.PermissionProfileId != null && this.PermissionProfileId.Equals(other.PermissionProfileId) ) && ( this.PermissionProfileName == other.PermissionProfileName || this.PermissionProfileName != null && this.PermissionProfileName.Equals(other.PermissionProfileName) ) && ( this.Settings == other.Settings || this.Settings != null && this.Settings.Equals(other.Settings) ) && ( this.UserCount == other.UserCount || this.UserCount != null && this.UserCount.Equals(other.UserCount) ) && ( this.Users == other.Users || this.Users != null && this.Users.SequenceEqual(other.Users) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.ModifiedByUsername != null) hash = hash * 59 + this.ModifiedByUsername.GetHashCode(); if (this.ModifiedDateTime != null) hash = hash * 59 + this.ModifiedDateTime.GetHashCode(); if (this.PermissionProfileId != null) hash = hash * 59 + this.PermissionProfileId.GetHashCode(); if (this.PermissionProfileName != null) hash = hash * 59 + this.PermissionProfileName.GetHashCode(); if (this.Settings != null) hash = hash * 59 + this.Settings.GetHashCode(); if (this.UserCount != null) hash = hash * 59 + this.UserCount.GetHashCode(); if (this.Users != null) hash = hash * 59 + this.Users.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// <copyright file="ResamplingWeightedProcessor.Weights.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageSharp.Processing.Processors { using System; using System.Numerics; using System.Runtime.CompilerServices; using ImageSharp.Memory; /// <content> /// Conains the definition of <see cref="WeightsWindow"/> and <see cref="WeightsBuffer"/>. /// </content> internal abstract partial class ResamplingWeightedProcessor<TPixel> { /// <summary> /// Points to a collection of of weights allocated in <see cref="WeightsBuffer"/>. /// </summary> internal struct WeightsWindow { /// <summary> /// The local left index position /// </summary> public int Left; /// <summary> /// The length of the weights window /// </summary> public int Length; /// <summary> /// The index in the destination buffer /// </summary> private readonly int flatStartIndex; /// <summary> /// The buffer containing the weights values. /// </summary> private readonly Buffer<float> buffer; /// <summary> /// Initializes a new instance of the <see cref="WeightsWindow"/> struct. /// </summary> /// <param name="index">The destination index in the buffer</param> /// <param name="left">The local left index</param> /// <param name="buffer">The span</param> /// <param name="length">The length of the window</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal WeightsWindow(int index, int left, Buffer2D<float> buffer, int length) { this.flatStartIndex = (index * buffer.Width) + left; this.Left = left; this.buffer = buffer; this.Length = length; } /// <summary> /// Gets a reference to the first item of the window. /// </summary> /// <returns>The reference to the first item of the window</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref float GetStartReference() { return ref this.buffer[this.flatStartIndex]; } /// <summary> /// Gets the span representing the portion of the <see cref="WeightsBuffer"/> that this window covers /// </summary> /// <returns>The <see cref="Span{T}"/></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<float> GetWindowSpan() => this.buffer.Slice(this.flatStartIndex, this.Length); /// <summary> /// Computes the sum of vectors in 'rowSpan' weighted by weight values, pointed by this <see cref="WeightsWindow"/> instance. /// </summary> /// <param name="rowSpan">The input span of vectors</param> /// <param name="sourceX">The source row position.</param> /// <returns>The weighted sum</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector4 ComputeWeightedRowSum(Span<Vector4> rowSpan, int sourceX) { ref float horizontalValues = ref this.GetStartReference(); int left = this.Left; ref Vector4 vecPtr = ref Unsafe.Add(ref rowSpan.DangerousGetPinnableReference(), left + sourceX); // Destination color components Vector4 result = Vector4.Zero; for (int i = 0; i < this.Length; i++) { float weight = Unsafe.Add(ref horizontalValues, i); Vector4 v = Unsafe.Add(ref vecPtr, i); result += v * weight; } return result; } /// <summary> /// Computes the sum of vectors in 'rowSpan' weighted by weight values, pointed by this <see cref="WeightsWindow"/> instance. /// Applies <see cref="Vector4Extensions.Expand(float)"/> to all input vectors. /// </summary> /// <param name="rowSpan">The input span of vectors</param> /// <param name="sourceX">The source row position.</param> /// <returns>The weighted sum</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector4 ComputeExpandedWeightedRowSum(Span<Vector4> rowSpan, int sourceX) { ref float horizontalValues = ref this.GetStartReference(); int left = this.Left; ref Vector4 vecPtr = ref Unsafe.Add(ref rowSpan.DangerousGetPinnableReference(), left + sourceX); // Destination color components Vector4 result = Vector4.Zero; for (int i = 0; i < this.Length; i++) { float weight = Unsafe.Add(ref horizontalValues, i); Vector4 v = Unsafe.Add(ref vecPtr, i); result += v.Expand() * weight; } return result; } /// <summary> /// Computes the sum of vectors in 'firstPassPixels' at a row pointed by 'x', /// weighted by weight values, pointed by this <see cref="WeightsWindow"/> instance. /// </summary> /// <param name="firstPassPixels">The buffer of input vectors in row first order</param> /// <param name="x">The row position</param> /// <param name="sourceY">The source column position.</param> /// <returns>The weighted sum</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector4 ComputeWeightedColumnSum(Buffer2D<Vector4> firstPassPixels, int x, int sourceY) { ref float verticalValues = ref this.GetStartReference(); int left = this.Left; // Destination color components Vector4 result = Vector4.Zero; for (int i = 0; i < this.Length; i++) { float yw = Unsafe.Add(ref verticalValues, i); int index = left + i + sourceY; result += firstPassPixels[x, index] * yw; } return result; } } /// <summary> /// Holds the <see cref="WeightsWindow"/> values in an optimized contigous memory region. /// </summary> internal class WeightsBuffer : IDisposable { private readonly Buffer2D<float> dataBuffer; /// <summary> /// Initializes a new instance of the <see cref="WeightsBuffer"/> class. /// </summary> /// <param name="sourceSize">The size of the source window</param> /// <param name="destinationSize">The size of the destination window</param> public WeightsBuffer(int sourceSize, int destinationSize) { this.dataBuffer = Buffer2D<float>.CreateClean(sourceSize, destinationSize); this.Weights = new WeightsWindow[destinationSize]; } /// <summary> /// Gets the calculated <see cref="Weights"/> values. /// </summary> public WeightsWindow[] Weights { get; } /// <summary> /// Disposes <see cref="WeightsBuffer"/> instance releasing it's backing buffer. /// </summary> public void Dispose() { this.dataBuffer.Dispose(); } /// <summary> /// Slices a weights value at the given positions. /// </summary> /// <param name="destIdx">The index in destination buffer</param> /// <param name="leftIdx">The local left index value</param> /// <param name="rightIdx">The local right index value</param> /// <returns>The weights</returns> public WeightsWindow GetWeightsWindow(int destIdx, int leftIdx, int rightIdx) { return new WeightsWindow(destIdx, leftIdx, this.dataBuffer, rightIdx - leftIdx + 1); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------------- // // Description: // ContentType class parses and validates the content-type string. // It provides functionality to compare the type/subtype values. // // Details: // Grammar which this class follows - // // Content-type grammar MUST conform to media-type grammar as per // RFC 2616 (ABNF notation): // // media-type = type "/" subtype *( ";" parameter ) // type = token // subtype = token // parameter = attribute "=" value // attribute = token // value = token | quoted-string // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) // qdtext = <any TEXT except <">> // quoted-pair = "\" CHAR // token = 1*<any CHAR except CTLs or separators> // separators = "(" | ")" | "<" | ">" | "@" // | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" // | "{" | "}" | SP | HT // TEXT = <any OCTET except CTLs, but including LWS> // OCTET = <any 8-bit sequence of data> // CHAR = <any US-ASCII character (octets 0 - 127)> // CTL = <any US-ASCII control character(octets 0 - 31)and DEL(127)> // CR = <US-ASCII CR, carriage return (13)> // LF = <US-ASCII LF, linefeed (10)> // SP = <US-ASCII SP, space (32)> // HT = <US-ASCII HT, horizontal-tab (9)> // <"> = <US-ASCII double-quote mark (34)> // LWS = [CRLF] 1*( SP | HT ) // CRLF = CR LF // Linear white space (LWS) MUST NOT be used between the type and subtype, nor // between an attribute and its value. Leading and trailing LWS are prohibited. // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; // For Dictionary<string, string> using System.Text; // For StringBuilder using System.Diagnostics; // For Debug.Assert namespace System.IO.Packaging { /// <summary> /// Content Type class /// </summary> internal sealed class ContentType { //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ #region Internal Constructors /// <summary> /// This constructor creates a ContentType object that represents /// the content-type string. At construction time we validate the /// string as per the grammar specified in RFC 2616. /// Note: We allow empty strings as valid input. Empty string should /// we used more as an indication of an absent/unknown ContentType. /// </summary> /// <param name="contentType">content-type</param> /// <exception cref="ArgumentNullException">If the contentType parameter is null</exception> /// <exception cref="ArgumentException">If the contentType string has leading or /// trailing Linear White Spaces(LWS) characters</exception> /// <exception cref="ArgumentException">If the contentType string invalid CR-LF characters</exception> internal ContentType(string contentType) { if (contentType == null) throw new ArgumentNullException("contentType"); if (String.CompareOrdinal(contentType, String.Empty) == 0) { _contentType = String.Empty; } else { if (IsLinearWhiteSpaceChar(contentType[0]) || IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])) throw new ArgumentException(SR.ContentTypeCannotHaveLeadingTrailingLWS); //Carriage return can be expressed as '\r\n' or '\n\r' //We need to make sure that a \r is accompanied by \n ValidateCarriageReturns(contentType); //Begin Parsing int semiColonIndex = contentType.IndexOf(SemicolonSeparator); if (semiColonIndex == -1) { // Parse content type similar to - type/subtype ParseTypeAndSubType(contentType); } else { // Parse content type similar to - type/subtype ; param1=value1 ; param2=value2 ; param3="value3" ParseTypeAndSubType(contentType.Substring(0, semiColonIndex)); ParseParameterAndValue(contentType.Substring(semiColonIndex)); } } // keep this untouched for return from OriginalString property _originalString = contentType; //This variable is used to print out the correct content type string representation //using the ToString method. This is mainly important while debugging and seeing the //value of the content type object in the debugger. _isInitialized = true; } #endregion Internal Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Properties /// <summary> /// TypeComponent of the Content Type /// If the content type is "text/xml". This property will return "text" /// </summary> internal string TypeComponent { get { return _type; } } /// <summary> /// SubType component /// If the content type is "text/xml". This property will return "xml" /// </summary> internal string SubTypeComponent { get { return _subType; } } /// <summary> /// Enumerator which iterates over the Parameter and Value pairs which are stored /// in a dictionary. We hand out just the enumerator in order to make this property /// ReadOnly /// Consider following Content type - /// type/subtype ; param1=value1 ; param2=value2 ; param3="value3" /// This will return a enumerator over a dictionary of the parameter/value pairs. /// </summary> internal Dictionary<string, string>.Enumerator ParameterValuePairs { get { EnsureParameterDictionary(); return _parameterDictionary.GetEnumerator(); } } #endregion Internal Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <summary> /// This method does a strong comparison of the content types, as parameters are not allowed. /// We only compare the type and subType values in an ASCII case-insensitive manner. /// Parameters are not allowed to be present on any of the content type operands. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType) { return AreTypeAndSubTypeEqual(contentType, false); } /// <summary> /// This method does a weak comparison of the content types. We only compare the /// type and subType values in an ASCII case-insensitive manner. /// Parameter and value pairs are not used for the comparison. /// If you wish to compare the paramters too, then you must get the ParameterValuePairs from /// both the ContentType objects and compare each parameter entry. /// The allowParameterValuePairs parameter is used to indicate whether the /// comparison is tolerant to parameters being present or no. /// </summary> /// <param name="contentType">Content type to be compared with</param> /// <param name="allowParameterValuePairs">If true, allows the presence of parameter value pairs. /// If false, parameter/value pairs cannot be present in the content type string. /// In either case, the parameter value pair is not used for the comparison.</param> /// <returns></returns> internal bool AreTypeAndSubTypeEqual(ContentType contentType, bool allowParameterValuePairs) { bool result = false; if (contentType != null) { if (!allowParameterValuePairs) { //Return false if this content type object has parameters if (_parameterDictionary != null) { if (_parameterDictionary.Count > 0) return false; } //Return false if the content type object passed in has parameters Dictionary<string, string>.Enumerator contentTypeEnumerator; contentTypeEnumerator = contentType.ParameterValuePairs; contentTypeEnumerator.MoveNext(); if (contentTypeEnumerator.Current.Key != null) return false; } // Perform a case-insensitive comparison on the type/subtype strings. This is a // safe comparison because the _type and _subType strings have been restricted to // ASCII characters, digits, and a small set of symbols. This is not a safe comparison // for the broader set of strings that have not been restricted in the same way. result = (String.Compare(_type, contentType.TypeComponent, StringComparison.OrdinalIgnoreCase) == 0 && String.Compare(_subType, contentType.SubTypeComponent, StringComparison.OrdinalIgnoreCase) == 0); } return result; } /// <summary> /// ToString - outputs a normalized form of the content type string /// </summary> /// <returns></returns> public override string ToString() { if (_contentType == null) { //This is needed so that while debugging we get the correct //string if (!_isInitialized) return String.Empty; Debug.Assert(String.CompareOrdinal(_type, String.Empty) != 0 || String.CompareOrdinal(_subType, String.Empty) != 0); StringBuilder stringBuilder = new StringBuilder(_type); stringBuilder.Append(s_forwardSlashSeparator[0]); stringBuilder.Append(_subType); if (_parameterDictionary != null && _parameterDictionary.Count > 0) { foreach (string paramterKey in _parameterDictionary.Keys) { stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(SemicolonSeparator); stringBuilder.Append(s_linearWhiteSpaceChars[0]); stringBuilder.Append(paramterKey); stringBuilder.Append(EqualSeparator); stringBuilder.Append(_parameterDictionary[paramterKey]); } } _contentType = stringBuilder.ToString(); } return _contentType; } #endregion Internal Methods //------------------------------------------------------ // // Nested Classes // //------------------------------------------------------ #region Nested Classes /// <summary> /// Comparer class makes it easier to put ContentType objects in collections. /// Only compares type and subtype components of the ContentType. Could be /// expanded to optionally compare parameters as well. /// </summary> internal class StrongComparer : IEqualityComparer<ContentType> { /// <summary> /// This method does a strong comparison of the content types. /// Only compares the ContentTypes' type and subtype components. /// </summary> public bool Equals(ContentType x, ContentType y) { if (x == null) { return (y == null); } else { return x.AreTypeAndSubTypeEqual(y); } } /// <summary> /// We lower case the results of ToString() because it returns the original /// casing passed into the constructor. ContentTypes that are equal (which /// ignores casing) must have the same hash code. /// </summary> public int GetHashCode(ContentType obj) { return obj.ToString().ToUpperInvariant().GetHashCode(); } } internal class WeakComparer : IEqualityComparer<ContentType> { /// <summary> /// This method does a weak comparison of the content types. /// Parameter and value pairs are not used for the comparison. /// </summary> public bool Equals(ContentType x, ContentType y) { if (x == null) { return (y == null); } else { return x.AreTypeAndSubTypeEqual(y, true); } } /// <summary> /// We lower case the results of ToString() because it returns the original /// casing passed into the constructor. ContentTypes that are equal (which /// ignores casing) must have the same hash code. /// </summary> public int GetHashCode(ContentType obj) { return obj._type.ToUpperInvariant().GetHashCode() ^ obj._subType.ToUpperInvariant().GetHashCode(); } } #endregion Nested Classes //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods /// <summary> /// This method validates if the content type string has /// valid CR-LF characters. Specifically we test if '\r' is /// accompanied by a '\n' in the string, else its an error. /// </summary> /// <param name="contentType"></param> private static void ValidateCarriageReturns(string contentType) { Debug.Assert(!IsLinearWhiteSpaceChar(contentType[0]) && !IsLinearWhiteSpaceChar(contentType[contentType.Length - 1])); //Prior to calling this method we have already checked that first and last //character of the content type are not Linear White Spaces. So its safe to //assume that the index will be greater than 0 and less that length-2. int index = contentType.IndexOf(s_linearWhiteSpaceChars[2]); while (index != -1) { if (contentType[index - 1] == s_linearWhiteSpaceChars[1] || contentType[index + 1] == s_linearWhiteSpaceChars[1]) { index = contentType.IndexOf(s_linearWhiteSpaceChars[2], ++index); } else throw new ArgumentException(SR.InvalidLinearWhiteSpaceCharacter); } } /// <summary> /// Parses the type ans subType tokens from the string. /// Also verifies if the Tokens are valid as per the grammar. /// </summary> /// <param name="typeAndSubType">substring that has the type and subType of the content type</param> /// <exception cref="ArgumentException">If the typeAndSubType parameter does not have the "/" character</exception> private void ParseTypeAndSubType(string typeAndSubType) { //okay to trim at this point the end of the string as Linear White Spaces(LWS) chars are allowed here. typeAndSubType = typeAndSubType.TrimEnd(s_linearWhiteSpaceChars); string[] splitBasedOnForwardSlash = typeAndSubType.Split(s_forwardSlashSeparator); if (splitBasedOnForwardSlash.Length != 2) throw new ArgumentException(SR.InvalidTypeSubType); _type = ValidateToken(splitBasedOnForwardSlash[0]); _subType = ValidateToken(splitBasedOnForwardSlash[1]); } /// <summary> /// Parse the individual parameter=value strings /// </summary> /// <param name="parameterAndValue">This string has the parameter and value pair of the form /// parameter=value</param> /// <exception cref="ArgumentException">If the string does not have the required "="</exception> private void ParseParameterAndValue(string parameterAndValue) { while (String.CompareOrdinal(parameterAndValue, String.Empty) != 0) { //At this point the first character MUST be a semi-colon //First time through this test is serving more as an assert. if (parameterAndValue[0] != SemicolonSeparator) throw new ArgumentException(SR.ExpectingSemicolon); //At this point if we have just one semicolon, then its an error. //Also, there can be no trailing LWS characters, as we already checked for that //in the constructor. if (parameterAndValue.Length == 1) throw new ArgumentException(SR.ExpectingParameterValuePairs); //Removing the leading ; from the string parameterAndValue = parameterAndValue.Substring(1); //okay to trim start as there can be spaces before the begining //of the parameter name. parameterAndValue = parameterAndValue.TrimStart(s_linearWhiteSpaceChars); int equalSignIndex = parameterAndValue.IndexOf(EqualSeparator); if (equalSignIndex <= 0 || equalSignIndex == (parameterAndValue.Length - 1)) throw new ArgumentException(SR.InvalidParameterValuePair); int parameterStartIndex = equalSignIndex + 1; //Get length of the parameter value int parameterValueLength = GetLengthOfParameterValue(parameterAndValue, parameterStartIndex); EnsureParameterDictionary(); _parameterDictionary.Add( ValidateToken(parameterAndValue.Substring(0, equalSignIndex)), ValidateQuotedStringOrToken(parameterAndValue.Substring(parameterStartIndex, parameterValueLength))); parameterAndValue = parameterAndValue.Substring(parameterStartIndex + parameterValueLength).TrimStart(s_linearWhiteSpaceChars); } } /// <summary> /// This method returns the length of the first parameter value in the input string. /// </summary> /// <param name="s"></param> /// <param name="startIndex">Starting index for parsing</param> /// <returns></returns> private static int GetLengthOfParameterValue(string s, int startIndex) { Debug.Assert(s != null); int length = 0; //if the parameter value does not start with a '"' then, //we expect a valid token. So we look for Linear White Spaces or //a ';' as the terminator for the token value. if (s[startIndex] != '"') { int semicolonIndex = s.IndexOf(SemicolonSeparator, startIndex); if (semicolonIndex != -1) { int lwsIndex = s.IndexOfAny(s_linearWhiteSpaceChars, startIndex); if (lwsIndex != -1 && lwsIndex < semicolonIndex) length = lwsIndex; else length = semicolonIndex; } else length = semicolonIndex; //If there is no linear white space found we treat the entire remaining string as //parameter value. if (length == -1) length = s.Length; } else { //if the parameter value starts with a '"' then, we need to look for the //pairing '"' that is not preceded by a "\" ["\" is used to escape the '"'] bool found = false; length = startIndex; while (!found) { length = s.IndexOf('"', ++length); if (length == -1) throw new ArgumentException(SR.InvalidParameterValue); if (s[length - 1] != '\\') { found = true; length++; } } } return length - startIndex; } /// <summary> /// Validating the given token /// The following checks are being made - /// 1. If all the characters in the token are either ASCII letter or digit. /// 2. If all the characters in the token are either from the remaining allowed cha----ter set. /// </summary> /// <param name="token">string token</param> /// <returns>validated string token</returns> /// <exception cref="ArgumentException">If the token is Empty</exception> private static string ValidateToken(string token) { if (String.CompareOrdinal(token, String.Empty) == 0) throw new ArgumentException(SR.InvalidToken); for (int i = 0; i < token.Length; i++) { if (IsAsciiLetterOrDigit(token[i])) { continue; } else { if (IsAllowedCharacter(token[i])) { continue; } else { throw new ArgumentException(SR.InvalidToken); } } } return token; } /// <summary> /// Validating if the value of a parameter is either a valid token or a /// valid quoted string /// </summary> /// <param name="parameterValue">paramter value string</param> /// <returns>validate parameter value string</returns> /// <exception cref="ArgumentException">If the paramter value is empty</exception> private static string ValidateQuotedStringOrToken(string parameterValue) { if (String.CompareOrdinal(parameterValue, String.Empty) == 0) throw new ArgumentException(SR.InvalidParameterValue); if (parameterValue.Length >= 2 && parameterValue.StartsWith(Quote, StringComparison.Ordinal) && parameterValue.EndsWith(Quote, StringComparison.Ordinal)) ValidateQuotedText(parameterValue.Substring(1, parameterValue.Length - 2)); else ValidateToken(parameterValue); return parameterValue; } /// <summary> /// This method validates if the text in the quoted string /// </summary> /// <param name="quotedText"></param> private static void ValidateQuotedText(string quotedText) { //empty is okay for (int i = 0; i < quotedText.Length; i++) { if (IsLinearWhiteSpaceChar(quotedText[i])) continue; if (quotedText[i] <= ' ' || quotedText[i] >= 0xFF) throw new ArgumentException(SR.InvalidParameterValue); else if (quotedText[i] == '"' && (i == 0 || quotedText[i - 1] != '\\')) throw new ArgumentException(SR.InvalidParameterValue); } } /// <summary> /// Returns true if the input character is an allowed character /// Returns false if the input cha----ter is not an allowed character /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAllowedCharacter(char character) { //We did not use any of the .Contains methods as //it will result in boxing costs. foreach (char c in s_allowedCharacters) { if (c == character) return true; } return false; } /// <summary> /// Returns true if the input character is an ASCII digit or letter /// Returns false if the input character is not an ASCII digit or letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetterOrDigit(char character) { if (IsAsciiLetter(character)) { return true; } if (character >= '0') { return (character <= '9'); } return false; } /// <summary> /// Returns true if the input character is an ASCII letter /// Returns false if the input character is not an ASCII letter /// </summary> /// <param name="character">input character</param> /// <returns></returns> private static bool IsAsciiLetter(char character) { if ((character >= 'a') && (character <= 'z')) { return true; } if (character >= 'A') { return (character <= 'Z'); } return false; } /// <summary> /// Returns true if the input character is one of the Linear White Space characters - /// ' ', '\t', '\n', '\r' /// Returns false if the input character is none of the above /// </summary> /// <param name="ch">input character</param> /// <returns></returns> private static bool IsLinearWhiteSpaceChar(char ch) { if (ch > ' ') { return false; } foreach (char c in s_linearWhiteSpaceChars) { if (ch == c) return true; } return false; } /// <summary> /// Lazy initialization for the ParameterDictionary /// </summary> private void EnsureParameterDictionary() { if (_parameterDictionary == null) { _parameterDictionary = new Dictionary<string, string>(); //initial size 0 } } #endregion Private Methods //------------------------------------------------------ // // Private Members // //------------------------------------------------------ #region Private Members private string _contentType = null; private string _type = String.Empty; private string _subType = String.Empty; private string _originalString; private Dictionary<string, string> _parameterDictionary = null; private bool _isInitialized = false; private const string Quote = "\""; private const char SemicolonSeparator = ';'; private const char EqualSeparator = '='; //This array is sorted by the ascii value of these characters. private static readonly char[] s_allowedCharacters = { '!' /*33*/, '#' /*35*/ , '$' /*36*/, '%' /*37*/, '&' /*38*/ , '\'' /*39*/, '*' /*42*/, '+' /*43*/ , '-' /*45*/, '.' /*46*/, '^' /*94*/ , '_' /*95*/, '`' /*96*/, '|' /*124*/, '~' /*126*/, }; private static readonly char[] s_forwardSlashSeparator = { '/' }; //Linear White Space characters private static readonly char[] s_linearWhiteSpaceChars = { ' ', // space - \x20 '\n', // new line - \x0A '\r', // carriage return - \x0D '\t' // horizontal tab - \x09 }; #endregion Private Members } }
/* * Copyright (c) 1999 World Wide Web Consortium, * (Massachusetts Institute of Technology, Institut National de Recherche * en Informatique et en Automatique, Keio University). * All Rights Reserved. http://www.w3.org/Consortium/Legal/ */ using System; using org.w3c.dom.views; namespace org.w3c.dom.events { /** * The <code>KeyEvent</code> interface provides specific contextual * information associated with Key events. * @since DOM Level 2 */ public interface KeyEvent : UIEvent { /** * <code>ctrlKey</code> indicates whether the 'ctrl' key was depressed * during the firing of the event. */ bool getCtrlKey(); /** * <code>shiftKey</code> indicates whether the 'shift' key was depressed * during the firing of the event. */ bool getShiftKey(); /** * <code>altKey</code> indicates whether the 'alt' key was depressed during * the firing of the event. On some platforms this key may map to an * alternative key name. */ bool getAltKey(); /** * <code>metaKey</code> indicates whether the 'meta' key was depressed * during the firing of the event. On some platforms this key may map to * an alternative key name. */ bool getMetaKey(); /** * The value of <code>keyCode</code> holds the virtual key code value of * the key which was depressed if the event is a key event. Otherwise, the * value is zero. */ int getKeyCode(); /** * <code>charCode</code> holds the value of the Unicode character * associated with the depressed key if the event is a key event. * Otherwise, the value is zero. */ int getCharCode(); /** * * @param typeArg Specifies the event type. * @param canBubbleArg Specifies whether or not the event can bubble. * @param cancelableArg Specifies whether or not the event's default action * can be prevent. * @param ctrlKeyArg Specifies whether or not control key was depressed * during the <code>Event</code>. * @param altKeyArg Specifies whether or not alt key was depressed during * the <code>Event</code>. * @param shiftKeyArg Specifies whether or not shift key was depressed * during the <code>Event</code>. * @param metaKeyArg Specifies whether or not meta key was depressed during * the <code>Event</code>. * @param keyCodeArg Specifies the <code>Event</code>'s <code>keyCode</code> * @param charCodeArg Specifies the <code>Event</code>'s * <code>charCode</code> * @param viewArg Specifies the <code>Event</code>'s * <code>AbstractView</code>. */ void initKeyEvent(String typeArg, bool canBubbleArg, bool cancelableArg, bool ctrlKeyArg, bool altKeyArg, bool shiftKeyArg, bool metaKeyArg, int keyCodeArg, int charCodeArg, AbstractView viewArg); } public sealed class KeyEventConstants { // VirtualKeyCode public const int CHAR_UNDEFINED = 0x0FFFF; public const int DOM_VK_0 = 0x30; public const int DOM_VK_1 = 0x31; public const int DOM_VK_2 = 0x32; public const int DOM_VK_3 = 0x33; public const int DOM_VK_4 = 0x34; public const int DOM_VK_5 = 0x35; public const int DOM_VK_6 = 0x36; public const int DOM_VK_7 = 0x37; public const int DOM_VK_8 = 0x38; public const int DOM_VK_9 = 0x39; public const int DOM_VK_A = 0x41; public const int DOM_VK_ACCEPT = 0x1E; public const int DOM_VK_ADD = 0x6B; public const int DOM_VK_AGAIN = 0xFFC9; public const int DOM_VK_ALL_CANDIDATES = 0x0100; public const int DOM_VK_ALPHANUMERIC = 0x00F0; public const int DOM_VK_ALT = 0x12; public const int DOM_VK_ALT_GRAPH = 0xFF7E; public const int DOM_VK_AMPERSAND = 0x96; public const int DOM_VK_ASTERISK = 0x97; public const int DOM_VK_AT = 0x0200; public const int DOM_VK_B = 0x42; public const int DOM_VK_BACK_QUOTE = 0xC0; public const int DOM_VK_BACK_SLASH = 0x5C; public const int DOM_VK_BACK_SPACE = 0x08; public const int DOM_VK_BRACELEFT = 0xA1; public const int DOM_VK_BRACERIGHT = 0xA2; public const int DOM_VK_C = 0x43; public const int DOM_VK_CANCEL = 0x03; public const int DOM_VK_CAPS_LOCK = 0x14; public const int DOM_VK_CIRCUMFLEX = 0x0202; public const int DOM_VK_CLEAR = 0x0C; public const int DOM_VK_CLOSE_BRACKET = 0x5D; public const int DOM_VK_CODE_INPUT = 0x0102; public const int DOM_VK_COLON = 0x0201; public const int DOM_VK_COMMA = 0x2C; public const int DOM_VK_COMPOSE = 0xFF20; public const int DOM_VK_CONTROL = 0x11; public const int DOM_VK_CONVERT = 0x1C; public const int DOM_VK_COPY = 0xFFCD; public const int DOM_VK_CUT = 0xFFD1; public const int DOM_VK_D = 0x44; public const int DOM_VK_DEAD_ABOVEDOT = 0x86; public const int DOM_VK_DEAD_ABOVERING = 0x88; public const int DOM_VK_DEAD_ACUTE = 0x81; public const int DOM_VK_DEAD_BREVE = 0x85; public const int DOM_VK_DEAD_CARON = 0x8A; public const int DOM_VK_DEAD_CEDILLA = 0x8B; public const int DOM_VK_DEAD_CIRCUMFLEX = 0x82; public const int DOM_VK_DEAD_DIAERESIS = 0x87; public const int DOM_VK_DEAD_DOUBLEACUTE = 0x89; public const int DOM_VK_DEAD_GRAVE = 0x80; public const int DOM_VK_DEAD_IOTA = 0x8D; public const int DOM_VK_DEAD_MACRON = 0x84; public const int DOM_VK_DEAD_OGONEK = 0x8C; public const int DOM_VK_DEAD_SEMIVOICED_SOUND = 0x8F; public const int DOM_VK_DEAD_TILDE = 0x83; public const int DOM_VK_DEAD_VOICED_SOUND = 0x8E; public const int DOM_VK_DECIMAL = 0x6E; public const int DOM_VK_DELETE = 0x7F; public const int DOM_VK_DIVIDE = 0x6F; public const int DOM_VK_DOLLAR = 0x0203; public const int DOM_VK_DOWN = 0x28; public const int DOM_VK_E = 0x45; public const int DOM_VK_END = 0x23; public const int DOM_VK_ENTER = 0x0D; public const int DOM_VK_EQUALS = 0x3D; public const int DOM_VK_ESCAPE = 0x1B; public const int DOM_VK_EURO_SIGN = 0x0204; public const int DOM_VK_EXCLAMATION_MARK = 0x0205; public const int DOM_VK_F = 0x46; public const int DOM_VK_F1 = 0x70; public const int DOM_VK_F10 = 0x79; public const int DOM_VK_F11 = 0x7A; public const int DOM_VK_F12 = 0x7B; public const int DOM_VK_F13 = 0xF000; public const int DOM_VK_F14 = 0xF001; public const int DOM_VK_F15 = 0xF002; public const int DOM_VK_F16 = 0xF003; public const int DOM_VK_F17 = 0xF004; public const int DOM_VK_F18 = 0xF005; public const int DOM_VK_F19 = 0xF006; public const int DOM_VK_F2 = 0x71; public const int DOM_VK_F20 = 0xF007; public const int DOM_VK_F21 = 0xF008; public const int DOM_VK_F22 = 0xF009; public const int DOM_VK_F23 = 0xF00A; public const int DOM_VK_F24 = 0xF00B; public const int DOM_VK_F3 = 0x72; public const int DOM_VK_F4 = 0x73; public const int DOM_VK_F5 = 0x74; public const int DOM_VK_F6 = 0x75; public const int DOM_VK_F7 = 0x76; public const int DOM_VK_F8 = 0x77; public const int DOM_VK_F9 = 0x78; public const int DOM_VK_FINAL = 0x18; public const int DOM_VK_FIND = 0xFFD0; public const int DOM_VK_FULL_WIDTH = 0x00F3; public const int DOM_VK_G = 0x47; public const int DOM_VK_GREATER = 0xA0; public const int DOM_VK_H = 0x48; public const int DOM_VK_HALF_WIDTH = 0x00F4; public const int DOM_VK_HELP = 0x9C; public const int DOM_VK_HIRAGANA = 0x00F2; public const int DOM_VK_HOME = 0x24; public const int DOM_VK_I = 0x49; public const int DOM_VK_INSERT = 0x9B; public const int DOM_VK_INVERTED_EXCLAMATION_MARK = 0x0206; public const int DOM_VK_J = 0x4A; public const int DOM_VK_JAPANESE_HIRAGANA = 0x0104; public const int DOM_VK_JAPANESE_KATAKANA = 0x0103; public const int DOM_VK_JAPANESE_ROMAN = 0x0105; public const int DOM_VK_K = 0x4B; public const int DOM_VK_KANA = 0x15; public const int DOM_VK_KANJI = 0x19; public const int DOM_VK_KATAKANA = 0x00F1; public const int DOM_VK_KP_DOWN = 0xE1; public const int DOM_VK_KP_LEFT = 0xE2; public const int DOM_VK_KP_RIGHT = 0xE3; public const int DOM_VK_KP_UP = 0xE0; public const int DOM_VK_L = 0x4C; public const int DOM_VK_LEFT = 0x25; public const int DOM_VK_LEFT_PARENTHESIS = 0x0207; public const int DOM_VK_LESS = 0x99; public const int DOM_VK_M = 0x4D; public const int DOM_VK_META = 0x9D; public const int DOM_VK_MINUS = 0x2D; public const int DOM_VK_MODECHANGE = 0x1F; public const int DOM_VK_MULTIPLY = 0x6A; public const int DOM_VK_N = 0x4E; public const int DOM_VK_NONCONVERT = 0x1D; public const int DOM_VK_NUM_LOCK = 0x90; public const int DOM_VK_NUMBER_SIGN = 0x0208; public const int DOM_VK_NUMPAD0 = 0x60; public const int DOM_VK_NUMPAD1 = 0x61; public const int DOM_VK_NUMPAD2 = 0x62; public const int DOM_VK_NUMPAD3 = 0x63; public const int DOM_VK_NUMPAD4 = 0x64; public const int DOM_VK_NUMPAD5 = 0x65; public const int DOM_VK_NUMPAD6 = 0x66; public const int DOM_VK_NUMPAD7 = 0x67; public const int DOM_VK_NUMPAD8 = 0x68; public const int DOM_VK_NUMPAD9 = 0x69; public const int DOM_VK_O = 0x4F; public const int DOM_VK_OPEN_BRACKET = 0x5B; public const int DOM_VK_P = 0x50; public const int DOM_VK_PAGE_DOWN = 0x22; public const int DOM_VK_PAGE_UP = 0x21; public const int DOM_VK_PASTE = 0xFFCF; public const int DOM_VK_PAUSE = 0x13; public const int DOM_VK_PERIOD = 0x2E; public const int DOM_VK_PLUS = 0x0209; public const int DOM_VK_PREVIOUS_CANDIDATE = 0x0101; public const int DOM_VK_PRINTSCREEN = 0x9A; public const int DOM_VK_PROPS = 0xFFCA; public const int DOM_VK_Q = 0x51; public const int DOM_VK_QUOTE = 0xDE; public const int DOM_VK_QUOTEDBL = 0x98; public const int DOM_VK_R = 0x52; public const int DOM_VK_RIGHT = 0x27; public const int DOM_VK_RIGHT_PARENTHESIS = 0x020A; public const int DOM_VK_ROMAN_CHARACTERS = 0x00F5; public const int DOM_VK_S = 0x53; public const int DOM_VK_SCROLL_LOCK = 0x91; public const int DOM_VK_SEMICOLON = 0x3B; public const int DOM_VK_SEPARATER = 0x6C; public const int DOM_VK_SHIFT = 0x10; public const int DOM_VK_SLASH = 0x2F; public const int DOM_VK_SPACE = 0x20; public const int DOM_VK_STOP = 0xFFC8; public const int DOM_VK_SUBTRACT = 0x6D; public const int DOM_VK_T = 0x54; public const int DOM_VK_TAB = 0x09; public const int DOM_VK_U = 0x55; public const int DOM_VK_UNDEFINED = 0x0; public const int DOM_VK_UNDERSCORE = 0x020B; public const int DOM_VK_UNDO = 0xFFCB; public const int DOM_VK_UP = 0x26; public const int DOM_VK_V = 0x56; public const int DOM_VK_W = 0x57; public const int DOM_VK_X = 0x58; public const int DOM_VK_Y = 0x59; public const int DOM_VK_Z = 0x5A; } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the HidHidatidosi class. /// </summary> [Serializable] public partial class HidHidatidosiCollection : ActiveList<HidHidatidosi, HidHidatidosiCollection> { public HidHidatidosiCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>HidHidatidosiCollection</returns> public HidHidatidosiCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { HidHidatidosi o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Hid_Hidatidosis table. /// </summary> [Serializable] public partial class HidHidatidosi : ActiveRecord<HidHidatidosi>, IActiveRecord { #region .ctors and Default Settings public HidHidatidosi() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public HidHidatidosi(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public HidHidatidosi(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public HidHidatidosi(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Hid_Hidatidosis", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdHidatidosis = new TableSchema.TableColumn(schema); colvarIdHidatidosis.ColumnName = "idHidatidosis"; colvarIdHidatidosis.DataType = DbType.Int32; colvarIdHidatidosis.MaxLength = 0; colvarIdHidatidosis.AutoIncrement = true; colvarIdHidatidosis.IsNullable = false; colvarIdHidatidosis.IsPrimaryKey = true; colvarIdHidatidosis.IsForeignKey = false; colvarIdHidatidosis.IsReadOnly = false; colvarIdHidatidosis.DefaultSetting = @""; colvarIdHidatidosis.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdHidatidosis); TableSchema.TableColumn colvarIdEstablecimiento = new TableSchema.TableColumn(schema); colvarIdEstablecimiento.ColumnName = "idEstablecimiento"; colvarIdEstablecimiento.DataType = DbType.Int32; colvarIdEstablecimiento.MaxLength = 0; colvarIdEstablecimiento.AutoIncrement = false; colvarIdEstablecimiento.IsNullable = false; colvarIdEstablecimiento.IsPrimaryKey = false; colvarIdEstablecimiento.IsForeignKey = false; colvarIdEstablecimiento.IsReadOnly = false; colvarIdEstablecimiento.DefaultSetting = @""; colvarIdEstablecimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstablecimiento); TableSchema.TableColumn colvarDocente = new TableSchema.TableColumn(schema); colvarDocente.ColumnName = "docente"; colvarDocente.DataType = DbType.String; colvarDocente.MaxLength = 100; colvarDocente.AutoIncrement = false; colvarDocente.IsNullable = true; colvarDocente.IsPrimaryKey = false; colvarDocente.IsForeignKey = false; colvarDocente.IsReadOnly = false; colvarDocente.DefaultSetting = @""; colvarDocente.ForeignKeyTableName = ""; schema.Columns.Add(colvarDocente); TableSchema.TableColumn colvarNombrePaciente = new TableSchema.TableColumn(schema); colvarNombrePaciente.ColumnName = "nombrePaciente"; colvarNombrePaciente.DataType = DbType.String; colvarNombrePaciente.MaxLength = 100; colvarNombrePaciente.AutoIncrement = false; colvarNombrePaciente.IsNullable = true; colvarNombrePaciente.IsPrimaryKey = false; colvarNombrePaciente.IsForeignKey = false; colvarNombrePaciente.IsReadOnly = false; colvarNombrePaciente.DefaultSetting = @""; colvarNombrePaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombrePaciente); TableSchema.TableColumn colvarApellidoPaciente = new TableSchema.TableColumn(schema); colvarApellidoPaciente.ColumnName = "apellidoPaciente"; colvarApellidoPaciente.DataType = DbType.String; colvarApellidoPaciente.MaxLength = 100; colvarApellidoPaciente.AutoIncrement = false; colvarApellidoPaciente.IsNullable = true; colvarApellidoPaciente.IsPrimaryKey = false; colvarApellidoPaciente.IsForeignKey = false; colvarApellidoPaciente.IsReadOnly = false; colvarApellidoPaciente.DefaultSetting = @""; colvarApellidoPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellidoPaciente); TableSchema.TableColumn colvarDniPaciente = new TableSchema.TableColumn(schema); colvarDniPaciente.ColumnName = "dniPaciente"; colvarDniPaciente.DataType = DbType.String; colvarDniPaciente.MaxLength = 10; colvarDniPaciente.AutoIncrement = false; colvarDniPaciente.IsNullable = true; colvarDniPaciente.IsPrimaryKey = false; colvarDniPaciente.IsForeignKey = false; colvarDniPaciente.IsReadOnly = false; colvarDniPaciente.DefaultSetting = @""; colvarDniPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarDniPaciente); TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema); colvarFechaNacimiento.ColumnName = "fechaNacimiento"; colvarFechaNacimiento.DataType = DbType.DateTime; colvarFechaNacimiento.MaxLength = 0; colvarFechaNacimiento.AutoIncrement = false; colvarFechaNacimiento.IsNullable = true; colvarFechaNacimiento.IsPrimaryKey = false; colvarFechaNacimiento.IsForeignKey = false; colvarFechaNacimiento.IsReadOnly = false; colvarFechaNacimiento.DefaultSetting = @""; colvarFechaNacimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaNacimiento); TableSchema.TableColumn colvarDomicilioPaciente = new TableSchema.TableColumn(schema); colvarDomicilioPaciente.ColumnName = "domicilioPaciente"; colvarDomicilioPaciente.DataType = DbType.String; colvarDomicilioPaciente.MaxLength = 100; colvarDomicilioPaciente.AutoIncrement = false; colvarDomicilioPaciente.IsNullable = true; colvarDomicilioPaciente.IsPrimaryKey = false; colvarDomicilioPaciente.IsForeignKey = false; colvarDomicilioPaciente.IsReadOnly = false; colvarDomicilioPaciente.DefaultSetting = @""; colvarDomicilioPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarDomicilioPaciente); TableSchema.TableColumn colvarTelefonoPaciente = new TableSchema.TableColumn(schema); colvarTelefonoPaciente.ColumnName = "telefonoPaciente"; colvarTelefonoPaciente.DataType = DbType.String; colvarTelefonoPaciente.MaxLength = 20; colvarTelefonoPaciente.AutoIncrement = false; colvarTelefonoPaciente.IsNullable = true; colvarTelefonoPaciente.IsPrimaryKey = false; colvarTelefonoPaciente.IsForeignKey = false; colvarTelefonoPaciente.IsReadOnly = false; colvarTelefonoPaciente.DefaultSetting = @""; colvarTelefonoPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarTelefonoPaciente); TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema); colvarObservaciones.ColumnName = "observaciones"; colvarObservaciones.DataType = DbType.AnsiString; colvarObservaciones.MaxLength = -1; colvarObservaciones.AutoIncrement = false; colvarObservaciones.IsNullable = true; colvarObservaciones.IsPrimaryKey = false; colvarObservaciones.IsForeignKey = false; colvarObservaciones.IsReadOnly = false; colvarObservaciones.DefaultSetting = @""; colvarObservaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservaciones); TableSchema.TableColumn colvarNombrePadre = new TableSchema.TableColumn(schema); colvarNombrePadre.ColumnName = "nombrePadre"; colvarNombrePadre.DataType = DbType.String; colvarNombrePadre.MaxLength = 100; colvarNombrePadre.AutoIncrement = false; colvarNombrePadre.IsNullable = true; colvarNombrePadre.IsPrimaryKey = false; colvarNombrePadre.IsForeignKey = false; colvarNombrePadre.IsReadOnly = false; colvarNombrePadre.DefaultSetting = @""; colvarNombrePadre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombrePadre); TableSchema.TableColumn colvarApellidoPadre = new TableSchema.TableColumn(schema); colvarApellidoPadre.ColumnName = "apellidoPadre"; colvarApellidoPadre.DataType = DbType.String; colvarApellidoPadre.MaxLength = 100; colvarApellidoPadre.AutoIncrement = false; colvarApellidoPadre.IsNullable = true; colvarApellidoPadre.IsPrimaryKey = false; colvarApellidoPadre.IsForeignKey = false; colvarApellidoPadre.IsReadOnly = false; colvarApellidoPadre.DefaultSetting = @""; colvarApellidoPadre.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellidoPadre); TableSchema.TableColumn colvarDniPadre = new TableSchema.TableColumn(schema); colvarDniPadre.ColumnName = "dniPadre"; colvarDniPadre.DataType = DbType.String; colvarDniPadre.MaxLength = 10; colvarDniPadre.AutoIncrement = false; colvarDniPadre.IsNullable = true; colvarDniPadre.IsPrimaryKey = false; colvarDniPadre.IsForeignKey = false; colvarDniPadre.IsReadOnly = false; colvarDniPadre.DefaultSetting = @""; colvarDniPadre.ForeignKeyTableName = ""; schema.Columns.Add(colvarDniPadre); TableSchema.TableColumn colvarResultadoRastreo = new TableSchema.TableColumn(schema); colvarResultadoRastreo.ColumnName = "resultadoRastreo"; colvarResultadoRastreo.DataType = DbType.String; colvarResultadoRastreo.MaxLength = 1; colvarResultadoRastreo.AutoIncrement = false; colvarResultadoRastreo.IsNullable = true; colvarResultadoRastreo.IsPrimaryKey = false; colvarResultadoRastreo.IsForeignKey = false; colvarResultadoRastreo.IsReadOnly = false; colvarResultadoRastreo.DefaultSetting = @""; colvarResultadoRastreo.ForeignKeyTableName = ""; schema.Columns.Add(colvarResultadoRastreo); TableSchema.TableColumn colvarProfesional = new TableSchema.TableColumn(schema); colvarProfesional.ColumnName = "profesional"; colvarProfesional.DataType = DbType.AnsiString; colvarProfesional.MaxLength = 100; colvarProfesional.AutoIncrement = false; colvarProfesional.IsNullable = true; colvarProfesional.IsPrimaryKey = false; colvarProfesional.IsForeignKey = false; colvarProfesional.IsReadOnly = false; colvarProfesional.DefaultSetting = @""; colvarProfesional.ForeignKeyTableName = ""; schema.Columns.Add(colvarProfesional); TableSchema.TableColumn colvarFechaAlta = new TableSchema.TableColumn(schema); colvarFechaAlta.ColumnName = "fechaAlta"; colvarFechaAlta.DataType = DbType.DateTime; colvarFechaAlta.MaxLength = 0; colvarFechaAlta.AutoIncrement = false; colvarFechaAlta.IsNullable = false; colvarFechaAlta.IsPrimaryKey = false; colvarFechaAlta.IsForeignKey = false; colvarFechaAlta.IsReadOnly = false; colvarFechaAlta.DefaultSetting = @"(getdate())"; colvarFechaAlta.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaAlta); TableSchema.TableColumn colvarDadoDeBaja = new TableSchema.TableColumn(schema); colvarDadoDeBaja.ColumnName = "dadoDeBaja"; colvarDadoDeBaja.DataType = DbType.Boolean; colvarDadoDeBaja.MaxLength = 0; colvarDadoDeBaja.AutoIncrement = false; colvarDadoDeBaja.IsNullable = false; colvarDadoDeBaja.IsPrimaryKey = false; colvarDadoDeBaja.IsForeignKey = false; colvarDadoDeBaja.IsReadOnly = false; colvarDadoDeBaja.DefaultSetting = @"((0))"; colvarDadoDeBaja.ForeignKeyTableName = ""; schema.Columns.Add(colvarDadoDeBaja); TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema); colvarIdUsuario.ColumnName = "idUsuario"; colvarIdUsuario.DataType = DbType.Int32; colvarIdUsuario.MaxLength = 0; colvarIdUsuario.AutoIncrement = false; colvarIdUsuario.IsNullable = true; colvarIdUsuario.IsPrimaryKey = false; colvarIdUsuario.IsForeignKey = false; colvarIdUsuario.IsReadOnly = false; colvarIdUsuario.DefaultSetting = @""; colvarIdUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuario); TableSchema.TableColumn colvarIdUsuarioBaja = new TableSchema.TableColumn(schema); colvarIdUsuarioBaja.ColumnName = "idUsuarioBaja"; colvarIdUsuarioBaja.DataType = DbType.Int32; colvarIdUsuarioBaja.MaxLength = 0; colvarIdUsuarioBaja.AutoIncrement = false; colvarIdUsuarioBaja.IsNullable = true; colvarIdUsuarioBaja.IsPrimaryKey = false; colvarIdUsuarioBaja.IsForeignKey = false; colvarIdUsuarioBaja.IsReadOnly = false; colvarIdUsuarioBaja.DefaultSetting = @""; colvarIdUsuarioBaja.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioBaja); TableSchema.TableColumn colvarFechaEcografia = new TableSchema.TableColumn(schema); colvarFechaEcografia.ColumnName = "fechaEcografia"; colvarFechaEcografia.DataType = DbType.DateTime; colvarFechaEcografia.MaxLength = 0; colvarFechaEcografia.AutoIncrement = false; colvarFechaEcografia.IsNullable = true; colvarFechaEcografia.IsPrimaryKey = false; colvarFechaEcografia.IsForeignKey = false; colvarFechaEcografia.IsReadOnly = false; colvarFechaEcografia.DefaultSetting = @""; colvarFechaEcografia.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaEcografia); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Hid_Hidatidosis",schema); } } #endregion #region Props [XmlAttribute("IdHidatidosis")] [Bindable(true)] public int IdHidatidosis { get { return GetColumnValue<int>(Columns.IdHidatidosis); } set { SetColumnValue(Columns.IdHidatidosis, value); } } [XmlAttribute("IdEstablecimiento")] [Bindable(true)] public int IdEstablecimiento { get { return GetColumnValue<int>(Columns.IdEstablecimiento); } set { SetColumnValue(Columns.IdEstablecimiento, value); } } [XmlAttribute("Docente")] [Bindable(true)] public string Docente { get { return GetColumnValue<string>(Columns.Docente); } set { SetColumnValue(Columns.Docente, value); } } [XmlAttribute("NombrePaciente")] [Bindable(true)] public string NombrePaciente { get { return GetColumnValue<string>(Columns.NombrePaciente); } set { SetColumnValue(Columns.NombrePaciente, value); } } [XmlAttribute("ApellidoPaciente")] [Bindable(true)] public string ApellidoPaciente { get { return GetColumnValue<string>(Columns.ApellidoPaciente); } set { SetColumnValue(Columns.ApellidoPaciente, value); } } [XmlAttribute("DniPaciente")] [Bindable(true)] public string DniPaciente { get { return GetColumnValue<string>(Columns.DniPaciente); } set { SetColumnValue(Columns.DniPaciente, value); } } [XmlAttribute("FechaNacimiento")] [Bindable(true)] public DateTime? FechaNacimiento { get { return GetColumnValue<DateTime?>(Columns.FechaNacimiento); } set { SetColumnValue(Columns.FechaNacimiento, value); } } [XmlAttribute("DomicilioPaciente")] [Bindable(true)] public string DomicilioPaciente { get { return GetColumnValue<string>(Columns.DomicilioPaciente); } set { SetColumnValue(Columns.DomicilioPaciente, value); } } [XmlAttribute("TelefonoPaciente")] [Bindable(true)] public string TelefonoPaciente { get { return GetColumnValue<string>(Columns.TelefonoPaciente); } set { SetColumnValue(Columns.TelefonoPaciente, value); } } [XmlAttribute("Observaciones")] [Bindable(true)] public string Observaciones { get { return GetColumnValue<string>(Columns.Observaciones); } set { SetColumnValue(Columns.Observaciones, value); } } [XmlAttribute("NombrePadre")] [Bindable(true)] public string NombrePadre { get { return GetColumnValue<string>(Columns.NombrePadre); } set { SetColumnValue(Columns.NombrePadre, value); } } [XmlAttribute("ApellidoPadre")] [Bindable(true)] public string ApellidoPadre { get { return GetColumnValue<string>(Columns.ApellidoPadre); } set { SetColumnValue(Columns.ApellidoPadre, value); } } [XmlAttribute("DniPadre")] [Bindable(true)] public string DniPadre { get { return GetColumnValue<string>(Columns.DniPadre); } set { SetColumnValue(Columns.DniPadre, value); } } [XmlAttribute("ResultadoRastreo")] [Bindable(true)] public string ResultadoRastreo { get { return GetColumnValue<string>(Columns.ResultadoRastreo); } set { SetColumnValue(Columns.ResultadoRastreo, value); } } [XmlAttribute("Profesional")] [Bindable(true)] public string Profesional { get { return GetColumnValue<string>(Columns.Profesional); } set { SetColumnValue(Columns.Profesional, value); } } [XmlAttribute("FechaAlta")] [Bindable(true)] public DateTime FechaAlta { get { return GetColumnValue<DateTime>(Columns.FechaAlta); } set { SetColumnValue(Columns.FechaAlta, value); } } [XmlAttribute("DadoDeBaja")] [Bindable(true)] public bool DadoDeBaja { get { return GetColumnValue<bool>(Columns.DadoDeBaja); } set { SetColumnValue(Columns.DadoDeBaja, value); } } [XmlAttribute("IdUsuario")] [Bindable(true)] public int? IdUsuario { get { return GetColumnValue<int?>(Columns.IdUsuario); } set { SetColumnValue(Columns.IdUsuario, value); } } [XmlAttribute("IdUsuarioBaja")] [Bindable(true)] public int? IdUsuarioBaja { get { return GetColumnValue<int?>(Columns.IdUsuarioBaja); } set { SetColumnValue(Columns.IdUsuarioBaja, value); } } [XmlAttribute("FechaEcografia")] [Bindable(true)] public DateTime? FechaEcografia { get { return GetColumnValue<DateTime?>(Columns.FechaEcografia); } set { SetColumnValue(Columns.FechaEcografia, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdEstablecimiento,string varDocente,string varNombrePaciente,string varApellidoPaciente,string varDniPaciente,DateTime? varFechaNacimiento,string varDomicilioPaciente,string varTelefonoPaciente,string varObservaciones,string varNombrePadre,string varApellidoPadre,string varDniPadre,string varResultadoRastreo,string varProfesional,DateTime varFechaAlta,bool varDadoDeBaja,int? varIdUsuario,int? varIdUsuarioBaja,DateTime? varFechaEcografia) { HidHidatidosi item = new HidHidatidosi(); item.IdEstablecimiento = varIdEstablecimiento; item.Docente = varDocente; item.NombrePaciente = varNombrePaciente; item.ApellidoPaciente = varApellidoPaciente; item.DniPaciente = varDniPaciente; item.FechaNacimiento = varFechaNacimiento; item.DomicilioPaciente = varDomicilioPaciente; item.TelefonoPaciente = varTelefonoPaciente; item.Observaciones = varObservaciones; item.NombrePadre = varNombrePadre; item.ApellidoPadre = varApellidoPadre; item.DniPadre = varDniPadre; item.ResultadoRastreo = varResultadoRastreo; item.Profesional = varProfesional; item.FechaAlta = varFechaAlta; item.DadoDeBaja = varDadoDeBaja; item.IdUsuario = varIdUsuario; item.IdUsuarioBaja = varIdUsuarioBaja; item.FechaEcografia = varFechaEcografia; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdHidatidosis,int varIdEstablecimiento,string varDocente,string varNombrePaciente,string varApellidoPaciente,string varDniPaciente,DateTime? varFechaNacimiento,string varDomicilioPaciente,string varTelefonoPaciente,string varObservaciones,string varNombrePadre,string varApellidoPadre,string varDniPadre,string varResultadoRastreo,string varProfesional,DateTime varFechaAlta,bool varDadoDeBaja,int? varIdUsuario,int? varIdUsuarioBaja,DateTime? varFechaEcografia) { HidHidatidosi item = new HidHidatidosi(); item.IdHidatidosis = varIdHidatidosis; item.IdEstablecimiento = varIdEstablecimiento; item.Docente = varDocente; item.NombrePaciente = varNombrePaciente; item.ApellidoPaciente = varApellidoPaciente; item.DniPaciente = varDniPaciente; item.FechaNacimiento = varFechaNacimiento; item.DomicilioPaciente = varDomicilioPaciente; item.TelefonoPaciente = varTelefonoPaciente; item.Observaciones = varObservaciones; item.NombrePadre = varNombrePadre; item.ApellidoPadre = varApellidoPadre; item.DniPadre = varDniPadre; item.ResultadoRastreo = varResultadoRastreo; item.Profesional = varProfesional; item.FechaAlta = varFechaAlta; item.DadoDeBaja = varDadoDeBaja; item.IdUsuario = varIdUsuario; item.IdUsuarioBaja = varIdUsuarioBaja; item.FechaEcografia = varFechaEcografia; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdHidatidosisColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdEstablecimientoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DocenteColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NombrePacienteColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn ApellidoPacienteColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn DniPacienteColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn FechaNacimientoColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn DomicilioPacienteColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn TelefonoPacienteColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn ObservacionesColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn NombrePadreColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn ApellidoPadreColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn DniPadreColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn ResultadoRastreoColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn ProfesionalColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn FechaAltaColumn { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn DadoDeBajaColumn { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn IdUsuarioColumn { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn IdUsuarioBajaColumn { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn FechaEcografiaColumn { get { return Schema.Columns[19]; } } #endregion #region Columns Struct public struct Columns { public static string IdHidatidosis = @"idHidatidosis"; public static string IdEstablecimiento = @"idEstablecimiento"; public static string Docente = @"docente"; public static string NombrePaciente = @"nombrePaciente"; public static string ApellidoPaciente = @"apellidoPaciente"; public static string DniPaciente = @"dniPaciente"; public static string FechaNacimiento = @"fechaNacimiento"; public static string DomicilioPaciente = @"domicilioPaciente"; public static string TelefonoPaciente = @"telefonoPaciente"; public static string Observaciones = @"observaciones"; public static string NombrePadre = @"nombrePadre"; public static string ApellidoPadre = @"apellidoPadre"; public static string DniPadre = @"dniPadre"; public static string ResultadoRastreo = @"resultadoRastreo"; public static string Profesional = @"profesional"; public static string FechaAlta = @"fechaAlta"; public static string DadoDeBaja = @"dadoDeBaja"; public static string IdUsuario = @"idUsuario"; public static string IdUsuarioBaja = @"idUsuarioBaja"; public static string FechaEcografia = @"fechaEcografia"; } #endregion #region Update PK Collections #endregion #region Deep Save #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. #if ENABLEDATABINDING using System; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; namespace System.Xml.XPath.DataBinding { public sealed class XPathDocumentView : IBindingList, ITypedList { ArrayList rows; Shape rowShape; XPathNode ndRoot; XPathDocument document; string xpath; IXmlNamespaceResolver namespaceResolver; IXmlNamespaceResolver xpathResolver; // // Constructors // public XPathDocumentView(XPathDocument document) : this(document, (IXmlNamespaceResolver)null) { } public XPathDocumentView(XPathDocument document, IXmlNamespaceResolver namespaceResolver) { if (null == document) throw new ArgumentNullException(nameof(document)); this.document = document; this.ndRoot = document.Root; if (null == this.ndRoot) throw new ArgumentException(nameof(document)); this.namespaceResolver = namespaceResolver; ArrayList rows = new ArrayList(); this.rows = rows; Debug.Assert(XPathNodeType.Root == this.ndRoot.NodeType); XPathNode nd = this.ndRoot.Child; while (null != nd) { if (XPathNodeType.Element == nd.NodeType) rows.Add(nd); nd = nd.Sibling; } DeriveShapeFromRows(); } public XPathDocumentView(XPathDocument document, string xpath) : this(document, xpath, null, true) { } public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver) : this(document, xpath, namespaceResolver, false) { } public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver, bool showPrefixes) { if (null == document) throw new ArgumentNullException(nameof(document)); this.xpath = xpath; this.document = document; this.ndRoot = document.Root; if (null == this.ndRoot) throw new ArgumentException(nameof(document)); this.ndRoot = document.Root; this.xpathResolver = namespaceResolver; if (showPrefixes) this.namespaceResolver = namespaceResolver; ArrayList rows = new ArrayList(); this.rows = rows; InitFromXPath(this.ndRoot, xpath); } internal XPathDocumentView(XPathNode root, ArrayList rows, Shape rowShape) { this.rows = rows; this.rowShape = rowShape; this.ndRoot = root; } // // public properties public XPathDocument Document { get { return this.document; } } public String XPath { get { return xpath; } } // // IEnumerable Implementation public IEnumerator GetEnumerator() { return new RowEnumerator(this); } // // ICollection implementation public int Count { get { return this.rows.Count; } } public bool IsSynchronized { get { return false ; } } public object SyncRoot { get { return null; } } public void CopyTo(Array array, int index) { object o; ArrayList rows = this.rows; for (int i=0; i < rows.Count; i++) o = this[i]; // force creation lazy of row object rows.CopyTo(array, index); } public void CopyTo(XPathNodeView[] array, int index) { object o; ArrayList rows = this.rows; for (int i=0; i < rows.Count; i++) o = this[i]; // force creation lazy of row object rows.CopyTo(array, index); } // // IList Implementation bool IList.IsReadOnly { get { return true; } } bool IList.IsFixedSize { get { return true; } } bool IList.Contains(object value) { return this.rows.Contains(value); } void IList.Remove(object value) { throw new NotSupportedException("IList.Remove"); } void IList.RemoveAt(int index) { throw new NotSupportedException("IList.RemoveAt"); } void IList.Clear() { throw new NotSupportedException("IList.Clear"); } int IList.Add(object value) { throw new NotSupportedException("IList.Add"); } void IList.Insert(int index, object value) { throw new NotSupportedException("IList.Insert"); } int IList.IndexOf( object value ) { return this.rows.IndexOf(value); } object IList.this[int index] { get { object val = this.rows[index]; if (val is XPathNodeView) return val; XPathNodeView xiv = FillRow((XPathNode)val, this.rowShape); this.rows[index] = xiv; return xiv; } set { throw new NotSupportedException("IList.this[]"); } } public bool Contains(XPathNodeView value) { return this.rows.Contains(value); } public int Add(XPathNodeView value) { throw new NotSupportedException("IList.Add"); } public void Insert(int index, XPathNodeView value) { throw new NotSupportedException("IList.Insert"); } public int IndexOf(XPathNodeView value) { return this.rows.IndexOf(value); } public void Remove(XPathNodeView value) { throw new NotSupportedException("IList.Remove"); } public XPathNodeView this[int index] { get { object val = this.rows[index]; XPathNodeView nodeView; nodeView = val as XPathNodeView; if (nodeView != null) { return nodeView; } nodeView = FillRow((XPathNode)val, this.rowShape); this.rows[index] = nodeView; return nodeView; } set { throw new NotSupportedException("IList.this[]"); } } // // IBindingList Implementation public bool AllowEdit { get { return false; } } public bool AllowAdd { get { return false; } } public bool AllowRemove { get { return false; } } public bool AllowNew { get { return false; } } public object AddNew() { throw new NotSupportedException("IBindingList.AddNew"); } public bool SupportsChangeNotification { get { return false; } } public event ListChangedEventHandler ListChanged { add { throw new NotSupportedException("IBindingList.ListChanged"); } remove { throw new NotSupportedException("IBindingList.ListChanged"); } } public bool SupportsSearching { get { return false; } } public bool SupportsSorting { get { return false; } } public bool IsSorted { get { return false; } } public PropertyDescriptor SortProperty { get { throw new NotSupportedException("IBindingList.SortProperty"); } } public ListSortDirection SortDirection { get { throw new NotSupportedException("IBindingList.SortDirection"); } } public void AddIndex( PropertyDescriptor descriptor ) { throw new NotSupportedException("IBindingList.AddIndex"); } public void ApplySort( PropertyDescriptor descriptor, ListSortDirection direction ) { throw new NotSupportedException("IBindingList.ApplySort"); } public int Find(PropertyDescriptor propertyDescriptor, object key) { throw new NotSupportedException("IBindingList.Find"); } public void RemoveIndex(PropertyDescriptor propertyDescriptor) { throw new NotSupportedException("IBindingList.RemoveIndex"); } public void RemoveSort() { throw new NotSupportedException("IBindingList.RemoveSort"); } // // ITypedList Implementation public string GetListName(PropertyDescriptor[] listAccessors) { if ( listAccessors == null ) { return this.rowShape.Name; } else { return listAccessors[listAccessors.Length-1].Name; } } public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { Shape shape = null; if ( listAccessors == null ) { shape = this.rowShape; } else { XPathNodeViewPropertyDescriptor propdesc = listAccessors[listAccessors.Length-1] as XPathNodeViewPropertyDescriptor; if (null != propdesc) shape = propdesc.Shape; } if (null == shape) throw new ArgumentException(nameof(listAccessors)); return new PropertyDescriptorCollection(shape.PropertyDescriptors); } // // Internal Implementation internal Shape RowShape { get { return this.rowShape; } } internal void SetRows(ArrayList rows) { Debug.Assert(this.rows == null); this.rows = rows; } XPathNodeView FillRow(XPathNode ndRow, Shape shape) { object[] columns; XPathNode nd; switch (shape.BindingType) { case BindingType.Text: case BindingType.Attribute: columns = new object[1]; columns[0] = ndRow; return new XPathNodeView(this, ndRow, columns); case BindingType.Repeat: columns = new object[1]; nd = TreeNavigationHelper.GetContentChild(ndRow); columns[0] = FillColumn(new ContentIterator(nd, shape), shape); return new XPathNodeView(this, ndRow, columns); case BindingType.Sequence: case BindingType.Choice: case BindingType.All: int subShapesCount = shape.SubShapes.Count; columns = new object[subShapesCount]; if (shape.BindingType == BindingType.Sequence && shape.SubShape(0).BindingType == BindingType.Attribute) { FillAttributes(ndRow, shape, columns); } Shape lastSubShape = (Shape)shape.SubShapes[subShapesCount - 1]; if (lastSubShape.BindingType == BindingType.Text) { //Attributes followed by simpe content or mixed content columns[subShapesCount - 1] = ndRow; return new XPathNodeView(this, ndRow, columns); } else { nd = TreeNavigationHelper.GetContentChild(ndRow); return FillSubRow(new ContentIterator(nd, shape), shape, columns); } default: // should not map to a row #if DEBUG throw new NotSupportedException("Unable to bind row to: "+shape.BindingType.ToString()); #else throw new NotSupportedException(); #endif } } void FillAttributes(XPathNode nd, Shape shape, object[] cols) { int i = 0; while (i < cols.Length) { Shape attrShape = shape.SubShape(i); if (attrShape.BindingType != BindingType.Attribute) break; XmlQualifiedName name = attrShape.AttributeName; XPathNode ndAttr = nd.GetAttribute( name.Name, name.Namespace ); if (null != ndAttr) cols[i] = ndAttr; i++; } } object FillColumn(ContentIterator iter, Shape shape) { object val; switch (shape.BindingType) { case BindingType.Element: val = iter.Node; iter.Next(); break; case BindingType.ElementNested: { ArrayList rows = new ArrayList(); rows.Add(iter.Node); iter.Next(); val = new XPathDocumentView(null, rows, shape.NestedShape); break; } case BindingType.Repeat: { ArrayList rows = new ArrayList(); Shape subShape = shape.SubShape(0); if (subShape.BindingType == BindingType.ElementNested) { Shape nestShape = subShape.NestedShape; XPathDocumentView xivc = new XPathDocumentView(null, null, nestShape); XPathNode nd; while (null != (nd = iter.Node) && subShape.IsParticleMatch(iter.Particle)) { rows.Add(nd); iter.Next(); } xivc.SetRows(rows); val = xivc; } else { XPathDocumentView xivc = new XPathDocumentView(null, null, subShape); XPathNode nd; while (null != (nd = iter.Node) && shape.IsParticleMatch(iter.Particle)) { rows.Add(xivc.FillSubRow(iter, subShape, null)); } xivc.SetRows(rows); val = xivc; } break; } case BindingType.Sequence: case BindingType.Choice: case BindingType.All: { XPathDocumentView docview = new XPathDocumentView(null, null, shape); ArrayList rows = new ArrayList(); rows.Add(docview.FillSubRow(iter, shape, null)); docview.SetRows(rows); val = docview; break; } default: case BindingType.Text: case BindingType.Attribute: throw new NotSupportedException(); } return val; } XPathNodeView FillSubRow(ContentIterator iter, Shape shape, object[] columns) { if (null == columns) { int colCount = shape.SubShapes.Count; if (0 == colCount) colCount = 1; columns = new object[colCount]; } switch (shape.BindingType) { case BindingType.Element: columns[0] = FillColumn(iter, shape); break; case BindingType.Sequence: { int iPrev = -1; int i; while (null != iter.Node) { i = shape.FindMatchingSubShape(iter.Particle); if (i <= iPrev) break; columns[i] = FillColumn(iter, shape.SubShape(i)); iPrev = i; } break; } case BindingType.All: { while (null != iter.Node) { int i = shape.FindMatchingSubShape(iter.Particle); if (-1 == i || null != columns[i]) break; columns[i] = FillColumn(iter, shape.SubShape(i)); } break; } case BindingType.Choice: { int i = shape.FindMatchingSubShape(iter.Particle); if (-1 != i) { columns[i] = FillColumn(iter, shape.SubShape(i)); } break; } case BindingType.Repeat: default: // should not map to a row throw new NotSupportedException(); } return new XPathNodeView(this, null, columns); } // // XPath support // void InitFromXPath(XPathNode ndRoot, string xpath) { XPathStep[] steps = ParseXPath(xpath, this.xpathResolver); ArrayList rows = this.rows; rows.Clear(); PopulateFromXPath(ndRoot, steps, 0); DeriveShapeFromRows(); } void DeriveShapeFromRows() { object schemaInfo = null; for (int i=0; (i<rows.Count) && (null==schemaInfo); i++) { XPathNode nd = rows[i] as XPathNode; Debug.Assert(null != nd && (XPathNodeType.Attribute == nd.NodeType || XPathNodeType.Element == nd.NodeType)); if (null != nd) { if (XPathNodeType.Attribute == nd.NodeType) schemaInfo = nd.SchemaAttribute; else schemaInfo = nd.SchemaElement; } } if (0 == rows.Count) { throw new NotImplementedException("XPath failed to match an elements"); } if (null == schemaInfo) { rows.Clear(); throw new XmlException(SR.XmlDataBinding_NoSchemaType, (string[])null); } ShapeGenerator shapeGen = new ShapeGenerator(this.namespaceResolver); XmlSchemaElement xse = schemaInfo as XmlSchemaElement; if (null != xse) this.rowShape = shapeGen.GenerateFromSchema(xse); else this.rowShape = shapeGen.GenerateFromSchema((XmlSchemaAttribute)schemaInfo); } void PopulateFromXPath(XPathNode nd, XPathStep[] steps, int step) { string ln = steps[step].name.Name; string ns = steps[step].name.Namespace; if (XPathNodeType.Attribute == steps[step].type) { XPathNode ndAttr = nd.GetAttribute( ln, ns, true); if (null != ndAttr) { if (null != ndAttr.SchemaAttribute) this.rows.Add(ndAttr); } } else { XPathNode ndChild = TreeNavigationHelper.GetElementChild(nd, ln, ns, true); if (null != ndChild) { int nextStep = step+1; do { if (steps.Length == nextStep) { if (null != ndChild.SchemaType) this.rows.Add(ndChild); } else { PopulateFromXPath(ndChild, steps, nextStep); } ndChild = TreeNavigationHelper.GetElementSibling(ndChild, ln, ns, true); } while (null != ndChild); } } } // This is the limited grammar we support // Path ::= '/ ' ( Step '/')* ( QName | '@' QName ) // Step ::= '.' | QName // This is encoded as an array of XPathStep structs struct XPathStep { internal XmlQualifiedName name; internal XPathNodeType type; } // Parse xpath (limited to above grammar), using provided namespaceResolver // to resolve prefixes. XPathStep[] ParseXPath(string xpath, IXmlNamespaceResolver xnr) { int pos; int stepCount = 1; for (pos=1; pos<(xpath.Length-1); pos++) { if ( ('/' == xpath[pos]) && ('.' != xpath[pos+1]) ) stepCount++; } XPathStep[] steps = new XPathStep[stepCount]; pos = 0; int i = 0; while (true) { if (pos >= xpath.Length) throw new XmlException(SR.XmlDataBinding_XPathEnd, (string[])null); if ('/' != xpath[pos]) throw new XmlException(SR.XmlDataBinding_XPathRequireSlash, (string[])null); pos++; char ch = xpath[pos]; if (ch == '.') { pos++; // again... } else if ('@' == ch) { if (0 == i) throw new XmlException(SR.XmlDataBinding_XPathAttrNotFirst, (string[])null); pos++; if (pos >= xpath.Length) throw new XmlException(SR.XmlDataBinding_XPathEnd, (string[])null); steps[i].name = ParseQName(xpath, ref pos, xnr); steps[i].type = XPathNodeType.Attribute; i++; if (pos != xpath.Length) throw new XmlException(SR.XmlDataBinding_XPathAttrLast, (string[])null); break; } else { steps[i].name = ParseQName(xpath, ref pos, xnr); steps[i].type = XPathNodeType.Element; i++; if (pos == xpath.Length) break; } } Debug.Assert(i == steps.Length); return steps; } // Parse a QName from the string, and resolve prefix XmlQualifiedName ParseQName(string xpath, ref int pos, IXmlNamespaceResolver xnr) { string nm = ParseName(xpath, ref pos); if (pos < xpath.Length && ':' == xpath[pos]) { pos++; string ns = (null==xnr) ? null : xnr.LookupNamespace(nm); if (null == ns || 0 == ns.Length) throw new XmlException(SR.Sch_UnresolvedPrefix, nm); return new XmlQualifiedName(ParseName(xpath, ref pos), ns); } else { return new XmlQualifiedName(nm); } } // Parse a NCNAME from the string string ParseName(string xpath, ref int pos) { char ch; int start = pos++; while (pos < xpath.Length && '/' != (ch = xpath[pos]) && ':' != ch) pos++; string nm = xpath.Substring(start, pos - start); if (!XmlReader.IsName(nm)) throw new XmlException(SR.Xml_InvalidNameChars, (string[])null); return this.document.NameTable.Add(nm); } // // Helper classes // class ContentIterator { XPathNode node; ContentValidator contentValidator; ValidationState currentState; object currentParticle; public ContentIterator(XPathNode nd, Shape shape) { this.node = nd; XmlSchemaElement xse = shape.XmlSchemaElement; Debug.Assert(null != xse); SchemaElementDecl decl = xse.ElementDecl; Debug.Assert(null != decl); this.contentValidator = decl.ContentValidator; this.currentState = new ValidationState(); this.contentValidator.InitValidation(this.currentState); this.currentState.ProcessContents = XmlSchemaContentProcessing.Strict; if (nd != null) Advance(); } public XPathNode Node { get { return this.node; } } public object Particle { get { return this.currentParticle; } } public bool Next() { if (null != this.node) { this.node = TreeNavigationHelper.GetContentSibling(this.node, XPathNodeType.Element); if (node != null) Advance(); return null != this.node; } return false; } private void Advance() { XPathNode nd = this.node; int errorCode; this.currentParticle = this.contentValidator.ValidateElement(new XmlQualifiedName(nd.LocalName, nd.NamespaceUri), this.currentState, out errorCode); if (null == this.currentParticle || 0 != errorCode) { this.node = null; } } } // Helper class to implement enumerator over rows // We can't just use ArrayList enumerator because // sometims rows may be lazily constructed sealed class RowEnumerator : IEnumerator { XPathDocumentView collection; int pos; internal RowEnumerator(XPathDocumentView collection) { this.collection = collection; this.pos = -1; } public object Current { get { if (this.pos < 0 || this.pos >= this.collection.Count) return null; return this.collection[this.pos]; } } public void Reset() { this.pos = -1; } public bool MoveNext() { this.pos++; int max = this.collection.Count; if (this.pos > max) this.pos = max; return this.pos < max; } } } } #endif
using System; using System.Linq; using nHydrate.Generator.Common.Util; using DslModeling = global::Microsoft.VisualStudio.Modeling; namespace nHydrate.Dsl { partial class EntityHasEntities { #region Constructors // Constructors were not generated for this relationship because it had HasCustomConstructor // set to true. Please provide the constructors below in a partial class. public EntityHasEntities(Entity source, Entity target) : base((source != null ? source.Partition : null), new DslModeling::RoleAssignment[] { new DslModeling::RoleAssignment(EntityHasEntities.ParentEntityDomainRoleId, source), new DslModeling::RoleAssignment(EntityHasEntities.ChildEntityDomainRoleId, target) }, null) { this.InternalId = Guid.NewGuid(); } public EntityHasEntities(DslModeling::Store store, params DslModeling::RoleAssignment[] roleAssignments) : base(store != null ? store.DefaultPartitionForClass(DomainClassId) : null, roleAssignments, null) { this.InternalId = Guid.NewGuid(); } public EntityHasEntities(DslModeling::Store store, DslModeling::RoleAssignment[] roleAssignments, DslModeling::PropertyAssignment[] propertyAssignments) : base(store != null ? store.DefaultPartitionForClass(DomainClassId) : null, roleAssignments, propertyAssignments) { this.InternalId = Guid.NewGuid(); } public EntityHasEntities(DslModeling::Partition partition, params DslModeling::RoleAssignment[] roleAssignments) : base(partition, roleAssignments, null) { this.InternalId = Guid.NewGuid(); } public EntityHasEntities(DslModeling::Partition partition, DslModeling::RoleAssignment[] roleAssignments, DslModeling::PropertyAssignment[] propertyAssignments) : base(partition, roleAssignments, propertyAssignments) { this.InternalId = Guid.NewGuid(); } #endregion public Guid InternalId { get; internal set; } public Entity TargetEntity => this.ChildEntity; public Entity SourceEntity => this.ParentEntity; /// <summary> /// Determines if this is a M:N relationship /// </summary> public bool IsManyToMany { get { var parentTable = this.SourceEntity; var childTable = this.TargetEntity; var otherTable = parentTable; if (childTable.IsAssociative) otherTable = childTable; if (otherTable.IsAssociative) { //The associative table must have exactly 2 relations var relationList = otherTable.GetRelationsWhereChild(); if (relationList.Count() == 2) { return true; } } return false; } } public string PascalRoleName => StringHelper.FirstCharToUpper(this.RoleName); public string LinkHash { get { var retval = string.Empty; if (this.SourceEntity != null) retval += this.SourceEntity.Name.ToLower() + "|"; if (this.TargetEntity != null) retval += this.TargetEntity.Name.ToLower() + "|"; retval += this.RoleName + "|"; foreach (var cr in this.FieldMapList()) { if (cr.GetSourceField(this) != null) retval += cr.GetSourceField(this).Name.ToLower() + "|"; if (cr.GetTargetField(this) != null) retval += cr.GetTargetField(this).Name.ToLower() + "|"; } return retval; } } public Entity GetSecondaryAssociativeTable() { if (!this.IsManyToMany) return null; var parentTable = this.SourceEntity; var childTable = this.TargetEntity; var otherTable = parentTable; if (childTable.IsAssociative) otherTable = childTable; if (otherTable.IsAssociative) { var relationList = otherTable.GetRelationsWhereChild(); { var relation = relationList.FirstOrDefault(x => x != this); if (relation == null) return null; return relation.SourceEntity; } } return null; } /// <summary> /// Determine if this relationship is based on primary keys /// </summary> public bool IsPrimaryKeyRelation() { var retval = true; foreach (var columnRelationship in this.FieldMapList()) { var parentColumn = columnRelationship.GetSourceField(this); var parentTable = this.SourceEntity; if (!parentTable.PrimaryKeyFields.Contains(parentColumn)) retval = false; } return retval; } /// <summary> /// Gets the other relation on an associative table /// </summary> public EntityHasEntities GetAssociativeOtherRelation() { if (!this.IsManyToMany) return null; var parentTable = this.SourceEntity; var childTable = this.TargetEntity; var otherTable = parentTable; if (childTable.IsAssociative) otherTable = childTable; if (otherTable.IsAssociative) { var relationList = otherTable.GetRelationsWhereChild(); if (relationList.Count() == 2) { var relation = relationList.FirstOrDefault(x => x != this); if (relation == null) return null; return relation; } } return null; } /// <summary> /// Determines if this is a 1:1 relationship /// </summary> public bool IsOneToOne { get { //If any of the columns are not unique then the relationship is NOT unique var retval = true; var childPKCount = 0; //Determine if any of the child columns are in the PK foreach (var columnRelationship in this.FieldMapList()) { var column1 = columnRelationship.GetSourceField(this); var column2 = columnRelationship.GetTargetField(this); if (column1 == null || column2 == null) return false; retval &= column1.IsUnique; retval &= column2.IsUnique; if (this.TargetEntity.PrimaryKeyFields.Contains(column2)) childPKCount++; } //If at least one column was a Child table PK, //then all columns must be in there to be 1:1 if ((childPKCount > 0) && (this.FieldMapList().Count() != this.TargetEntity.PrimaryKeyFields.Count)) { return false; } return retval; } } public override string ToString() => this.DisplayName; public string DisplayName { get { var retval = string.Empty; if (this.ParentEntity == null) return "(Unknown)"; if (this.ChildEntity == null) return "(Unknown)"; if (!this.FieldMapList().Any()) return "(Unknown)"; retval = this.ParentEntity.Name + " -> " + this.ChildEntity.Name; if (!string.IsNullOrEmpty(this.RoleName)) { retval += " (Role: " + this.RoleName + ")"; } var index = 0; var fields = this.FieldMapList().ToList(); foreach (var cr in fields) { retval += " [" + cr.GetSourceField(this).Name + ":" + cr.GetTargetField(this).Name + "]"; if (index < fields.Count - 1) retval += ","; index++; } return retval; } } protected override void OnDeleting() { //Remove from relation mapped collections var count1 = this.ParentEntity.nHydrateModel.RelationFields.Remove(x => x.RelationID == this.Id); base.OnDeleting(); } } partial class EntityHasEntitiesBase { /// <summary> /// Constructor. /// </summary> /// <param name="partition">The Partition instance containing this ElementLink</param> /// <param name="roleAssignments">A set of role assignments for role player initialization</param> /// <param name="propertyAssignments">A set of attribute assignments for attribute initialization</param> protected EntityHasEntitiesBase(DslModeling::Partition partition, DslModeling::RoleAssignment[] roleAssignments, DslModeling::PropertyAssignment[] propertyAssignments) : base(partition, roleAssignments, propertyAssignments) { } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using Org.BouncyCastle.Math; namespace Org.BouncyCastle.Asn1 { public class DerObjectIdentifier : Asn1Object { private static readonly Regex _oidRegex = new Regex(@"\A[0-2](\.[0-9]+)+\z"); private readonly string _identifier; /** * return an Oid from the passed in object * * @exception ArgumentException if the object cannot be converted. */ public static DerObjectIdentifier GetInstance(object obj) { if (obj == null || obj is DerObjectIdentifier) { return (DerObjectIdentifier)obj; } throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj"); } /** * return an object Identifier from a tagged object. * * @param obj the tagged object holding the object we want * @param explicitly true if the object is meant to be explicitly * tagged false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static DerObjectIdentifier GetInstance(Asn1TaggedObject obj, bool explicitly) { return GetInstance(obj.GetObject()); } public DerObjectIdentifier(string identifier) { if (identifier == null) throw new ArgumentNullException("identifier"); if (!_oidRegex.IsMatch(identifier)) throw new FormatException("string " + identifier + " not an OID"); _identifier = identifier; } public string Id { get { return _identifier; } } public virtual DerObjectIdentifier Branch(string branchId) { return new DerObjectIdentifier(_identifier + "." + branchId); } internal DerObjectIdentifier(byte[] bytes) : this(MakeOidStringFromBytes(bytes)) { } private static void WriteField(Stream outputStream, long fieldValue) { var result = new byte[9]; var pos = 8; result[pos] = (byte)(fieldValue & 0x7f); while (fieldValue >= (1L << 7)) { fieldValue >>= 7; result[--pos] = (byte)((fieldValue & 0x7f) | 0x80); } outputStream.Write(result, pos, 9 - pos); } private static void WriteField(Stream outputStream, IBigInteger fieldValue) { var byteCount = (fieldValue.BitLength + 6) / 7; if (byteCount == 0) { outputStream.WriteByte(0); } else { var tmpValue = fieldValue; var tmp = new byte[byteCount]; for (var i = byteCount - 1; i >= 0; i--) { tmp[i] = (byte)((tmpValue.IntValue & 0x7f) | 0x80); tmpValue = tmpValue.ShiftRight(7); } tmp[byteCount - 1] &= 0x7f; outputStream.Write(tmp, 0, tmp.Length); } } internal override void Encode(DerOutputStream derOut) { var tok = new OidTokenizer(_identifier); using (var bOut = new MemoryStream()) { using (var dOut = new DerOutputStream(bOut)) { var token = tok.NextToken(); var first = int.Parse(token); token = tok.NextToken(); var second = int.Parse(token); WriteField(bOut, first * 40 + second); while (tok.HasMoreTokens) { token = tok.NextToken(); if (token.Length < 18) { WriteField(bOut, Int64.Parse(token)); } else { WriteField(bOut, new BigInteger(token)); } } } derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, bOut.ToArray()); } } protected override int Asn1GetHashCode() { return _identifier.GetHashCode(); } protected override bool Asn1Equals(Asn1Object asn1Object) { var other = asn1Object as DerObjectIdentifier; return other != null && this._identifier.Equals(other._identifier); } public override string ToString() { return _identifier; } public byte[] ToBytes() { var split = _identifier.Split('.'); var bytes = new List<byte>(); for (int a = 0, i = 0; i < split.Length; i++) { switch (i) { case 0: a = int.Parse(split[0]); break; case 1: bytes.Add((byte)(40 * a + int.Parse(split[1]))); break; default: var b = int.Parse(split[i]); if (b < 128) { bytes.Add((byte) b); } else { bytes.Add((byte) (128 + (b/128))); bytes.Add((byte) (b%128)); } break; } } return bytes.ToArray(); } private static string MakeOidStringFromBytes(byte[] bytes) { var objId = new StringBuilder(); long value = 0; IBigInteger bigValue = null; var first = true; for (var i = 0; i != bytes.Length; i++) { int b = bytes[i]; if (value < 0x80000000000000L) { value = value * 128 + (b & 0x7f); if ((b & 0x80) == 0) // end of number reached { if (first) { switch ((int)value / 40) { case 0: objId.Append('0'); break; case 1: objId.Append('1'); value -= 40; break; default: objId.Append('2'); value -= 80; break; } first = false; } objId.Append('.'); objId.Append(value); value = 0; } } else { if (bigValue == null) { bigValue = BigInteger.ValueOf(value); } bigValue = bigValue.ShiftLeft(7); bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f)); if ((b & 0x80) == 0) { objId.Append('.'); objId.Append(bigValue); bigValue = null; value = 0; } } } return objId.ToString(); } } }
// 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. /************************************************************************** /*Test: RanCollect /*args: iRep--the repeat times of alloc and delete /* iObj--max elements' number for every collection object /* iBigSize -- max Bignode's size. (10 <-->4MB) /* iSeed -- seed of random generator, for getting random elements' number /*Description:This test use collection objects (L_ArrList2, L_Queue, L_ArrList1) and /* Variant(L_Vart). It has iRep loops. Inside every loop, create random number /* elements in Collection Objects and Variant Object.every element's size /* is random, from 0 to iBigSize*iBigSize*10*4KB, for very loop, it also /* delete random number elements or all the objects. samply change the four /* arguments, you can get handreds of GC condition. /****************************************************************************/ namespace DefaultNamespace { using System; //using System.Collections.Generic; internal class RanCollect { public static int Main(String [] Args) { int iRep = 0; int iObj = 0; int iBigSize = 0; int iSeed = 0; Console.WriteLine("Test should return with ExitCode 100 ..."); if (Args.Length == 4) { if (!Int32.TryParse( Args[0], out iRep) || !Int32.TryParse( Args[1], out iObj) || !Int32.TryParse( Args[2], out iBigSize ) || !Int32.TryParse( Args[3], out iSeed ) ) { return 1; } } else { iRep = 10; iObj = 100; iBigSize = 2; iSeed = 49; } if(iObj <= 10) { Console.WriteLine("the second argument must be larger than 10."); return 1; } Console.Write("iRep= "); Console.Write(iRep); Console.Write(" ; iObj= "); Console.Write(iObj); Console.Write(" ; iBigSize="); Console.Write(iBigSize); Console.Write(" ; iSeed = "); Console.WriteLine(iSeed); RanCollect Mv_Obj = new RanCollect(); if(Mv_Obj.runTest(iRep, iObj, iBigSize, iSeed)) { Console.WriteLine("Test Passed"); return 100; } Console.WriteLine("Test Failed"); return 1; } public virtual bool runTest(int iRep, int iObj, int iBigSize, int iSeed) { ArrayList L_ArrList1 = new ArrayList(); //whose node is big double link object (DoubLinkBig). ArrayList L_ArrList2 = new ArrayList(); //whose node is MinNode . Queue L_Queue = new Queue(); //Whose node is DLRanBigNode. Random r = new Random(iSeed); int num = r.Next (10, iObj-1); int delnum; Object [] L_Vart = null; Console.Write(num); Console.WriteLine (" number's elements in collection objects"); for(int i=0; i<iRep;i++) { /*allocate memory*/ L_Vart = new Object[num]; for(int j=0; j<num; j++) { int Size= r.Next(3, num); //the size of nodes. /*L_ArrList1 element's size is from 0 to iBigSize*iBigSize*10*4KB*/ L_ArrList1.Add(new DoubLinkBig(r.Next(iBigSize))); /*L_ArrList2 element's size is Size number bytes;*/ L_ArrList2.Add( new MinNode(Size)); /*L_Queue element's size is from 0 to 1M*/ L_Queue.Enqueue(new DLRanBigNode(250, null, null)); if(j%6==0) { L_Vart[j] = (new DLRanBigNode(250, null, null)); } else { L_Vart[j] = (new MinNode(Size)); } L_ArrList1.RemoveAt(0); } /*start to make leak*/ if(r.Next(1, iRep)/3 == 0 || num < iObj/8) //learn all the nodes { num = r.Next(10, iObj-1); L_ArrList1 = new ArrayList(); //whose node is big double link object (DoubLinkBig). L_ArrList2 = new ArrayList(); //whose node is MinNode . L_Queue = new Queue(); //Whose node is DLRanBigNode. Console.WriteLine("all objects were deleted at the end of loop {0}",i); Console.WriteLine ("{0} number's elements in every collection objects in loop {1}", num, (i+1)); } else { if (L_ArrList2.Count <=1) { delnum = 1; } else { delnum = r.Next (1, L_ArrList2.Count); //going to delete delnum nodes } if (delnum > (L_ArrList2.Count*3/4)) { delnum = L_ArrList2.Count/2; } num = L_ArrList2.Count - delnum; //going to add num nodes for(int j=0; j<delnum; j++) { L_ArrList2.RemoveAt(0); L_Queue.Dequeue(); } Console.WriteLine("{0} were deleted in each collections at the end of loop {1}", delnum, i); Console.WriteLine ("{0} elements in each collection objects in loop ", num*2, (i+1)); } } return true; } } public class DoubLinkBig { internal DLRanBigNode[] Mv_DLink; internal int NodeNum; public DoubLinkBig(int Num) { NodeNum = Num; Mv_DLink = new DLRanBigNode[Num]; if (Num == 0) { return; } if (Num == 1) { Mv_DLink[0] = new DLRanBigNode(Num * 10, Mv_DLink[0], Mv_DLink[0]); return; } Mv_DLink[0] = new DLRanBigNode(Num * 10, Mv_DLink[Num - 1], Mv_DLink[1]); for (int i = 1; i < Num - 1; i++) { Mv_DLink[i] = new DLRanBigNode(Num * 10, Mv_DLink[i - 1], Mv_DLink[i + 1]); } Mv_DLink[Num - 1] = new DLRanBigNode(Num * 10, Mv_DLink[Num - 2], Mv_DLink[0]); } public virtual int GetNodeNum() { return NodeNum; } } internal class MinNode { public MinNode(int size) { byte[] obj = new byte[size]; if (size > 0) { obj[0] = (byte)10; if (size > 1) { obj[size - 1] = (byte)11; } } } } public class DLRanBigNode { // disabling unused variable warning #pragma warning disable 0414 internal DLRanBigNode Last; internal DLRanBigNode Next; internal int[] Size; #pragma warning restore 0414 internal static int FACTOR = 1024; public DLRanBigNode(int SizeNum, DLRanBigNode LastObject, DLRanBigNode NextObject) { Last = LastObject; Next = NextObject; Random r = new Random(10); Size = new int[FACTOR * r.Next(SizeNum)]; } } //Queue implemented as a circular array class Queue { int m_Capacity = 20; //default capacity int m_Size = 0; Object[] m_Array; int m_First = 0; int m_Last = -1; public Queue() { m_Array = new Object[m_Capacity]; } public Queue(int capacity) { m_Capacity = capacity; m_Array = new Object[m_Capacity]; } public int Count { get { return m_Size; } } public void Enqueue(Object obj) { if(m_Size >= m_Capacity) //array full; increase capacity { int newCapacity = m_Capacity * 2; Object[] newArray = new Object[newCapacity]; int current = m_First; for (int i = 0; i < m_Size; i++) { newArray[0] = m_Array[current]; current = (current+1) % m_Capacity; } m_Array = newArray; m_First = 0; m_Last = m_Size - 1; m_Capacity = newCapacity; } m_Last++; if(m_Last == m_Capacity) //wrap around m_Last = m_Last % m_Capacity; m_Array[m_Last] = obj; m_Size++; } public Object Dequeue() { if (m_Size == 0) throw new InvalidOperationException(); Object returnObject = m_Array[m_First]; m_Array[m_First] = null; m_First = (m_First+1) % m_Capacity; m_Size--; return returnObject; } } class ArrayList { int m_Capacity = 20; //default capacity int m_Size = 0; Object[] m_Array; public ArrayList() { m_Array = new Object[m_Capacity]; } public ArrayList(int capacity) { m_Capacity = capacity; m_Array = new Object[m_Capacity]; } public int Count { get { return m_Size; } } public int Capacity { get { return m_Capacity; } } //Add an Object; returns the array index at which the object was added; public int Add(Object obj) { if (m_Size >= m_Capacity) //increase capacity { int newCapacity = m_Capacity * 2; Object[] newArray = new Object[newCapacity]; for (int i = 0; i < m_Size; i++) { newArray[i] = m_Array[i]; } m_Array = newArray; m_Capacity = newCapacity; } m_Array[m_Size] = obj; m_Size++; return (m_Size - 1); } public void RemoveAt(int position) { if (position < 0 || position >= m_Size) throw new ArgumentOutOfRangeException(); m_Array[position] = null; //shift elements to fill the empty slot for (int i = position; i < m_Size-1; i++) { m_Array[i] = m_Array[i + 1]; } m_Size--; } } }
// Copyright (C) 2005-2013, Andriy Kozachuk // Copyright (C) 2014 Extesla, 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. using OpenGamingLibrary.Numerics.OpHelpers; using OpenGamingLibrary.Numerics.Utils; namespace OpenGamingLibrary.Numerics.Dividers { /// <summary> /// Divider using "classic" algorithm. /// </summary> sealed internal class ClassicDivider : DividerBase { /// <summary> /// Divides two big integers. /// Also modifies <paramref name="digits1" /> and <paramref name="length1"/> (it will contain remainder). /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="digitsBuffer1">Buffer for first big integer digits. May also contain remainder. Can be null - in this case it's created if necessary.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="digitsBuffer2">Buffer for second big integer digits. Only temporarily used. Can be null - in this case it's created if necessary.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <param name="resultFlags">Which operation results to return.</param> /// <param name="cmpResult">Big integers comparsion result (pass -2 if omitted).</param> /// <returns>Resulting big integer length.</returns> override unsafe public uint DivMod( uint[] digits1, uint[] digitsBuffer1, ref uint length1, uint[] digits2, uint[] digitsBuffer2, uint length2, uint[] digitsRes, DivModResultFlags resultFlags, int cmpResult) { // Create some buffers if necessary if (digitsBuffer1 == null) { digitsBuffer1 = new uint[length1 + 1]; } if (digitsBuffer2 == null) { digitsBuffer2 = new uint[length2]; } fixed (uint* digitsPtr1 = digits1, digitsBufferPtr1 = digitsBuffer1, digitsPtr2 = digits2, digitsBufferPtr2 = digitsBuffer2, digitsResPtr = digitsRes != null ? digitsRes : digits1) { return DivMod( digitsPtr1, digitsBufferPtr1, ref length1, digitsPtr2, digitsBufferPtr2, length2, digitsResPtr == digitsPtr1 ? null : digitsResPtr, resultFlags, cmpResult); } } /// <summary> /// Divides two big integers. /// Also modifies <paramref name="digitsPtr1" /> and <paramref name="length1"/> (it will contain remainder). /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="digitsBufferPtr1">Buffer for first big integer digits. May also contain remainder.</param> /// <param name="length1">First big integer length.</param> /// <param name="digitsPtr2">Second big integer digits.</param> /// <param name="digitsBufferPtr2">Buffer for second big integer digits. Only temporarily used.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsResPtr">Resulting big integer digits.</param> /// <param name="resultFlags">Which operation results to return.</param> /// <param name="cmpResult">Big integers comparsion result (pass -2 if omitted).</param> /// <returns>Resulting big integer length.</returns> override unsafe public uint DivMod( uint* digitsPtr1, uint* digitsBufferPtr1, ref uint length1, uint* digitsPtr2, uint* digitsBufferPtr2, uint length2, uint* digitsResPtr, DivModResultFlags resultFlags, int cmpResult) { // Call base (for special cases) uint resultLength = base.DivMod( digitsPtr1, digitsBufferPtr1, ref length1, digitsPtr2, digitsBufferPtr2, length2, digitsResPtr, resultFlags, cmpResult); if (resultLength != uint.MaxValue) return resultLength; bool divNeeded = (resultFlags & DivModResultFlags.Div) != 0; bool modNeeded = (resultFlags & DivModResultFlags.Mod) != 0; // // Prepare digitsBufferPtr1 and digitsBufferPtr2 // int shift1 = 31 - Bits.Msb(digitsPtr2[length2 - 1]); if (shift1 == 0) { // We don't need to shift - just copy DigitHelper.DigitsBlockCopy(digitsPtr1, digitsBufferPtr1, length1); // We also don't need to shift second digits digitsBufferPtr2 = digitsPtr2; } else { int rightShift1 = Constants.DigitBitCount - shift1; // We do need to shift here - so copy with shift - suppose we have enough storage for this operation length1 = DigitOpHelper.Shr(digitsPtr1, length1, digitsBufferPtr1 + 1, rightShift1, true) + 1U; // Second digits also must be shifted DigitOpHelper.Shr(digitsPtr2, length2, digitsBufferPtr2 + 1, rightShift1, true); } // // Division main algorithm implementation // ulong longDigit; ulong divEst; ulong modEst; ulong mulRes; uint divRes; long k, t; // Some digits2 cached digits uint lastDigit2 = digitsBufferPtr2[length2 - 1]; uint preLastDigit2 = digitsBufferPtr2[length2 - 2]; // Main divide loop bool isMaxLength; uint maxLength = length1 - length2; for (uint i = maxLength, iLen2 = length1, j, ji; i <= maxLength; --i, --iLen2) { isMaxLength = iLen2 == length1; // Calculate estimates if (isMaxLength) { longDigit = digitsBufferPtr1[iLen2 - 1]; } else { longDigit = (ulong)digitsBufferPtr1[iLen2] << Constants.DigitBitCount | digitsBufferPtr1[iLen2 - 1]; } divEst = longDigit / lastDigit2; modEst = longDigit - divEst * lastDigit2; // Check estimate (maybe correct it) for (;;) { if (divEst == Constants.BitCountStepOf2 || divEst * preLastDigit2 > (modEst << Constants.DigitBitCount) + digitsBufferPtr1[iLen2 - 2]) { --divEst; modEst += lastDigit2; if (modEst < Constants.BitCountStepOf2) continue; } break; } divRes = (uint)divEst; // Multiply and subtract k = 0; for (j = 0, ji = i; j < length2; ++j, ++ji) { mulRes = (ulong)divRes * digitsBufferPtr2[j]; t = digitsBufferPtr1[ji] - k - (long)(mulRes & 0xFFFFFFFF); digitsBufferPtr1[ji] = (uint)t; k = (long)(mulRes >> Constants.DigitBitCount) - (t >> Constants.DigitBitCount); } if (!isMaxLength) { t = digitsBufferPtr1[iLen2] - k; digitsBufferPtr1[iLen2] = (uint)t; } else { t = -k; } // Correct result if subtracted too much if (t < 0) { --divRes; k = 0; for (j = 0, ji = i; j < length2; ++j, ++ji) { t = (long)digitsBufferPtr1[ji] + digitsBufferPtr2[j] + k; digitsBufferPtr1[ji] = (uint)t; k = t >> Constants.DigitBitCount; } if (!isMaxLength) { digitsBufferPtr1[iLen2] = (uint)(k + digitsBufferPtr1[iLen2]); } } // Maybe save div result if (divNeeded) { digitsResPtr[i] = divRes; } } if (modNeeded) { // First set correct mod length length1 = DigitHelper.GetRealDigitsLength(digitsBufferPtr1, length2); // Next maybe shift result back to the right if (shift1 != 0 && length1 != 0) { length1 = DigitOpHelper.Shr(digitsBufferPtr1, length1, digitsBufferPtr1, shift1, false); } } // Finally return length return !divNeeded ? 0 : (digitsResPtr[maxLength] == 0 ? maxLength : ++maxLength); } } }
using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Logging; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Security; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Web; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Web.Common.ActionsResults; using Umbraco.Cms.Web.Common.Filters; using Umbraco.Cms.Web.Common.Security; using Umbraco.Extensions; using SignInResult = Microsoft.AspNetCore.Identity.SignInResult; namespace Umbraco.Cms.Web.Website.Controllers { [UmbracoMemberAuthorize] public class UmbExternalLoginController : SurfaceController { private readonly IMemberManager _memberManager; private readonly ITwoFactorLoginService _twoFactorLoginService; private readonly IOptions<SecuritySettings> _securitySettings; private readonly ILogger<UmbExternalLoginController> _logger; private readonly IMemberSignInManagerExternalLogins _memberSignInManager; public UmbExternalLoginController( ILogger<UmbExternalLoginController> logger, IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IMemberSignInManagerExternalLogins memberSignInManager, IMemberManager memberManager, ITwoFactorLoginService twoFactorLoginService, IOptions<SecuritySettings> securitySettings) : base( umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) { _logger = logger; _memberSignInManager = memberSignInManager; _memberManager = memberManager; _twoFactorLoginService = twoFactorLoginService; _securitySettings = securitySettings; } /// <summary> /// Endpoint used to redirect to a specific login provider. This endpoint is used from the Login Macro snippet. /// </summary> [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl = null) { if (returnUrl.IsNullOrWhiteSpace()) { returnUrl = Request.GetEncodedPathAndQuery(); } var wrappedReturnUrl = Url.SurfaceAction(nameof(ExternalLoginCallback), this.GetControllerName(), new { returnUrl }); AuthenticationProperties properties = _memberSignInManager.ConfigureExternalAuthenticationProperties(provider, wrappedReturnUrl); return Challenge(properties, provider); } /// <summary> /// Endpoint used my the login provider to call back to our solution. /// </summary> [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl) { var errors = new List<string>(); ExternalLoginInfo loginInfo = await _memberSignInManager.GetExternalLoginInfoAsync(); if (loginInfo is null) { errors.Add("Invalid response from the login provider"); } else { SignInResult result = await _memberSignInManager.ExternalLoginSignInAsync(loginInfo, false, _securitySettings.Value.MemberBypassTwoFactorForExternalLogins); if (result == SignInResult.Success) { // Update any authentication tokens if succeeded await _memberSignInManager.UpdateExternalAuthenticationTokensAsync(loginInfo); return RedirectToLocal(returnUrl); } if (result == SignInResult.TwoFactorRequired) { MemberIdentityUser attemptedUser = await _memberManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); if (attemptedUser == null) { return new ValidationErrorResult( $"No local user found for the login provider {loginInfo.LoginProvider} - {loginInfo.ProviderKey}"); } var providerNames = await _twoFactorLoginService.GetEnabledTwoFactorProviderNamesAsync(attemptedUser.Key); ViewData.SetTwoFactorProviderNames(providerNames); return CurrentUmbracoPage(); } if (result == SignInResult.LockedOut) { errors.Add( $"The local member {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} is locked out."); } else if (result == SignInResult.NotAllowed) { // This occurs when SignInManager.CanSignInAsync fails which is when RequireConfirmedEmail , RequireConfirmedPhoneNumber or RequireConfirmedAccount fails // however since we don't enforce those rules (yet) this shouldn't happen. errors.Add( $"The member {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not confirmed their details and cannot sign in."); } else if (result == SignInResult.Failed) { // Failed only occurs when the user does not exist errors.Add("The requested provider (" + loginInfo.LoginProvider + ") has not been linked to an account, the provider must be linked before it can be used."); } else if (result == MemberSignInManager.ExternalLoginSignInResult.NotAllowed) { // This occurs when the external provider has approved the login but custom logic in OnExternalLogin has denined it. errors.Add( $"The user {loginInfo.Principal.Identity.Name} for the external provider {loginInfo.ProviderDisplayName} has not been accepted and cannot sign in."); } else if (result == MemberSignInManager.AutoLinkSignInResult.FailedNotLinked) { errors.Add("The requested provider (" + loginInfo.LoginProvider + ") has not been linked to an account, the provider must be linked from the back office."); } else if (result == MemberSignInManager.AutoLinkSignInResult.FailedNoEmail) { errors.Add( $"The requested provider ({loginInfo.LoginProvider}) has not provided the email claim {ClaimTypes.Email}, the account cannot be linked."); } else if (result is MemberSignInManager.AutoLinkSignInResult autoLinkSignInResult && autoLinkSignInResult.Errors.Count > 0) { errors.AddRange(autoLinkSignInResult.Errors); } else if (!result.Succeeded) { // this shouldn't occur, the above should catch the correct error but we'll be safe just in case errors.Add($"An unknown error with the requested provider ({loginInfo.LoginProvider}) occurred."); } } if (errors.Count > 0) { ViewData.SetExternalSignInProviderErrors( new BackOfficeExternalLoginProviderErrors( loginInfo?.LoginProvider, errors)); return CurrentUmbracoPage(); } return RedirectToLocal(returnUrl); } private void AddModelErrors(IdentityResult result, string prefix = "") { foreach (IdentityError error in result.Errors) { ModelState.AddModelError(prefix, error.Description); } } [HttpPost] [ValidateAntiForgeryToken] public IActionResult LinkLogin(string provider, string returnUrl = null) { if (returnUrl.IsNullOrWhiteSpace()) { returnUrl = Request.GetEncodedPathAndQuery(); } var wrappedReturnUrl = Url.SurfaceAction(nameof(ExternalLinkLoginCallback), this.GetControllerName(), new { returnUrl }); // Configures the redirect URL and user identifier for the specified external login including xsrf data AuthenticationProperties properties = _memberSignInManager.ConfigureExternalAuthenticationProperties(provider, wrappedReturnUrl, _memberManager.GetUserId(User)); return Challenge(properties, provider); } [HttpGet] public async Task<IActionResult> ExternalLinkLoginCallback(string returnUrl) { MemberIdentityUser user = await _memberManager.GetUserAsync(User); string loginProvider = null; var errors = new List<string>(); if (user == null) { // ... this should really not happen errors.Add("Local user does not exist"); } else { ExternalLoginInfo info = await _memberSignInManager.GetExternalLoginInfoAsync(await _memberManager.GetUserIdAsync(user)); if (info == null) { //Add error and redirect for it to be displayed errors.Add( "An error occurred, could not get external login info"); } else { loginProvider = info.LoginProvider; IdentityResult addLoginResult = await _memberManager.AddLoginAsync(user, info); if (addLoginResult.Succeeded) { // Update any authentication tokens if succeeded await _memberSignInManager.UpdateExternalAuthenticationTokensAsync(info); return RedirectToLocal(returnUrl); } //Add errors and redirect for it to be displayed errors.AddRange(addLoginResult.Errors.Select(x => x.Description)); } } ViewData.SetExternalSignInProviderErrors( new BackOfficeExternalLoginProviderErrors( loginProvider, errors)); return CurrentUmbracoPage(); } private IActionResult RedirectToLocal(string returnUrl) => Url.IsLocalUrl(returnUrl) ? Redirect(returnUrl) : RedirectToCurrentUmbracoPage(); [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Disassociate(string provider, string providerKey, string returnUrl = null) { if (returnUrl.IsNullOrWhiteSpace()) { returnUrl = Request.GetEncodedPathAndQuery(); } MemberIdentityUser user = await _memberManager.FindByIdAsync(User.Identity.GetUserId()); IdentityResult result = await _memberManager.RemoveLoginAsync(user, provider, providerKey); if (result.Succeeded) { await _memberSignInManager.SignInAsync(user, false); return RedirectToLocal(returnUrl); } AddModelErrors(result); return CurrentUmbracoPage(); } } }
// 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.ComponentModel; namespace System.Collections.Immutable { public sealed partial class ImmutableList<T> { /// <summary> /// Enumerates the contents of a binary tree. /// </summary> /// <remarks> /// This struct can and should be kept in exact sync with the other binary tree enumerators: /// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>. /// /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator<T>, ISecurePooledObjectUser, IStrongEnumerator<T> { /// <summary> /// The resource pool of reusable mutable stacks for purposes of enumeration. /// </summary> /// <remarks> /// We utilize this resource pool to make "allocation free" enumeration achievable. /// </remarks> private static readonly SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator> s_EnumeratingStacks = new SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator>(); /// <summary> /// The builder being enumerated, if applicable. /// </summary> private readonly Builder _builder; /// <summary> /// A unique ID for this instance of this enumerator. /// Used to protect pooled objects from use after they are recycled. /// </summary> private readonly int _poolUserId; /// <summary> /// The starting index of the collection at which to begin enumeration. /// </summary> private readonly int _startIndex; /// <summary> /// The number of elements to include in the enumeration. /// </summary> private readonly int _count; /// <summary> /// The number of elements left in the enumeration. /// </summary> private int _remainingCount; /// <summary> /// A value indicating whether this enumerator walks in reverse order. /// </summary> private bool _reversed; /// <summary> /// The set being enumerated. /// </summary> private Node _root; /// <summary> /// The stack to use for enumerating the binary tree. /// </summary> private SecurePooledObject<Stack<RefAsValueType<Node>>> _stack; /// <summary> /// The node currently selected. /// </summary> private Node _current; /// <summary> /// The version of the builder (when applicable) that is being enumerated. /// </summary> private int _enumeratingBuilderVersion; /// <summary> /// Initializes an <see cref="Enumerator"/> structure. /// </summary> /// <param name="root">The root of the set to be enumerated.</param> /// <param name="builder">The builder, if applicable.</param> /// <param name="startIndex">The index of the first element to enumerate.</param> /// <param name="count">The number of elements in this collection.</param> /// <param name="reversed"><c>true</c> if the list should be enumerated in reverse order.</param> internal Enumerator(Node root, Builder builder = null, int startIndex = -1, int count = -1, bool reversed = false) { Requires.NotNull(root, nameof(root)); Requires.Range(startIndex >= -1, nameof(startIndex)); Requires.Range(count >= -1, nameof(count)); Requires.Argument(reversed || count == -1 || (startIndex == -1 ? 0 : startIndex) + count <= root.Count); Requires.Argument(!reversed || count == -1 || (startIndex == -1 ? root.Count - 1 : startIndex) - count + 1 >= 0); _root = root; _builder = builder; _current = null; _startIndex = startIndex >= 0 ? startIndex : (reversed ? root.Count - 1 : 0); _count = count == -1 ? root.Count : count; _remainingCount = _count; _reversed = reversed; _enumeratingBuilderVersion = builder != null ? builder.Version : -1; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (_count > 0) { if (!s_EnumeratingStacks.TryTake(this, out _stack)) { _stack = s_EnumeratingStacks.PrepNew(this, new Stack<RefAsValueType<Node>>(root.Height)); } this.ResetStack(); } } /// <inheritdoc/> int ISecurePooledObjectUser.PoolUserId => _poolUserId; /// <summary> /// The current element. /// </summary> public T Current { get { this.ThrowIfDisposed(); if (_current != null) { return _current.Value; } throw new InvalidOperationException(); } } /// <summary> /// The current element. /// </summary> object System.Collections.IEnumerator.Current => this.Current; /// <summary> /// Disposes of this enumerator and returns the stack reference to the resource pool. /// </summary> public void Dispose() { _root = null; _current = null; Stack<RefAsValueType<Node>> stack; if (_stack != null && _stack.TryUse(ref this, out stack)) { stack.ClearFastWhenEmpty(); s_EnumeratingStacks.TryAdd(this, _stack); } _stack = null; } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); this.ThrowIfChanged(); if (_stack != null) { var stack = _stack.Use(ref this); if (_remainingCount > 0 && stack.Count > 0) { Node n = stack.Pop().Value; _current = n; this.PushNext(this.NextBranch(n)); _remainingCount--; return true; } } _current = null; return false; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _enumeratingBuilderVersion = _builder != null ? _builder.Version : -1; _remainingCount = _count; if (_stack != null) { this.ResetStack(); } } /// <summary>Resets the stack used for enumeration.</summary> private void ResetStack() { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); var node = _root; var skipNodes = _reversed ? _root.Count - _startIndex - 1 : _startIndex; while (!node.IsEmpty && skipNodes != this.PreviousBranch(node).Count) { if (skipNodes < this.PreviousBranch(node).Count) { stack.Push(new RefAsValueType<Node>(node)); node = this.PreviousBranch(node); } else { skipNodes -= this.PreviousBranch(node).Count + 1; node = this.NextBranch(node); } } if (!node.IsEmpty) { stack.Push(new RefAsValueType<Node>(node)); } } /// <summary> /// Obtains the right branch of the given node (or the left, if walking in reverse). /// </summary> private Node NextBranch(Node node) => _reversed ? node.Left : node.Right; /// <summary> /// Obtains the left branch of the given node (or the right, if walking in reverse). /// </summary> private Node PreviousBranch(Node node) => _reversed ? node.Right : node.Left; /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed. /// </summary> private void ThrowIfDisposed() { // Since this is a struct, copies might not have been marked as disposed. // But the stack we share across those copies would know. // This trick only works when we have a non-null stack. // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } } /// <summary> /// Throws an exception if the underlying builder's contents have been changed since enumeration started. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the collection has changed.</exception> private void ThrowIfChanged() { if (_builder != null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration); } } /// <summary> /// Pushes this node and all its Left descendants onto the stack. /// </summary> /// <param name="node">The starting node to push onto the stack.</param> private void PushNext(Node node) { Requires.NotNull(node, nameof(node)); if (!node.IsEmpty) { var stack = _stack.Use(ref this); while (!node.IsEmpty) { stack.Push(new RefAsValueType<Node>(node)); node = this.PreviousBranch(node); } } } } } }