Ejemplo n.º 1
0
        internal void SetWrappedTask(Task wrappedTask)
        {
            Requires.NotNull(wrappedTask, nameof(wrappedTask));

            using (this.Factory.Context.NoMessagePumpSynchronizationContext.Apply())
            {
                lock (this.owner.Context.SyncContextLock)
                {
                    Assumes.Null(this.wrappedTask);
                    this.wrappedTask = wrappedTask;

                    if (wrappedTask.IsCompleted)
                    {
                        this.Complete();
                    }
                    else
                    {
                        // Arrange for the wrapped task to complete this job when the task completes.
                        this.wrappedTask.ContinueWith(
                            (t, s) => ((JoinableTask)s).Complete(),
                            this,
                            CancellationToken.None,
                            TaskContinuationOptions.ExecuteSynchronously,
                            TaskScheduler.Default);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public void Null()
        {
            object o1 = null;

            ExceptionAssert.Throws <AssumptionException>(() => { Assumes.Null(new object()); }).WithMessage("Assumption failed.");
            Assumes.Null(o1);
        }
Ejemplo n.º 3
0
        public void Null()
        {
            object o1 = null;

            ExceptionAssert.Throws(debugAssertException, () => { Assumes.Null(new object()); }).WithMessage("Assumption failed.", ExceptionMessageComparison.StartsWith);
            Assumes.Null(o1);
        }
Ejemplo n.º 4
0
            /// <summary>
            /// Executes some action on a long-lived thread.
            /// </summary>
            /// <param name="action">The delegate to execute.</param>
            /// <returns>
            /// A task that either faults with the exception thrown by <paramref name="action"/>
            /// or completes after successfully executing the delegate
            /// with a result that should be disposed when it is safe to terminate the long-lived thread.
            /// </returns>
            /// <remarks>
            /// This thread never posts to <see cref="SynchronizationContext.Current"/>, so it is safe
            /// to call this method and synchronously block on its result.
            /// </remarks>
            internal static async Task <IDisposable> ExecuteOnDedicatedThreadAsync(Action action)
            {
                Requires.NotNull(action, nameof(action));

                var  tcs = new TaskCompletionSource <EmptyStruct>();
                bool keepAliveCountIncremented = false;

                try
                {
                    lock (SyncObject)
                    {
                        PendingWork.Enqueue(Tuple.Create(action, tcs));

                        try
                        {
                            // This block intentionally left blank.
                        }
                        finally
                        {
                            // We make these two assignments within a finally block
                            // to guard against an untimely ThreadAbortException causing
                            // us to execute just one of them.
                            keepAliveCountIncremented = true;
                            ++keepAliveCount;
                        }

                        if (keepAliveCount == 1)
                        {
                            Assumes.Null(liveThread);
                            liveThread = new Thread(Worker, SmallThreadStackSize)
                            {
                                IsBackground = true,
                                Name         = "Registry watcher",
                            };
                            liveThread.Start();
                        }
                        else
                        {
                            // There *could* temporarily be multiple threads in some race conditions.
                            // Pulse all of them so that the live one is sure to get the message.
                            Monitor.PulseAll(SyncObject);
                        }
                    }

                    await tcs.Task.ConfigureAwait(false);

                    return(new ThreadHandleRelease());
                }
                catch
                {
                    if (keepAliveCountIncremented)
                    {
                        // Our caller will never have a chance to release their claim on the dedicated thread,
                        // so do it for them.
                        ReleaseRefOnDedicatedThread();
                    }

                    throw;
                }
            }
Ejemplo n.º 5
0
        /// <summary>
        /// Stores the continuation for later execution when <see cref="Resume"/> is invoked.
        /// </summary>
        /// <param name="continuation">The delegate to execute later.</param>
        public void OnCompleted(Action continuation)
        {
            Requires.NotNull(continuation, nameof(continuation));
            Assumes.Null(this.continuation); // Only one continuation is supported.

            this.capturedSynchronizationContext = SynchronizationContext.Current;
            this.continuation = continuation;
        }
Ejemplo n.º 6
0
        public async Task InitializeAsync(IAsyncServiceProvider asyncServiceProvider)
        {
            Assumes.Null(_solution);
            Assumes.True(_context.IsOnMainThread, "Must be on UI thread");

            _solution = await asyncServiceProvider.GetServiceAsync <IVsSolution, IVsSolution>();

            Verify.HResult(_solution.AdviseSolutionEvents(this, out _cookie));
        }
Ejemplo n.º 7
0
        public async Task InitializeAsync(IAsyncServiceProvider asyncServiceProvider)
        {
            Assumes.Null(_projectSelector);
            Assumes.True(_context.IsOnMainThread, "Must be on UI thread");

            _projectSelector = await asyncServiceProvider.GetServiceAsync <SVsRegisterProjectTypes, IVsRegisterProjectSelector>();

            Guid selectorGuid = GetType().GUID;

            _projectSelector.RegisterProjectSelector(ref selectorGuid, this, out _cookie);
        }
Ejemplo n.º 8
0
        public async ValueTask <IReadOnlyList <ProjectAction> > GetUninstallActionsAsync(
            string projectId,
            PackageIdentity packageIdentity,
            bool removeDependencies,
            bool forceRemove,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectId);
            Assumes.NotNull(packageIdentity);
            Assumes.False(packageIdentity.HasVersion);
            Assumes.NotNull(_state.SourceCacheContext);
            Assumes.NotNull(_state.ResolvedActions);
            Assumes.Null(_state.PackageIdentity);

            cancellationToken.ThrowIfCancellationRequested();

            return(await CatchAndRethrowExceptionAsync(async() =>
            {
                INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync <INuGetProjectContext>();
                (bool success, NuGetProject? project) = await TryGetNuGetProjectMatchingProjectIdAsync(projectId);

                Assumes.True(success);
                Assumes.NotNull(project);

                var projectActions = new List <ProjectAction>();
                var uninstallationContext = new UninstallationContext(removeDependencies, forceRemove);

                NuGetPackageManager packageManager = await _sharedState.PackageManager.GetValueAsync(cancellationToken);
                IEnumerable <NuGetProjectAction> actions = await packageManager.PreviewUninstallPackageAsync(
                    project,
                    packageIdentity.Id,
                    uninstallationContext,
                    projectContext,
                    cancellationToken);

                foreach (NuGetProjectAction action in actions)
                {
                    var resolvedAction = new ResolvedAction(project, action);
                    var projectAction = new ProjectAction(
                        CreateProjectActionId(),
                        projectId,
                        action.PackageIdentity,
                        action.NuGetProjectActionType,
                        implicitActions: null);

                    _state.ResolvedActions[projectAction.Id] = resolvedAction;

                    projectActions.Add(projectAction);
                }

                return projectActions;
            }));
        }
Ejemplo n.º 9
0
        public async Task InitializeAsync(IAsyncServiceProvider asyncServiceProvider)
        {
            Assumes.Null(_registerProjectTypes);
            Assumes.True(_context.IsOnMainThread, "Must be on UI thread");

            _registerProjectTypes = await asyncServiceProvider.GetServiceAsync <SVsRegisterProjectTypes, IVsRegisterProjectTypes>();

            ((IVsProjectFactory)this).SetSite(new ServiceProviderToOleServiceProviderAdapter(ServiceProvider.GlobalProvider));

            Guid guid = GetType().GUID;

            Verify.HResult(_registerProjectTypes.RegisterProjectType(ref guid, this, out _cookie));
        }
Ejemplo n.º 10
0
        internal void DocumentReopened(ITextDocument document)
        {
            Requires.NotNull(document, nameof(document));
            Assumes.Null(this.Document);

            this.Document = document;
            document.FileActionOccurred += this.OnFileActionOccurred;

            foreach (var s in this.Spans)
            {
                s.DocumentReopened();
            }
        }
Ejemplo n.º 11
0
        public async ValueTask <IReadOnlyList <ProjectAction> > GetUninstallActionsAsync(
            IReadOnlyCollection <string> projectIds,
            PackageIdentity packageIdentity,
            bool removeDependencies,
            bool forceRemove,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectIds);
            Assumes.NotNull(packageIdentity);
            Assumes.False(packageIdentity.HasVersion);
            Assumes.NotNull(_state.SourceCacheContext);
            Assumes.Null(_state.PackageIdentity);
            Assumes.True(_state.ResolvedActions.Count == 0);

            cancellationToken.ThrowIfCancellationRequested();

            return(await CatchAndRethrowExceptionAsync(async() =>
            {
                INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync <INuGetProjectContext>();
                IReadOnlyList <NuGetProject> projects = await GetProjectsAsync(projectIds, cancellationToken);

                var projectActions = new List <ProjectAction>();
                var uninstallationContext = new UninstallationContext(removeDependencies, forceRemove);

                NuGetPackageManager packageManager = await _sharedState.GetPackageManagerAsync(cancellationToken);
                IEnumerable <NuGetProjectAction> projectsWithActions = await packageManager.PreviewProjectsUninstallPackageAsync(
                    projects,
                    packageIdentity.Id,
                    uninstallationContext,
                    projectContext,
                    cancellationToken);

                foreach (NuGetProjectAction projectWithActions in projectsWithActions)
                {
                    var resolvedAction = new ResolvedAction(projectWithActions.Project, projectWithActions);
                    var projectAction = new ProjectAction(
                        CreateProjectActionId(),
                        projectWithActions.Project.GetMetadata <string>(NuGetProjectMetadataKeys.ProjectId),
                        projectWithActions.PackageIdentity,
                        projectWithActions.NuGetProjectActionType,
                        implicitActions: null);

                    _state.ResolvedActions[projectAction.Id] = resolvedAction;

                    projectActions.Add(projectAction);
                }

                return projectActions;
            }));
        }
Ejemplo n.º 12
0
            /// <summary>
            /// Apply channel options to this channel, including setting up or linking to an user-supplied pipe writer/reader pair.
            /// </summary>
            /// <param name="channelOptions">The channel options to apply.</param>
            private void ApplyChannelOptions(ChannelOptions channelOptions)
            {
                Requires.NotNull(channelOptions, nameof(channelOptions));
                Assumes.Null(this.TraceSource); // We've already applied options

                try
                {
                    this.TraceSource = channelOptions.TraceSource
                                       ?? this.MultiplexingStream.DefaultChannelTraceSourceFactory?.Invoke(this.QualifiedId, this.Name)
                                       ?? new TraceSource($"{nameof(Streams.MultiplexingStream)}.{nameof(Channel)} {this.QualifiedId} ({this.Name})", SourceLevels.Critical);

                    lock (this.SyncObject)
                    {
                        Verify.NotDisposed(this);
                        this.InitializeOwnPipes();
                        if (channelOptions.ExistingPipe is object)
                        {
                            Assumes.NotNull(this.channelIO);
                            this.existingPipe      = channelOptions.ExistingPipe;
                            this.existingPipeGiven = true;

                            // We always want to write ALL received data to the user's ExistingPipe, rather than truncating it on disposal, so don't use a cancellation token in that direction.
                            this.DisposeSelfOnFailure(this.channelIO.Input.LinkToAsync(channelOptions.ExistingPipe.Output));

                            // Upon disposal, we no longer want to continue reading from the user's ExistingPipe into our buffer since we won't be propagating it any further, so use our DisposalToken.
                            this.DisposeSelfOnFailure(channelOptions.ExistingPipe.Input.LinkToAsync(this.channelIO.Output, this.DisposalToken));
                        }
                        else
                        {
                            this.existingPipeGiven = false;
                        }
                    }

                    this.mxStreamIOReaderCompleted = this.ProcessOutboundTransmissionsAsync();
                    this.DisposeSelfOnFailure(this.mxStreamIOReaderCompleted);
                    this.DisposeSelfOnFailure(this.AutoCloseOnPipesClosureAsync());
                }
                catch (Exception ex)
                {
                    this.optionsAppliedTaskSource?.TrySetException(ex);
                    throw;
                }
                finally
                {
                    this.optionsAppliedTaskSource?.TrySetResult(null);
                }
            }
Ejemplo n.º 13
0
            /// <summary>
            /// Apply channel options to this channel, including setting up or linking to an user-supplied pipe writer/reader pair.
            /// </summary>
            /// <param name="channelOptions">The channel options to apply.</param>
            private void ApplyChannelOptions(ChannelOptions channelOptions)
            {
                Requires.NotNull(channelOptions, nameof(channelOptions));
                Assumes.Null(this.TraceSource); // We've already applied options

                try
                {
                    this.TraceSource = channelOptions.TraceSource
                                       ?? this.MultiplexingStream.DefaultChannelTraceSourceFactory?.Invoke(this.Id, this.Name)
                                       ?? new TraceSource($"{nameof(Streams.MultiplexingStream)}.{nameof(Channel)} {this.Id} ({this.Name})", SourceLevels.Critical);

                    lock (this.SyncObject)
                    {
                        Verify.NotDisposed(this);
                        this.InitializeOwnPipes();
                        if (channelOptions.ExistingPipe is object)
                        {
                            Assumes.NotNull(this.channelIO);
                            this.DisposeSelfOnFailure(this.channelIO.LinkToAsync(channelOptions.ExistingPipe, propagateSuccessfulCompletion: true));
                            this.existingPipeGiven = true;
                        }
                        else
                        {
                            this.existingPipeGiven = false;
                        }
                    }

                    this.mxStreamIOReaderCompleted = this.ProcessOutboundTransmissionsAsync();
                    this.DisposeSelfOnFailure(this.mxStreamIOReaderCompleted);
                    this.DisposeSelfOnFailure(this.AutoCloseOnPipesClosureAsync());
                }
                catch (Exception ex)
                {
                    this.optionsAppliedTaskSource?.TrySetException(ex);
                    throw;
                }
                finally
                {
                    this.optionsAppliedTaskSource?.TrySetResult(null);
                }
            }
Ejemplo n.º 14
0
        public async ValueTask <IReadOnlyList <ProjectAction> > GetUpdateActionsAsync(
            IReadOnlyCollection <string> projectIds,
            IReadOnlyCollection <PackageIdentity> packageIdentities,
            VersionConstraints versionConstraints,
            bool includePrelease,
            DependencyBehavior dependencyBehavior,
            IReadOnlyList <string> packageSourceNames,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectIds);
            Assumes.NotNullOrEmpty(packageIdentities);
            Assumes.NotNullOrEmpty(packageSourceNames);
            Assumes.NotNull(_state.SourceCacheContext);
            Assumes.NotNull(_state.ResolvedActions);
            Assumes.Null(_state.PackageIdentity);

            var primarySources   = new List <SourceRepository>();
            var secondarySources = new List <SourceRepository>();

            ISourceRepositoryProvider sourceRepositoryProvider = await _sharedState.SourceRepositoryProvider.GetValueAsync(cancellationToken);

            IEnumerable <SourceRepository> sourceRepositories = sourceRepositoryProvider.GetRepositories();
            var packageSourceNamesSet = new HashSet <string>(packageSourceNames, StringComparer.OrdinalIgnoreCase);

            foreach (SourceRepository sourceRepository in sourceRepositories)
            {
                if (packageSourceNamesSet.Contains(sourceRepository.PackageSource.Name))
                {
                    primarySources.Add(sourceRepository);
                }

                if (sourceRepository.PackageSource.IsEnabled)
                {
                    secondarySources.Add(sourceRepository);
                }
            }

            INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync <INuGetProjectContext>();

            var projects = new List <NuGetProject>();

            foreach (string projectId in projectIds)
            {
                (bool success, NuGetProject? project) = await TryGetNuGetProjectMatchingProjectIdAsync(projectId);

                Assumes.True(success);
                Assumes.NotNull(project);

                projects.Add(project);
            }

            var resolutionContext = new ResolutionContext(
                dependencyBehavior,
                includePrelease,
                includeUnlisted: true,
                versionConstraints,
                new GatherCache(),
                _state.SourceCacheContext);

            NuGetPackageManager packageManager = await _sharedState.PackageManager.GetValueAsync(cancellationToken);

            IEnumerable <NuGetProjectAction> actions = await packageManager.PreviewUpdatePackagesAsync(
                packageIdentities.ToList(),
                projects,
                resolutionContext,
                projectContext,
                primarySources,
                secondarySources,
                cancellationToken);

            var projectActions = new List <ProjectAction>();

            foreach (NuGetProjectAction action in actions)
            {
                string projectId      = action.Project.GetMetadata <string>(NuGetProjectMetadataKeys.ProjectId);
                var    resolvedAction = new ResolvedAction(action.Project, action);
                var    projectAction  = new ProjectAction(
                    CreateProjectActionId(),
                    projectId,
                    action.PackageIdentity,
                    action.NuGetProjectActionType,
                    implicitActions: null);

                _state.ResolvedActions[projectAction.Id] = resolvedAction;

                projectActions.Add(projectAction);
            }

            return(projectActions);
        }
Ejemplo n.º 15
0
        internal void Post(SendOrPostCallback d, object state, bool mainThreadAffinitized)
        {
            using (this.Factory.Context.NoMessagePumpSynchronizationContext.Apply())
            {
                SingleExecuteProtector       wrapper          = null;
                List <AsyncManualResetEvent> eventsNeedNotify = null; // initialized if we should pulse it at the end of the method
                bool postToFactory = false;

                bool isCompleteRequested;
                bool synchronouslyBlockingMainThread;
                lock (this.owner.Context.SyncContextLock)
                {
                    isCompleteRequested             = this.IsCompleteRequested;
                    synchronouslyBlockingMainThread = this.SynchronouslyBlockingMainThread;
                }

                if (isCompleteRequested)
                {
                    // This job has already been marked for completion.
                    // We need to forward the work to the fallback mechanisms.
                    postToFactory = true;
                }
                else
                {
                    bool mainThreadQueueUpdated       = false;
                    bool backgroundThreadQueueUpdated = false;
                    wrapper = SingleExecuteProtector.Create(this, d, state);

                    if (ThreadingEventSource.Instance.IsEnabled())
                    {
                        ThreadingEventSource.Instance.PostExecutionStart(wrapper.GetHashCode(), mainThreadAffinitized);
                    }

                    if (mainThreadAffinitized && !synchronouslyBlockingMainThread)
                    {
                        wrapper.RaiseTransitioningEvents();
                    }

                    lock (this.owner.Context.SyncContextLock)
                    {
                        if (mainThreadAffinitized)
                        {
                            if (this.mainThreadQueue == null)
                            {
                                this.mainThreadQueue = new ExecutionQueue(this);
                            }

                            // Try to post the message here, but we'll also post to the underlying sync context
                            // so if this fails (because the operation has completed) we'll still get the work
                            // done eventually.
                            this.mainThreadQueue.TryEnqueue(wrapper);
                            mainThreadQueueUpdated = true;
                        }
                        else
                        {
                            if (this.SynchronouslyBlockingThreadPool)
                            {
                                if (this.threadPoolQueue == null)
                                {
                                    this.threadPoolQueue = new ExecutionQueue(this);
                                }

                                backgroundThreadQueueUpdated = this.threadPoolQueue.TryEnqueue(wrapper);
                                if (!backgroundThreadQueueUpdated)
                                {
                                    ThreadPool.QueueUserWorkItem(SingleExecuteProtector.ExecuteOnceWaitCallback, wrapper);
                                }
                            }
                            else
                            {
                                ThreadPool.QueueUserWorkItem(SingleExecuteProtector.ExecuteOnceWaitCallback, wrapper);
                            }
                        }

                        if (mainThreadQueueUpdated || backgroundThreadQueueUpdated)
                        {
                            var tasksNeedNotify = this.GetDependingSynchronousTasks(mainThreadQueueUpdated);
                            if (tasksNeedNotify.Count > 0)
                            {
                                eventsNeedNotify = new List <AsyncManualResetEvent>(tasksNeedNotify.Count);
                                foreach (var taskToNotify in tasksNeedNotify)
                                {
                                    if (taskToNotify.pendingEventSource == null || taskToNotify == this)
                                    {
                                        taskToNotify.pendingEventSource = this.WeakSelf;
                                    }

                                    taskToNotify.pendingEventCount++;
                                    if (taskToNotify.queueNeedProcessEvent != null)
                                    {
                                        eventsNeedNotify.Add(taskToNotify.queueNeedProcessEvent);
                                    }
                                }
                            }
                        }
                    }
                }

                // Notify tasks which can process the event queue.
                if (eventsNeedNotify != null)
                {
                    foreach (var queueEvent in eventsNeedNotify)
                    {
                        queueEvent.PulseAll();
                    }
                }

                // We deferred this till after we release our lock earlier in this method since we're calling outside code.
                if (postToFactory)
                {
                    Assumes.Null(wrapper); // we avoid using a wrapper in this case because this job transferring ownership to the factory.
                    this.Factory.Post(d, state, mainThreadAffinitized);
                }
                else if (mainThreadAffinitized)
                {
                    Assumes.NotNull(wrapper); // this should have been initialized in the above logic.
                    this.owner.PostToUnderlyingSynchronizationContextOrThreadPool(wrapper);

                    foreach (var nestingFactory in this.nestingFactories)
                    {
                        if (nestingFactory != this.owner)
                        {
                            nestingFactory.PostToUnderlyingSynchronizationContextOrThreadPool(wrapper);
                        }
                    }
                }
            }
        }
            /// <summary>
            /// Apply channel options to this channel, including setting up or migrating to an user-supplied pipe writer/reader pair.
            /// </summary>
            /// <param name="channelOptions">The channel options to apply.</param>
            private void ApplyChannelOptions(ChannelOptions channelOptions)
            {
                Requires.NotNull(channelOptions, nameof(channelOptions));
                Assumes.Null(this.TraceSource); // We've already applied options

                try
                {
                    this.TraceSource = channelOptions.TraceSource
                                       ?? this.MultiplexingStream.DefaultChannelTraceSourceFactory?.Invoke(this.Id, this.Name)
                                       ?? new TraceSource($"{nameof(Streams.MultiplexingStream)}.{nameof(Channel)} {this.Id} ({this.Name})", SourceLevels.Critical);

                    lock (this.SyncObject)
                    {
                        Verify.NotDisposed(this);
                        if (channelOptions.ExistingPipe != null)
                        {
                            if (this.mxStreamIOWriter != null)
                            {
                                // A Pipe was already created (because data has been coming in for this channel even before it was accepted).
                                // To be most efficient, we need to:
                                // 1. Start forwarding all bytes written with this.mxStreamIOWriter to channelOptions.ExistingPipe.Output
                                // 2. Arrange for the *next* call to GetReceivedMessagePipeWriterAsync to:
                                //      call this.mxStreamIOWriter.Complete()
                                //      wait for our forwarding code to finish (without propagating copmletion to channel.ExistingPipe.Output)
                                //      return channel.ExistingPipe.Output
                                //    From then on, GetReceivedMessagePipeWriterAsync should simply return channel.ExistingPipe.Output
                                // Since this channel hasn't yet been exposed to the local owner, we can just replace the PipeWriter they use to transmit.

                                // Take ownership of reading bytes that the MultiplexingStream may have already written to this channel.
                                var mxStreamIncomingBytesReader = this.channelIO !.Input;
                                this.channelIO = null;

                                // Forward any bytes written by the MultiplexingStream to the ExistingPipe.Output writer,
                                // and make that ExistingPipe.Output writer available only after the old Pipe-based writer has completed.
                                // First, capture the ExistingPipe as a local since ChannelOptions is a mutable type, and we're going to need
                                // its current value later on.
                                var existingPipe = channelOptions.ExistingPipe;
                                this.switchingToExistingPipe = Task.Run(async delegate
                                {
                                    // Await propagation of all bytes. Don't complete the ExistingPipe.Output when we're done because we still want to use it.
                                    await mxStreamIncomingBytesReader.LinkToAsync(existingPipe.Output, propagateSuccessfulCompletion: false).ConfigureAwait(false);
                                    return(existingPipe.Output);
                                });
                            }
                            else
                            {
                                // We haven't created a Pipe yet, so we can simply direct all writing to the ExistingPipe.Output immediately.
                                this.mxStreamIOWriter = channelOptions.ExistingPipe.Output;
                            }

                            this.mxStreamIOReader = channelOptions.ExistingPipe.Input;
                        }
                        else if (channelOptions.InputPipeOptions != null && this.mxStreamIOWriter != null)
                        {
                            // Similar strategy to the situation above with ExistingPipe.
                            // Take ownership of reading bytes that the MultiplexingStream may have already written to this channel.
                            var mxStreamIncomingBytesReader = this.channelIO !.Input;

                            var writerRelay = new Pipe();
                            var readerRelay = new Pipe(channelOptions.InputPipeOptions);
                            this.mxStreamIOReader = writerRelay.Reader;
                            this.channelIO        = new DuplexPipe(readerRelay.Reader, writerRelay.Writer);

                            this.switchingToExistingPipe = Task.Run(async delegate
                            {
                                // Await propagation of all bytes. Don't complete the readerRelay.Writer when we're done because we still want to use it.
                                await mxStreamIncomingBytesReader.LinkToAsync(readerRelay.Writer, propagateSuccessfulCompletion: false).ConfigureAwait(false);
                                return(readerRelay.Writer);
                            });
                        }
                        else
                        {
                            this.InitializeOwnPipes(channelOptions.InputPipeOptions ?? PipeOptions.Default);
                        }
                    }

                    this.mxStreamIOReaderCompleted = this.ProcessOutboundTransmissionsAsync();
                    this.DisposeSelfOnFailure(this.mxStreamIOReaderCompleted);
                    this.DisposeSelfOnFailure(this.AutoCloseOnPipesClosureAsync());
                }
                catch (Exception ex)
                {
                    this.optionsAppliedTaskSource?.TrySetException(ex);
                    throw;
                }
                finally
                {
                    this.optionsAppliedTaskSource?.TrySetResult(null);
                }
            }
Ejemplo n.º 17
0
        public async ValueTask <IReadOnlyList <ProjectAction> > GetUpdateActionsAsync(
            IReadOnlyCollection <string> projectIds,
            IReadOnlyCollection <PackageIdentity> packageIdentities,
            VersionConstraints versionConstraints,
            bool includePrelease,
            DependencyBehavior dependencyBehavior,
            IReadOnlyList <string> packageSourceNames,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectIds);
            Assumes.NotNullOrEmpty(packageIdentities);
            Assumes.NotNullOrEmpty(packageSourceNames);
            Assumes.NotNull(_state.SourceCacheContext);
            Assumes.NotNull(_state.ResolvedActions);
            Assumes.Null(_state.PackageIdentity);

            return(await CatchAndRethrowExceptionAsync(async() =>
            {
                var primarySources = new List <SourceRepository>();
                var secondarySources = new List <SourceRepository>();

                IEnumerable <SourceRepository> sourceRepositories = _sharedState.SourceRepositoryProvider.GetRepositories();
                var packageSourceNamesSet = new HashSet <string>(packageSourceNames, StringComparer.OrdinalIgnoreCase);

                foreach (SourceRepository sourceRepository in sourceRepositories)
                {
                    if (packageSourceNamesSet.Contains(sourceRepository.PackageSource.Name))
                    {
                        primarySources.Add(sourceRepository);
                    }

                    if (sourceRepository.PackageSource.IsEnabled)
                    {
                        secondarySources.Add(sourceRepository);
                    }
                }

                INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync <INuGetProjectContext>();
                IReadOnlyList <NuGetProject> projects = await GetProjectsAsync(projectIds, cancellationToken);

                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease,
                    includeUnlisted: true,
                    versionConstraints,
                    new GatherCache(),
                    _state.SourceCacheContext);

                NuGetPackageManager packageManager = await _sharedState.GetPackageManagerAsync(cancellationToken);
                IEnumerable <NuGetProjectAction> actions = await packageManager.PreviewUpdatePackagesAsync(
                    packageIdentities.ToList(),
                    projects,
                    resolutionContext,
                    projectContext,
                    primarySources,
                    secondarySources,
                    cancellationToken);

                var projectActions = new List <ProjectAction>();

                foreach (NuGetProjectAction action in actions)
                {
                    var resolvedAction = new ResolvedAction(action.Project, action);
                    ProjectAction projectAction = CreateProjectAction(resolvedAction);

                    _state.ResolvedActions[projectAction.Id] = resolvedAction;

                    projectActions.Add(projectAction);
                }

                return projectActions;
            }));
        }
