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); }
public ReflectionType(Type type) { Assumes.NotNull(type); this._type = type; }
public void Activate() { Assumes.NotNull(this.initialization); this.initialization.Wait(); }
/// <summary> /// This is called on F5 to return the list of debug targets. What we return depends on the type /// of project. /// </summary> /// <returns><see langword="null"/> if the runnable project information is <see langword="null"/>. Otherwise, the debug launch settings.</returns> internal async Task <DebugLaunchSettings?> GetConsoleTargetForProfileAsync(ILaunchProfile resolvedProfile, DebugLaunchOptions launchOptions, bool validateSettings) { var settings = new DebugLaunchSettings(launchOptions); string?executable, arguments; string projectFolder = Path.GetDirectoryName(_project.UnconfiguredProject.FullPath) ?? string.Empty; ConfiguredProject?configuredProject = await GetConfiguredProjectForDebugAsync(); Assumes.NotNull(configuredProject); // If no working directory specified in the profile, we default to output directory. If for some reason the output directory // is not specified, fall back to the project folder. string defaultWorkingDir = await GetOutputDirectoryAsync(configuredProject); if (string.IsNullOrEmpty(defaultWorkingDir)) { defaultWorkingDir = projectFolder; } else { if (!Path.IsPathRooted(defaultWorkingDir)) { defaultWorkingDir = _fileSystem.GetFullPath(Path.Combine(projectFolder, defaultWorkingDir)); } // If the directory at OutDir doesn't exist, fall back to the project folder if (!_fileSystem.DirectoryExists(defaultWorkingDir)) { defaultWorkingDir = projectFolder; } } string?commandLineArgs = resolvedProfile.CommandLineArgs? .Replace("\r\n", " ") .Replace("\r", " ") .Replace("\n", " ") .Replace("\\r\\n", "\r\n") .Replace("\\n", "\n"); // Is this profile just running the project? If so we ignore the exe if (IsRunProjectCommand(resolvedProfile)) { // Get the executable to run, the arguments and the default working directory (string Command, string Arguments, string WorkingDirectory)? runnableProjectInfo = await GetRunnableProjectInformationAsync(configuredProject, validateSettings); if (runnableProjectInfo == null) { return(null); } string workingDirectory; (executable, arguments, workingDirectory) = runnableProjectInfo.Value; if (!string.IsNullOrWhiteSpace(workingDirectory)) { defaultWorkingDir = workingDirectory; } if (!string.IsNullOrWhiteSpace(commandLineArgs)) { arguments = arguments + " " + commandLineArgs; } } else { executable = resolvedProfile.ExecutablePath; arguments = commandLineArgs; } string workingDir; if (Strings.IsNullOrWhiteSpace(resolvedProfile.WorkingDirectory)) { workingDir = defaultWorkingDir; } else { // If the working directory is not rooted we assume it is relative to the project directory workingDir = _fileSystem.GetFullPath(Path.Combine(projectFolder, resolvedProfile.WorkingDirectory.Replace("/", "\\"))); } // IF the executable is not rooted, we want to make is relative to the workingDir unless is doesn't contain // any path elements. In that case we are going to assume it is in the current directory of the VS process, or on // the environment path. If we can't find it, we just launch it as before. if (!Strings.IsNullOrWhiteSpace(executable)) { executable = executable.Replace("/", "\\"); if (Path.GetPathRoot(executable) == "\\") { // Root of current drive executable = _fileSystem.GetFullPath(executable); } else if (!Path.IsPathRooted(executable)) { if (executable.Contains("\\")) { // Combine with the working directory used by the profile executable = _fileSystem.GetFullPath(Path.Combine(workingDir, executable)); } else { // Try to resolve against the current working directory (for compat) and failing that, the environment path. string exeName = executable.EndsWith(".exe", StringComparisons.Paths) ? executable : executable + ".exe"; string fullPath = _fileSystem.GetFullPath(exeName); if (_fileSystem.FileExists(fullPath)) { executable = fullPath; } else { string?fullPathFromEnv = GetFullPathOfExeFromEnvironmentPath(exeName); if (fullPathFromEnv != null) { executable = fullPathFromEnv; } } } } } if (validateSettings) { ValidateSettings(executable, workingDir, resolvedProfile.Name); } // Apply environment variables. if (resolvedProfile.EnvironmentVariables?.IsEmpty == false) { foreach ((string key, string value) in resolvedProfile.EnvironmentVariables) { settings.Environment[key] = value; } } settings.LaunchOperation = DebugLaunchOperation.CreateProcess; settings.LaunchDebugEngineGuid = await GetDebuggingEngineAsync(configuredProject); if (resolvedProfile.IsNativeDebuggingEnabled()) { settings.AdditionalDebugEngines.Add(DebuggerEngines.NativeOnlyEngine); } if (resolvedProfile.IsSqlDebuggingEnabled()) { settings.AdditionalDebugEngines.Add(DebuggerEngines.SqlEngine); } bool useCmdShell = false; if (await _outputTypeChecker.IsConsoleAsync()) { if (await IsIntegratedConsoleEnabledAsync()) { settings.LaunchOptions |= DebugLaunchOptions.IntegratedConsole; } useCmdShell = UseCmdShellForConsoleLaunch(resolvedProfile, settings.LaunchOptions); } GetExeAndArguments(useCmdShell, executable, arguments, out string?finalExecutable, out string?finalArguments); settings.Executable = finalExecutable; settings.Arguments = finalArguments; settings.CurrentDirectory = workingDir; settings.Project = _unconfiguredProjectVsServices.VsHierarchy; if (resolvedProfile.IsRemoteDebugEnabled()) { settings.RemoteMachine = resolvedProfile.RemoteDebugMachine(); string?remoteAuthenticationMode = resolvedProfile.RemoteAuthenticationMode(); if (!Strings.IsNullOrEmpty(remoteAuthenticationMode)) { IRemoteAuthenticationProvider?remoteAuthenticationProvider = _remoteDebuggerAuthenticationService.FindProviderForAuthenticationMode(remoteAuthenticationMode); if (remoteAuthenticationProvider != null) { settings.PortSupplierGuid = remoteAuthenticationProvider.PortSupplierGuid; } } } // WebView2 debugging is only supported for Project and Executable commands if (resolvedProfile.IsJSWebView2DebuggingEnabled() && (IsRunExecutableCommand(resolvedProfile) || IsRunProjectCommand(resolvedProfile))) { // If JS Debugger is selected, we would need to change the launch debugger to that one settings.LaunchDebugEngineGuid = DebuggerEngines.JavaScriptForWebView2Engine; // Create the launch params needed for the JS debugger var debuggerLaunchOptions = new JObject( new JProperty("type", "pwa-msedge"), new JProperty("runtimeExecutable", finalExecutable), new JProperty("webRoot", workingDir), // We use the Working Directory debugging option as the WebRoot, to map the urls to files on disk new JProperty("useWebView", true), new JProperty("runtimeArgs", finalArguments) ); settings.Options = JsonConvert.SerializeObject(debuggerLaunchOptions); } if (await HotReloadShouldBeEnabledAsync(resolvedProfile, launchOptions) && await _hotReloadSessionManager.Value.TryCreatePendingSessionAsync(settings.Environment)) { // Enable XAML Hot Reload settings.Environment["ENABLE_XAML_DIAGNOSTICS_SOURCE_INFO"] = "1"; } if (settings.Environment.Count > 0) { settings.LaunchOptions |= DebugLaunchOptions.MergeEnvironment; } return(settings); }
private static void EnsureEnabled(bool condition) { Assumes.IsTrue(condition, "To avoid unnecessary work when a trace level has not been enabled, check CanWriteXXX before calling this method."); }
/// <summary> /// This is where the information entered in the form should be saved in CPS /// </summary> public int Apply() { Assumes.NotNull(_threadHandling); return(_threadHandling.ExecuteSynchronously(OnApply)); }
public ExportFactoryCreator(Type exportFactoryType) { Assumes.NotNull(exportFactoryType); _exportFactoryType = exportFactoryType; }
/// <summary> /// Creates a populated provider context. /// </summary> /// <remarks> /// The caller is responsible to dispose of the result when its use is over. /// </remarks> /// <returns> /// A task whose result is the export life time context. The expected type of object here is <see cref="IVsReferenceProviderContext"/>. /// Returning Task<ExportLifetimeContext<object[]>> instead of Task<ExportLifetimeContext<IVsReferenceProviderContext[]>> is because IVsReferenceProviderContext is an embedded interop type, /// so it can't be used across assembly boundaries. /// </returns> public virtual Task <ExportLifetimeContext <object> > CreateProviderContextAsync() { Assumes.NotNull(NextHandler); return(NextHandler.CreateProviderContextAsync()); }
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress); //ToDo move this down - just before command initializations // When initialized asynchronously, the current thread may be a background thread at this point. // Do any initialization that requires the UI thread after switching to the UI thread. await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var dte = (DTE) await GetServiceAsync(typeof(DTE)); Assumes.Present(dte); var dte2 = (DTE2) await GetServiceAsync(typeof(SDTE)); Assumes.Present(dte2); solService = await GetServiceAsync(typeof(SVsSolution)) as IVsSolution; Assumes.Present(solService); var rdt = await GetServiceAsync(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; Assumes.Present(rdt); //! Set globals DteRefs.Package = this; DteRefs.DTE = dte; DteRefs.DTE2 = dte2; DteRefs.Solution = solService; DteRefs.RDT = rdt; //! Activate MEF ActivateMEF(); //! Get VS editor's background color var vsProperties = dte.Properties["FontsAndColors", "TextEditor"]; var fontsAndColors = vsProperties.Item("FontsAndColorsItems").Object as FontsAndColorsItems; var plainText = fontsAndColors.Item("Plain Text"); //! Set VS editor's background in configs var bg = ColorExtensions.FromInt((int)plainText.Background); commentConfigs.Defaults.VSBackground = Color.FromArgb(255, bg.R, bg.G, bg.B); //! Register classifications //? This might be redundant! clsService.SyncWithConfigs(); //! Hook events solService.AdviseSolutionEvents(ViewModelLocator.Instance, out var cookie); var events = dte2.Events as Events2; if (events != null) { ViewModelLocator.Instance.SubscribeToEvents(events); } //! Handle solution load if (await IsSolutionLoadedAsync()) { //todo Remove this if not used //! Only handle it if it's solution, and ignore it if it's a folder. //solService.GetProperty((int)__VSPROPID.VSPROPID_IsSolutionOpen, out var value); //if (await IsSolutionLoadedAsync()) //HandleOpenSolution(); // ViewModelLocator.Instance.Scanner.ScanSolution(); } await BookmarksListCommand.InitializeAsync(this); await SettingsCommand.InitializeAsync(this); }
private ProjectProperties GetProjectData() { ThreadHelper.ThrowIfNotOnUIThread(); Solution solution = GetActiveSolution(); if (solution == null) { return(null); } Project project = GetActiveProject(); if (project == null) { return(null); } VCProject prj = project.Object as VCProject; if (prj == null) { return(null); } VCConfiguration config = prj.ActiveConfiguration; if (config == null) { return(null); } VCPlatform platform = config.Platform; if (platform == null) { return(null); } var vctools = config.Tools as IVCCollection; if (vctools == null) { return(null); } var midl = vctools.Item("VCMidlTool") as VCMidlTool; ProjectProperties ret = new ProjectProperties(); ret.Target = midl != null && midl.TargetEnvironment == midlTargetEnvironment.midlTargetWin32 ? ProjectProperties.TargetType.x86 : ProjectProperties.TargetType.x64; //Working directory (always local to processed file) ret.WorkingDirectory = Path.GetDirectoryName(project.FullName); //TODO ~ ramonv ~ find a way to extract the /std value //Include dirs / files and preprocessor AppendMSBuildStringToList(ret.IncludeDirectories, platform.Evaluate(platform.IncludeDirectories)); AppendProjectProperties(ret, vctools.Item("VCCLCompilerTool") as VCCLCompilerTool, vctools.Item("VCNMakeTool") as VCNMakeTool, platform); try { //Get settings from the single file (this might fail badly if there are no settings to catpure) var applicationObject = ServiceProvider.GetService(typeof(DTE)) as EnvDTE80.DTE2; Assumes.Present(applicationObject); ProjectItem item = applicationObject.ActiveDocument.ProjectItem; VCFile vcfile = item.Object as VCFile; IVCCollection fileCfgs = (IVCCollection)vcfile.FileConfigurations; VCFileConfiguration fileConfig = fileCfgs.Item(config.Name) as VCFileConfiguration; AppendProjectProperties(ret, fileConfig.Tool as VCCLCompilerTool, fileConfig.Tool as VCNMakeTool, platform); } catch (Exception) {} SolutionSettings customSettings = SettingsManager.Instance.Settings; if (customSettings != null) { AppendMSBuildStringToList(ret.IncludeDirectories, platform.Evaluate(customSettings.AdditionalIncludeDirs)); AppendMSBuildStringToList(ret.ForceIncludes, platform.Evaluate(customSettings.AdditionalForceIncludes)); AppendMSBuildStringToList(ret.PrepocessorDefinitions, platform.Evaluate(customSettings.AdditionalPreprocessorDefinitions)); ret.ExtraArguments = platform.Evaluate(customSettings.AdditionalCommandLine); ret.ShowWarnings = customSettings.EnableWarnings; } //Exclude directories RemoveMSBuildStringFromList(ret.IncludeDirectories, platform.Evaluate(platform.ExcludeDirectories)); return(ret); }
/// <summary> /// Applies reference changes. /// </summary> /// <param name="operation">The add or remove operation as defined by <see cref="__VSREFERENCECHANGEOPERATION"/></param> /// <param name="changedContext"><see cref="IVsReferenceProviderContext"/> representing the references to change. The declaration uses object instead because IVsReferenceProviderContext is an embedded interop type, /// so it can't be used across assembly boundaries.</param> /// <returns>A task whose result changes the references.</returns> public virtual Task ChangeReferencesAsync(uint operation, object changedContext) { Assumes.NotNull(NextHandler); return(NextHandler.ChangeReferencesAsync(operation, changedContext)); }
private async ValueTask <IVsWindowFrame> CreateToolWindowAsync(WorkspaceVisualNodeBase workspaceVisualNodeBase, IVsHierarchy hier, uint itemId) { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (!Guid.TryParse(IProjectContextInfoUtility.GetProjectGuidStringFromVslsQueryString(workspaceVisualNodeBase.VSSelectionMoniker), out Guid projectGuid)) { throw new InvalidOperationException(); } IVsWindowFrame windowFrame = null; var uiShell = await _asyncServiceProvider.GetServiceAsync(typeof(SVsUIShell)) as IVsUIShell; Assumes.Present(uiShell); uint toolWindowId; bool foundToolWindowId = _projectGuidToToolWindowId.TryGetValue(projectGuid.ToString(), out toolWindowId); const uint FTW_none = 0; if (foundToolWindowId) { ErrorHandler.ThrowOnFailure( uiShell.FindToolWindowEx( FTW_none, //grfFTW - badly-documented enum value. typeof(PackageManagerToolWindowPane).GUID, // rguidPersistenceSlot toolWindowId, // dwToolWindowId out windowFrame)); if (windowFrame != null) { ((IVsWindowFrame2)windowFrame).ActivateOwnerDockedWindow(); } else { _projectGuidToToolWindowId.Remove(projectGuid.ToString()); } } if (windowFrame == null) { IServiceBroker serviceBroker = await ServiceBrokerProvider.Value.GetAsync(); IProjectContextInfo projectContextInfo = await IProjectContextInfoUtility.CreateAsync(serviceBroker, projectGuid.ToString(), CancellationToken.None); INuGetUI uiController = await UIFactory.Value.CreateAsync(serviceBroker, projectContextInfo); // This model takes ownership of --- and Dispose() responsibility for --- the INuGetUI instance. var model = new PackageManagerModel(uiController, isSolution: false, editorFactoryGuid: GuidList.NuGetEditorType); var control = await PackageManagerControl.CreateAsync(model, OutputConsoleLogger.Value); var caption = string.Format(CultureInfo.CurrentCulture, Resx.Label_NuGetWindowCaption, Path.GetFileNameWithoutExtension(workspaceVisualNodeBase.NodeMoniker)); int[] pfDefaultPosition = null; var windowPane = new PackageManagerToolWindowPane(control, projectGuid.ToString()); ErrorHandler.ThrowOnFailure( uiShell.CreateToolWindow( (uint)__VSCREATETOOLWIN.CTW_fInitNew, ++_maxToolWindowId, // dwToolWindowId windowPane, // ToolWindowPane Guid.Empty, // rclsidTool = GUID_NULL typeof(PackageManagerToolWindowPane).GUID, // rguidPersistenceSlot Guid.Empty, // reserved - do not use - GUID_NULL null, // IServiceProvider caption, pfDefaultPosition, out windowFrame)); _projectGuidToToolWindowId.Add(projectGuid.ToString(), _maxToolWindowId); windowPane.Closed += WindowPane_Closed; if (windowFrame != null) { WindowFrameHelper.AddF1HelpKeyword(windowFrame, keywordValue: F1KeywordValuePmUI); WindowFrameHelper.DisableWindowAutoReopen(windowFrame); WindowFrameHelper.DockToolWindow(windowFrame); } } return(windowFrame); }
///// <summary> ///// MvvmTools2Package GUID string. ///// </summary> //public const string PackageGuidString = "6e8a3b1d-0f93-4749-b3e8-39e83c15c82e"; #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param> /// <param name="progress">A provider for progress updates.</param> /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns> protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { try { // Add package and package specific services. Container.RegisterInstance <IMvvmToolsPackage>(this, new ContainerControlledLifetimeManager()); Container.RegisterInstance(GetGlobalService(typeof(SComponentModel)) as IComponentModel, new ContainerControlledLifetimeManager()); Container.RegisterInstance(await GetServiceAsync(typeof(IMenuCommandService)) as IMenuCommandService, new ContainerControlledLifetimeManager()); // Templating services. var tt = await GetServiceAsync(typeof(STextTemplating)) as STextTemplating; Container.RegisterInstance((ITextTemplating)tt, new ContainerControlledLifetimeManager()); Container.RegisterInstance((ITextTemplatingEngineHost)tt, new ContainerControlledLifetimeManager()); Container.RegisterInstance((ITextTemplatingSessionHost)tt, new ContainerControlledLifetimeManager()); //Kernel.Bind<ITextTemplatingEngine>().ToConstant((ITextTemplatingEngine) tt); // Our own singleton services. Container.RegisterType <ISettingsService, SettingsService>(new ContainerControlledLifetimeManager()); Container.RegisterType <IViewFactory, ViewFactory>(new ContainerControlledLifetimeManager()); Container.RegisterType <IDialogService, DialogService>(new ContainerControlledLifetimeManager()); // Option view model, a shared singleton because it's easier. Container.RegisterType <OptionsViewModel>(new ContainerControlledLifetimeManager()); Container.RegisterType <ITemplateService, TemplateService>(new ContainerControlledLifetimeManager()); await JoinableTaskFactory.SwitchToMainThreadAsync(); // Commands, which are singletons. Container.RegisterType <GoToViewOrViewModelCommand>(new ContainerControlledLifetimeManager()); //Container.RegisterType<ScaffoldViewAndViewModelCommand>(new ContainerControlledLifetimeManager()); //Container.RegisterType<ExtractViewModelFromViewCommand>(new ContainerControlledLifetimeManager()); //ServiceLocator.SetLocatorProvider(() => new NinjectServiceLocator(Container)); // Add solution services. Container.RegisterInstance(Ide, new ContainerControlledLifetimeManager()); Container.RegisterType <ISolutionService, SolutionService>(new ContainerControlledLifetimeManager()); _vsSolution = await GetServiceAsync(typeof(SVsSolution)) as IVsSolution; Assumes.Present(_vsSolution); Container.RegisterInstance(_vsSolution, new ContainerControlledLifetimeManager()); var ss = Container.Resolve <ISolutionService>(); await ss.Init(); var result = _vsSolution?.AdviseSolutionEvents(ss, out _solutionEventsCookie); await base.InitializeAsync(cancellationToken, progress); RegisterCommands(); } catch (Exception ex) { Debug.WriteLine($"MVVM Tools service startup failed: {ex}."); } // When initialized asynchronously, the current thread may be a background thread at this point. // Do any initialization that requires the UI thread after switching to the UI thread. await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); }
public static CombinedCancellationToken CombineWith(this CancellationToken original, params CancellationToken[] others) { Requires.NotNull(others, nameof(others)); if (original.IsCancellationRequested) { return(new CombinedCancellationToken(original)); } int cancelableTokensCount = original.CanBeCanceled ? 1 : 0; foreach (var other in others) { if (other.IsCancellationRequested) { return(new CombinedCancellationToken(other)); } if (other.CanBeCanceled) { cancelableTokensCount++; } } switch (cancelableTokensCount) { case 0: return(new CombinedCancellationToken(CancellationToken.None)); case 1: if (original.CanBeCanceled) { return(new CombinedCancellationToken(original)); } foreach (var other in others) { if (other.CanBeCanceled) { return(new CombinedCancellationToken(other)); } } throw Assumes.NotReachable(); case 2: CancellationToken first = CancellationToken.None; CancellationToken second = CancellationToken.None; if (original.CanBeCanceled) { first = original; } foreach (var other in others) { if (other.CanBeCanceled) { if (first.CanBeCanceled) { second = other; } else { first = other; } } } Assumes.True(first.CanBeCanceled && second.CanBeCanceled); // Call the overload that takes two CancellationTokens explicitly to avoid an array allocation. return(new CombinedCancellationToken(CancellationTokenSource.CreateLinkedTokenSource(first, second))); default: // This is the most expensive path to take since it involves allocating memory and requiring disposal. // Before this point we've checked every condition that would allow us to avoid it. var cancelableTokens = new CancellationToken[cancelableTokensCount]; int i = 0; foreach (var other in others) { if (other.CanBeCanceled) { cancelableTokens[i++] = other; } } return(new CombinedCancellationToken(CancellationTokenSource.CreateLinkedTokenSource(cancelableTokens))); } }
private void EnqueueProjectEvaluation(IComparable version, IProjectChangeDiff evaluationDifference) { Assumes.False(_projectEvaluations.Count > 0 && version.IsEarlierThanOrEqualTo(_projectEvaluations.Peek().Version), "Attempted to push a project evaluation that regressed in version."); _projectEvaluations.Enqueue(new VersionedProjectChangeDiff(version, evaluationDifference)); }
private Producer BuildProducer(string url) { var reuseConnectionProperty = this.senderOptions.GetReuseConnection(); var reuseConnection = reuseConnectionProperty.HasValue && reuseConnectionProperty.Value; var source = new CancellationTokenSource(); var connection = this.connectionPool.Get(url, reuseConnection, source.Token); this.logger.Trace($"Using connection [{connection.Id}] at URL=[{url}] to resolve a producer"); using (var topologyBuilder = new TopologyBuilder(connection)) { var builder = new RouteResolverBuilder(this.bus.Endpoint, topologyBuilder, this.Configuration); var routeResolverBuilderFunc = this.Configuration.Options.GetRouteResolverBuilder(); Assumes.True( routeResolverBuilderFunc.HasValue, "RouteResolverBuilder must be set for [{0}]", this.Configuration.Label); var routeResolver = routeResolverBuilderFunc.Value(builder); var producer = new Producer( this.bus.Endpoint, connection, this.Configuration.Label, routeResolver, this.Configuration.Options.IsConfirmationRequired()); if (this.Configuration.RequiresCallback) { var callbackConfiguration = this.CreateCallbackReceiverConfiguration(url); var receiver = this.bus.RegisterReceiver(callbackConfiguration, true); this.logger.Trace( $"A sender of [{this.Configuration.Label}] requires a callback configuration; registering a receiver of [{callbackConfiguration.Label}] with connection string [{callbackConfiguration.Options.GetConnectionString()}]"); this.logger.Trace( $"A new callback receiver of [{callbackConfiguration.Label}] with connection string [{callbackConfiguration.Options.GetConnectionString()}] has been successfully registered, getting one of its listeners with URL=[{producer.BrokerUrl}]..."); var listener = receiver.GetListener(l => l.BrokerUrl == producer.BrokerUrl); if (listener == null) { throw new BusConfigurationException( $"Unable to find a suitable listener for receiver {receiver}"); } this.logger.Trace( $"A listener at URL=[{listener.BrokerUrl}] belonging to callback receiver of [{callbackConfiguration.Label}] acquired"); listener.StopOnChannelShutdown = true; producer.UseCallbackListener(listener); producer.StopOnChannelShutdown = true; producer.Stopped += (sender, args) => { this.OnProducerStopped(url, sender, args); }; this.logger.Trace( $"A producer of [{producer.Label}] at URL=[{producer.BrokerUrl}] has registered a callback listener successfully"); } return(producer); } }
/// <summary> /// Informs derived classes that configuration has changed /// </summary> internal void SetObjects(bool isClosing) { Assumes.NotNull(_threadHandling); _threadHandling.ExecuteSynchronously(() => OnSetObjects(isClosing)); }
protected override async Task <bool> TryHandleCommandAsync(IProjectTree node, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut) { if (!ShouldHandle(node)) { return(false); } if (await IsReadyToBuildAsync()) { // Build manager APIs require UI thread access. await _threadingService.SwitchToUIThread(); Assumes.NotNull(Project.Services.HostObject); // Save documents before build. var projectVsHierarchy = (IVsHierarchy)Project.Services.HostObject; ErrorHandler.ThrowOnFailure(_buildManager !.SaveDocumentsBeforeBuild(projectVsHierarchy, (uint)VSConstants.VSITEMID.Root, 0 /*docCookie*/)); // We need to make sure dependencies are built so they can go into the package ErrorHandler.ThrowOnFailure(_buildManager.CalculateProjectDependencies()); // Assembly our list of projects to build var projects = new List <IVsHierarchy> { projectVsHierarchy }; // First we find out how many dependent projects there are uint[] dependencyCounts = new uint[1]; ErrorHandler.ThrowOnFailure(_buildManager.GetProjectDependencies(projectVsHierarchy, 0, null, dependencyCounts)); if (dependencyCounts[0] > 0) { // Get all of the dependent projects, and add them to our list var projectsArray = new IVsHierarchy[dependencyCounts[0]]; ErrorHandler.ThrowOnFailure(_buildManager.GetProjectDependencies(projectVsHierarchy, dependencyCounts[0], projectsArray, dependencyCounts)); projects.AddRange(projectsArray); } // Turn off "GeneratePackageOnBuild" because otherwise the Pack target will not do a build, even if there is no built output _generatePackageOnBuildPropertyProvider.OverrideGeneratePackageOnBuild(false); uint dwFlags = (uint)(VSSOLNBUILDUPDATEFLAGS.SBF_SUPPRESS_SAVEBEFOREBUILD_QUERY | VSSOLNBUILDUPDATEFLAGS.SBF_OPERATION_BUILD); uint[] buildFlags = new uint[projects.Count]; // We tell the Solution Build Manager to Package our project, which will call the Pack target, which will build if necessary. // Any dependent projects will just do a normal build buildFlags[0] = VSConstants.VS_BUILDABLEPROJECTCFGOPTS_PACKAGE; ErrorHandler.ThrowOnFailure(_buildManager.StartUpdateSpecificProjectConfigurations(cProjs: (uint)projects.Count, rgpHier: projects.ToArray(), rgpcfg: null, rgdwCleanFlags: null, rgdwBuildFlags: buildFlags, rgdwDeployFlags: null, dwFlags: dwFlags, fSuppressUI: 0)); } return(true); }
internal ProjectLoggerBatch(IProjectLogger logger) { Assumes.NotNull(logger); _logger = logger; }
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var shell = (IVsShell) await GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true); var solution = (IVsSolution) await GetServiceAsync(typeof(SVsSolution)).ConfigureAwait(true); cancellationToken.ThrowIfCancellationRequested(); Assumes.Present(shell); Assumes.Present(solution); foreach (var editorFactory in CreateEditorFactories()) { RegisterEditorFactory(editorFactory); } RegisterLanguageService(typeof(TLanguageService), async ct => { await JoinableTaskFactory.SwitchToMainThreadAsync(ct); // Create the language service, tell it to set itself up, then store it in a field // so we can notify it that it's time to clean up. _languageService = CreateLanguageService(); _languageService.Setup(); return(_languageService.ComAggregate); }); // Okay, this is also a bit strange. We need to get our Interop dll into our process, // but we're in the GAC. Ask the base Roslyn Package to load, and it will take care of // it for us. // * NOTE * workspace should never be created before loading roslyn package since roslyn package // installs a service roslyn visual studio workspace requires shell.LoadPackage(Guids.RoslynPackageId, out var setupPackage); _miscellaneousFilesWorkspace = this.ComponentModel.GetService <MiscellaneousFilesWorkspace>(); if (_miscellaneousFilesWorkspace != null) { // make sure solution crawler start once everything has been setup. _miscellaneousFilesWorkspace.StartSolutionCrawler(); } RegisterMiscellaneousFilesWorkspaceInformation(_miscellaneousFilesWorkspace); this.Workspace = this.CreateWorkspace(); if (await IsInIdeModeAsync(this.Workspace, cancellationToken).ConfigureAwait(true)) { // make sure solution crawler start once everything has been setup. // this also should be started before any of workspace events start firing this.Workspace.StartSolutionCrawler(); // start remote host EnableRemoteHostClientService(); Workspace.AdviseSolutionEvents(solution); } // Ensure services that must be created on the UI thread have been. HACK_AbstractCreateServicesOnUiThread.CreateServicesOnUIThread(ComponentModel, RoslynLanguageName); LoadComponentsInUIContextOnceSolutionFullyLoaded(cancellationToken); }
public CompositionServiceShim(CompositionContainer innerContainer) { Assumes.NotNull(innerContainer); _innerContainer = innerContainer; }
public IPackageReferenceContextInfo?Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { if (reader.TryReadNil()) { return(null); } // stack overflow mitigation - see https://github.com/neuecc/MessagePack-CSharp/security/advisories/GHSA-7q36-4xx7-xcxf options.Security.DepthStep(ref reader); try { PackageIdentity?identity = null; NuGetFramework? framework = null; bool isUserInstalled = false; bool isAutoReferenced = false; bool isDevelopmentDependency = false; string? allowedVersions = null; int propertyCount = reader.ReadMapHeader(); for (int propertyIndex = 0; propertyIndex < propertyCount; propertyIndex++) { switch (reader.ReadString()) { case IdentityPropertyName: identity = PackageIdentityFormatter.Instance.Deserialize(ref reader, options); break; case FrameworkPropertyName: framework = NuGetFrameworkFormatter.Instance.Deserialize(ref reader, options); break; case IsUserInstalledPropertyName: isUserInstalled = reader.ReadBoolean(); break; case IsAutoReferencedPropertyName: isAutoReferenced = reader.ReadBoolean(); break; case IsDevelopmentDependencyPropertyName: isDevelopmentDependency = reader.ReadBoolean(); break; case AllowedVersionsPropertyName: if (!reader.TryReadNil()) // Advances beyond the current value if the current value is nil and returns true; otherwise leaves the reader's position unchanged and returns false. { allowedVersions = reader.ReadString(); } break; default: reader.Skip(); break; } } Assumes.NotNull(identity); Assumes.NotNull(framework); var packageReferenceContextInfo = new PackageReferenceContextInfo(identity, framework) { IsUserInstalled = isUserInstalled, IsAutoReferenced = isAutoReferenced, IsDevelopmentDependency = isDevelopmentDependency }; if (!string.IsNullOrWhiteSpace(allowedVersions) && VersionRange.TryParse(allowedVersions, out VersionRange versionRange)) { packageReferenceContextInfo.AllowedVersions = versionRange; } return(packageReferenceContextInfo); } finally { // stack overflow mitigation - see https://github.com/neuecc/MessagePack-CSharp/security/advisories/GHSA-7q36-4xx7-xcxf reader.Depth--; } }
public ReflectionComposablePartDefinition(IReflectionPartCreationInfo creationInfo) { Assumes.NotNull(creationInfo); this._creationInfo = creationInfo; }
/// <summary> /// Refreshes the <see cref="ComposablePartDefinition"/>s with the latest files in the directory that match /// the searchPattern. If any files have been added they will be added to the catalog and if any files were /// removed they will be removed from the catalog. For files that have been removed keep in mind that the /// assembly cannot be unloaded from the process so <see cref="ComposablePartDefinition"/>s for those files /// will simply be removed from the catalog. /// /// Possible exceptions that can be thrown are any that <see cref="Directory.GetFiles(string, string)"/> or /// <see cref="Assembly.Load(AssemblyName)"/> can throw. /// </summary> /// <exception cref="DirectoryNotFoundException"> /// The specified <paramref name="path"/> has been removed since object construction. /// </exception> public void Refresh() { this.ThrowIfDisposed(); Assumes.NotNull(this._loadedFiles); List <Tuple <string, AssemblyCatalog> > catalogsToAdd; List <Tuple <string, AssemblyCatalog> > catalogsToRemove; ComposablePartDefinition[] addedDefinitions; ComposablePartDefinition[] removedDefinitions; object changeReferenceObject; string[] afterFiles; string[] beforeFiles; while (true) { afterFiles = this.GetFiles(); using (new ReadLock(this._thisLock)) { changeReferenceObject = this._loadedFiles; beforeFiles = this._loadedFiles.ToArray(); } this.DiffChanges(beforeFiles, afterFiles, out catalogsToAdd, out catalogsToRemove); // Don't go any further if there's no work to do if (catalogsToAdd.Count == 0 && catalogsToRemove.Count == 0) { return; } // Notify listeners to give them a preview before completeting the changes addedDefinitions = catalogsToAdd .SelectMany(cat => cat.Item2.Parts) .ToArray <ComposablePartDefinition>(); removedDefinitions = catalogsToRemove .SelectMany(cat => cat.Item2.Parts) .ToArray <ComposablePartDefinition>(); using (var atomicComposition = new AtomicComposition()) { var changingArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, atomicComposition); this.OnChanging(changingArgs); // if the change went through then write the catalog changes using (new WriteLock(this._thisLock)) { if (changeReferenceObject != this._loadedFiles) { // Someone updated the list while we were diffing so we need to try the diff again continue; } foreach (var catalogToAdd in catalogsToAdd) { this._assemblyCatalogs.Add(catalogToAdd.Item1, catalogToAdd.Item2); this._catalogCollection.Add(catalogToAdd.Item2); } foreach (var catalogToRemove in catalogsToRemove) { this._assemblyCatalogs.Remove(catalogToRemove.Item1); this._catalogCollection.Remove(catalogToRemove.Item2); } this._partsQuery = this._catalogCollection.AsQueryable().SelectMany(catalog => catalog.Parts); this._loadedFiles = afterFiles.ToReadOnlyCollection(); // Lastly complete any changes added to the atomicComposition during the change event atomicComposition.Complete(); // Break out of the while(true) break; } // WriteLock } // AtomicComposition } // while (true) var changedArgs = new ComposablePartCatalogChangeEventArgs(addedDefinitions, removedDefinitions, null); this.OnChanged(changedArgs); }
public async Task SearchAsync(IDependenciesTreeProjectSearchContext context) { // get latest snapshot ExportProvider exportProvider = context.UnconfiguredProject.Services.ExportProvider; Lazy <IAssetsFileDependenciesDataSource, IAppliesToMetadataView> dataSource = exportProvider .GetExports <IAssetsFileDependenciesDataSource, IAppliesToMetadataView>() .SingleOrDefault(export => export.Metadata.AppliesTo(context.UnconfiguredProject.Capabilities)); if (dataSource == null) { // dataSource will be null for shared projects, for example return; } IProjectDataSourceRegistry?dataSourceRegistry = context.UnconfiguredProject.Services.DataSourceRegistry; Assumes.Present(dataSourceRegistry); AssetsFileDependenciesSnapshot snapshot = (await dataSource.Value.GetLatestVersionAsync <AssetsFileDependenciesSnapshot>(dataSourceRegistry, cancellationToken: context.CancellationToken)).Value; if (context.UnconfiguredProject.Services.ExportProvider.GetExportedValue <IActiveConfigurationGroupService>() is not IActiveConfigurationGroupService3 activeConfigurationGroupService) { return; } IConfigurationGroup <ConfiguredProject> configuredProjects = await activeConfigurationGroupService.GetActiveLoadedConfiguredProjectGroupAsync(); foreach ((_, AssetsFileTarget target) in snapshot.DataByTarget) { ConfiguredProject?configuredProject = await FindConfiguredProjectAsync(target.TargetFrameworkMoniker); if (configuredProject == null) { continue; } IDependenciesTreeConfiguredProjectSearchContext?targetContext = await context.ForConfiguredProjectAsync(configuredProject); if (targetContext == null) { continue; } foreach ((_, AssetsFileTargetLibrary library) in target.LibraryByName) { if (context.CancellationToken.IsCancellationRequested) { // Search was cancelled return; } if (targetContext.IsMatch(library.Name)) { targetContext.SubmitResult(CreateLibraryItem(library)); } SearchAssemblies(library, library.CompileTimeAssemblies, PackageAssemblyGroupType.CompileTime); SearchAssemblies(library, library.FrameworkAssemblies, PackageAssemblyGroupType.Framework); SearchContentFiles(library); SearchBuildFiles(library, library.BuildFiles, PackageBuildFileGroupType.Build); SearchBuildFiles(library, library.BuildMultiTargetingFiles, PackageBuildFileGroupType.BuildMultiTargeting); } SearchLogMessages(); continue; async Task <ConfiguredProject?> FindConfiguredProjectAsync(string tfm) { foreach (ConfiguredProject configuredProject in configuredProjects) { if (configuredProject.Services.ProjectSubscription == null) { continue; } IProjectSubscriptionUpdate subscriptionUpdate = (await configuredProject.Services.ProjectSubscription.ProjectRuleSource.GetLatestVersionAsync(configuredProject, cancellationToken: context.CancellationToken)).Value; if (subscriptionUpdate.CurrentState.TryGetValue(NuGetRestoreRule.SchemaName, out IProjectRuleSnapshot nuGetRestoreSnapshot) && nuGetRestoreSnapshot.Properties.TryGetValue(NuGetRestoreRule.NuGetTargetMonikerProperty, out string nuGetTargetMoniker) && StringComparer.OrdinalIgnoreCase.Equals(nuGetTargetMoniker, tfm)) { // Assets file 'target' string matches the configured project's NuGetTargetMoniker property value return(configuredProject); } if (subscriptionUpdate.CurrentState.TryGetValue(ConfigurationGeneralRule.SchemaName, out IProjectRuleSnapshot configurationGeneralSnapshot)) { if (configurationGeneralSnapshot.Properties.TryGetValue(ConfigurationGeneralRule.TargetFrameworkMonikerProperty, out string targetFrameworkMoniker) && StringComparer.OrdinalIgnoreCase.Equals(targetFrameworkMoniker, tfm)) { // Assets file 'target' string matches the configured project's TargetFrameworkMoniker property value return(configuredProject); } if (configurationGeneralSnapshot.Properties.TryGetValue(ConfigurationGeneralRule.TargetFrameworkProperty, out string targetFramework) && StringComparer.OrdinalIgnoreCase.Equals(targetFramework, tfm)) { // Assets file 'target' string matches the configured project's TargetFramework property value return(configuredProject); } } } // No project found return(null); } void SearchAssemblies(AssetsFileTargetLibrary library, ImmutableArray <string> assemblies, PackageAssemblyGroupType groupType) { foreach (string assembly in assemblies) { if (targetContext.IsMatch(Path.GetFileName(assembly))) { targetContext.SubmitResult(new PackageAssemblyItem(target, library, assembly, groupType)); } } } void SearchContentFiles(AssetsFileTargetLibrary library) { foreach (AssetsFileTargetLibraryContentFile contentFile in library.ContentFiles) { if (targetContext.IsMatch(contentFile.Path)) { targetContext.SubmitResult(new PackageContentFileItem(target, library, contentFile, _fileIconProvider)); } } } void SearchBuildFiles(AssetsFileTargetLibrary library, ImmutableArray <string> buildFiles, PackageBuildFileGroupType groupType) { foreach (string buildFile in buildFiles) { if (targetContext.IsMatch(Path.GetFileName(buildFile))) { targetContext.SubmitResult(new PackageBuildFileItem(target, library, buildFile, groupType, _fileOpener)); } } } IRelatableItem CreateLibraryItem(AssetsFileTargetLibrary library) { return(library.Type switch { AssetsFileLibraryType.Package => new PackageReferenceItem(target, library), AssetsFileLibraryType.Project => new ProjectReferenceItem(target, library), _ => throw Assumes.NotReachable() }); } void SearchLogMessages() { foreach (AssetsFileLogMessage log in target.Logs) { if (targetContext.IsMatch(log.Message)) { targetContext.SubmitResult(CreateLogItem(log)); } } DiagnosticItem?CreateLogItem(AssetsFileLogMessage log) { if (target.LibraryByName.TryGetValue(log.LibraryName, out AssetsFileTargetLibrary? library)) { return(new DiagnosticItem(target, library, log)); } return(null); } } }
public NetCorePackageReferenceProjectProvider(IProjectSystemCache projectSystemCache) { Assumes.Present(projectSystemCache); _projectSystemCache = projectSystemCache; }
protected override async Task <IEnumerable <IProjectItem> > GetUnresolvedReferencesAsync(ConfiguredProjectServices services) { Assumes.Present(services.PackageReferences); return((await services.PackageReferences.GetUnresolvedReferencesAsync()).Cast <IProjectItem>()); }
public bool TryCreateNuGetProject( IVsProjectAdapter vsProject, ProjectProviderContext context, bool forceProjectType, out NuGetProject result) { Assumes.Present(vsProject); Assumes.Present(context); ThreadHelper.ThrowIfNotOnUIThread(); result = null; // The project must be an IVsHierarchy. var hierarchy = vsProject.VsHierarchy; if (hierarchy == null) { return(false); } // Check if the project is not CPS capable or if it is CPS capable then it does not have TargetFramework(s), if so then return false if (!hierarchy.IsCapabilityMatch("CPS")) { return(false); } var buildProperties = vsProject.BuildProperties; // read MSBuild property RestoreProjectStyle, TargetFramework, and TargetFrameworks var restoreProjectStyle = buildProperties.GetPropertyValue(ProjectBuildProperties.RestoreProjectStyle); var targetFramework = buildProperties.GetPropertyValue(ProjectBuildProperties.TargetFramework); var targetFrameworks = buildProperties.GetPropertyValue(ProjectBuildProperties.TargetFrameworks); // check for RestoreProjectStyle property is set and if not set to PackageReference then return false if (!(string.IsNullOrEmpty(restoreProjectStyle) || restoreProjectStyle.Equals(PackageReference, StringComparison.OrdinalIgnoreCase))) { return(false); } // check whether TargetFramework or TargetFrameworks property is set, else return false else if (string.IsNullOrEmpty(targetFramework) && string.IsNullOrEmpty(targetFrameworks)) { return(false); } // Lazy load the CPS enabled JoinableTaskFactory for the UI. NuGetUIThreadHelper.SetJoinableTaskFactoryFromService(ProjectServiceAccessor.Value as IProjectServiceAccessor); var projectNames = vsProject.ProjectNames; var fullProjectPath = vsProject.FullProjectPath; var unconfiguredProject = GetUnconfiguredProject(vsProject.Project); result = new NetCorePackageReferenceProject( vsProject.ProjectName, vsProject.CustomUniqueName, fullProjectPath, _projectSystemCache, vsProject, unconfiguredProject, vsProject.ProjectId); return(true); }
protected override IDisposable LinkExternalInput(ITargetBlock <IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> > targetBlock) { Assumes.Present(_configuredProject.Services.ProjectSubscription); bool attemptedStateRestore = false; // Initial state is empty. We will evolve this reference over time, updating it iteratively // on each new data update. UpToDateCheckImplicitConfiguredInput state = UpToDateCheckImplicitConfiguredInput.Empty; IPropagatorBlock <IProjectVersionedValue <UpdateValues>, IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> > transformBlock = DataflowBlockSlim.CreateTransformBlock <IProjectVersionedValue <UpdateValues>, IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> >(TransformAsync); IProjectValueDataSource <IProjectSubscriptionUpdate> source1 = _configuredProject.Services.ProjectSubscription.JointRuleSource; IProjectValueDataSource <IProjectSubscriptionUpdate> source2 = _configuredProject.Services.ProjectSubscription.SourceItemsRuleSource; IProjectValueDataSource <IProjectSnapshot> source3 = _configuredProject.Services.ProjectSubscription.ProjectSource; IProjectItemSchemaService source4 = _projectItemSchemaService; IProjectValueDataSource <IProjectCatalogSnapshot> source5 = _configuredProject.Services.ProjectSubscription.ProjectCatalogSource; return(new DisposableBag { // Sync-link various sources to our transform block ProjectDataSources.SyncLinkTo( source1.SourceBlock.SyncLinkOptions(DataflowOption.WithRuleNames(ProjectPropertiesSchemas)), source2.SourceBlock.SyncLinkOptions(), source3.SourceBlock.SyncLinkOptions(), source4.SourceBlock.SyncLinkOptions(), source5.SourceBlock.SyncLinkOptions(), target: transformBlock, linkOptions: DataflowOption.PropagateCompletion, CancellationToken.None), // Link the transform block to our target block transformBlock.LinkTo(targetBlock, DataflowOption.PropagateCompletion), JoinUpstreamDataSources(source1, source2, source3, source4, source5) }); async Task <IProjectVersionedValue <UpToDateCheckImplicitConfiguredInput> > TransformAsync(IProjectVersionedValue <UpdateValues> e) { if (!attemptedStateRestore) { attemptedStateRestore = true; if (_persistentState is not null) { // Restoring state requires the UI thread. We must use JTF.RunAsync here to ensure the UI // thread is shared between related work and prevent deadlocks. (int ItemHash, DateTime InputsChangedAtUtc)? restoredState = await JoinableFactory.RunAsync(() => _persistentState.RestoreStateAsync(_configuredProject.UnconfiguredProject.FullPath, _configuredProject.ProjectConfiguration.Dimensions)); if (restoredState is not null) { state = state.WithRestoredState(restoredState.Value.ItemHash, restoredState.Value.InputsChangedAtUtc); } } } int? priorItemHash = state.ItemHash; DateTime priorLastItemsChangedAtUtc = state.LastItemsChangedAtUtc; var snapshot = e.Value.Item3 as IProjectSnapshot2; Assumes.NotNull(snapshot); state = state.Update( jointRuleUpdate: e.Value.Item1, sourceItemsUpdate: e.Value.Item2, projectSnapshot: snapshot, projectItemSchema: e.Value.Item4, projectCatalogSnapshot: e.Value.Item5); if (state.ItemHash is not null && _persistentState is not null && (priorItemHash != state.ItemHash || priorLastItemsChangedAtUtc != state.LastItemsChangedAtUtc)) { _persistentState.StoreState(_configuredProject.UnconfiguredProject.FullPath, _configuredProject.ProjectConfiguration.Dimensions, state.ItemHash.Value, state.LastItemsChangedAtUtc); } return(new ProjectVersionedValue <UpToDateCheckImplicitConfiguredInput>(state, e.DataSourceVersions)); } }
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); }