Ejemplo n.º 18
0
        public async ValueTask <IReadOnlyList <ProjectAction> > GetInstallActionsAsync(
            IReadOnlyCollection <string> projectIds,
            PackageIdentity packageIdentity,
            VersionConstraints versionConstraints,
            bool includePrelease,
            DependencyBehavior dependencyBehavior,
            IReadOnlyList <string> packageSourceNames,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectIds);
            Assumes.NotNull(packageIdentity);
            Assumes.NotNullOrEmpty(packageSourceNames);
            Assumes.Null(_state.PackageIdentity);
            Assumes.True(_state.ResolvedActions.Count == 0);
            Assumes.NotNull(_state.SourceCacheContext);

            cancellationToken.ThrowIfCancellationRequested();

            return(await CatchAndRethrowExceptionAsync(async() =>
            {
                _state.PackageIdentity = packageIdentity;

                IReadOnlyList <SourceRepository> sourceRepositories = GetSourceRepositories(
                    packageSourceNames,
                    cancellationToken);

                Assumes.NotNullOrEmpty(sourceRepositories);

                INuGetProjectContext projectContext = await ServiceLocator.GetComponentModelServiceAsync <INuGetProjectContext>();
                IReadOnlyList <NuGetProject> projects = await GetProjectsAsync(projectIds, cancellationToken);

                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease,
                    includeUnlisted: false,
                    versionConstraints,
                    new GatherCache(),
                    _state.SourceCacheContext);

                NuGetPackageManager packageManager = await _sharedState.GetPackageManagerAsync(cancellationToken);
                IEnumerable <ResolvedAction> resolvedActions = await packageManager.PreviewProjectsInstallPackageAsync(
                    projects,
                    _state.PackageIdentity,
                    resolutionContext,
                    projectContext,
                    sourceRepositories,
                    cancellationToken);

                var projectActions = new List <ProjectAction>();

                foreach (ResolvedAction resolvedAction in resolvedActions)
                {
                    ProjectAction projectAction = CreateProjectAction(resolvedAction);

                    _state.ResolvedActions[projectAction.Id] = resolvedAction;

                    projectActions.Add(projectAction);
                }

                return projectActions;
            }));
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Sets the stream to copy written data to.
 /// </summary>
 /// <param name="other">The other stream.</param>
 internal void SetOtherStream(FullDuplexStream other)
 {
     Requires.NotNull(other, nameof(other));
     Assumes.Null(this.other);
     this.other = other;
 }
Ejemplo n.º 20
0
        public async ValueTask <IReadOnlyList <ProjectAction> > GetInstallActionsAsync(
            IReadOnlyCollection <string> projectIds,
            PackageIdentity packageIdentity,
            VersionConstraints versionConstraints,
            bool includePrelease,
            DependencyBehavior dependencyBehavior,
            IReadOnlyList <string> packageSourceNames,
            CancellationToken cancellationToken)
        {
            Assumes.NotNullOrEmpty(projectIds);
            Assumes.NotNull(packageIdentity);
            Assumes.NotNullOrEmpty(packageSourceNames);
            Assumes.Null(_state.PackageIdentity);
            Assumes.True(_state.ResolvedActions.Count == 0);
            Assumes.NotNull(_state.SourceCacheContext);

            cancellationToken.ThrowIfCancellationRequested();

            _state.PackageIdentity = packageIdentity;

            IReadOnlyList <SourceRepository> sourceRepositories = await GetSourceRepositoriesAsync(
                packageSourceNames,
                cancellationToken);

            Assumes.NotNullOrEmpty(sourceRepositories);

            INuGetProjectContext projectContext = await ServiceLocator.GetInstanceAsync <INuGetProjectContext>();

            IReadOnlyList <NuGetProject> projects = await GetProjectsAsync(projectIds, cancellationToken);

            var resolutionContext = new ResolutionContext(
                dependencyBehavior,
                includePrelease,
                includeUnlisted: false,
                versionConstraints,
                new GatherCache(),
                _state.SourceCacheContext);

            NuGetPackageManager packageManager = await _sharedState.PackageManager.GetValueAsync(cancellationToken);

            IEnumerable <ResolvedAction> resolvedActions = await packageManager.PreviewProjectsInstallPackageAsync(
                projects,
                _state.PackageIdentity,
                resolutionContext,
                projectContext,
                sourceRepositories,
                cancellationToken);

            var projectActions = new List <ProjectAction>();

            foreach (ResolvedAction resolvedAction in resolvedActions)
            {
                List <ImplicitProjectAction>?implicitActions = null;

                if (resolvedAction.Action is BuildIntegratedProjectAction buildIntegratedAction)
                {
                    implicitActions = new List <ImplicitProjectAction>();

                    foreach (NuGetProjectAction?buildAction in buildIntegratedAction.GetProjectActions())
                    {
                        var implicitAction = new ImplicitProjectAction(
                            CreateProjectActionId(),
                            buildAction.PackageIdentity,
                            buildAction.NuGetProjectActionType);

                        implicitActions.Add(implicitAction);
                    }
                }

                string projectId     = resolvedAction.Project.GetMetadata <string>(NuGetProjectMetadataKeys.ProjectId);
                var    projectAction = new ProjectAction(
                    CreateProjectActionId(),
                    projectId,
                    resolvedAction.Action.PackageIdentity,
                    resolvedAction.Action.NuGetProjectActionType,
                    implicitActions);

                _state.ResolvedActions[projectAction.Id] = resolvedAction;

                projectActions.Add(projectAction);
            }

            return(projectActions);
        }
Ejemplo n.º 21
0
 public void Null_NullableStruct()
 {
     Assert.ThrowsAny <Exception>(() => Assumes.Null((int?)5));
     Assumes.Null((int?)null);
 }
Ejemplo n.º 22
0
 public void Null()
 {
     Assert.ThrowsAny <Exception>(() => Assumes.Null("not null"));
     Assumes.Null((object)null);
 }