public async Task <bool> CanBeStartupProjectAsync(DebugLaunchOptions launchOptions, ILaunchProfile profile) { if (IsRunProjectCommand(profile)) { // If the profile uses the "Project" command, check that the project specifies // something we can run. ConfiguredProject?configuredProject = await GetConfiguredProjectForDebugAsync(); Assumes.NotNull(configuredProject); Assumes.Present(configuredProject.Services.ProjectPropertiesProvider); IProjectProperties properties = configuredProject.Services.ProjectPropertiesProvider.GetCommonProperties(); string?runCommand = await GetTargetCommandAsync(properties, validateSettings : true); if (string.IsNullOrWhiteSpace(runCommand)) { return(false); } } // Otherwise, the profile must be using the "Executable" command in which case it // can always be a start-up project. return(true); }
/// <summary> /// Gets the property values for the dimension. /// </summary> /// <param name="project">Unconfigured project.</param> /// <returns>Collection of values for the dimension.</returns> /// <remarks> /// From <see cref="IProjectConfigurationDimensionsProvider"/>. /// </remarks> private async Task <ImmutableArray <string> > GetOrderedPropertyValuesAsync(UnconfiguredProject project) { Requires.NotNull(project, nameof(project)); string?propertyValue = await GetPropertyValueAsync(project); if (string.IsNullOrEmpty(propertyValue)) { return(ImmutableArray <string> .Empty); } else { return(BuildUtilities.GetPropertyValues(propertyValue !).ToImmutableArray()); } async Task <string?> GetPropertyValueAsync(UnconfiguredProject project) { ConfiguredProject?configuredProject = await project.GetSuggestedConfiguredProjectAsync(); Assumes.NotNull(configuredProject); return(await ProjectAccessor.OpenProjectForReadAsync(configuredProject, evaluatedProject => { // Need evaluated property to get inherited properties defines in props or targets. return evaluatedProject.GetProperty(PropertyName)?.EvaluatedValue; })); } }
private async Task <string> ReplaceMSBuildTokensInStringAsync(string rawString) { MatchCollection matches = s_matchTokenRegex.Matches(rawString); if (matches.Count == 0) { return(rawString); } ConfiguredProject?configuredProject = await ActiveDebugFrameworkService.GetConfiguredProjectForActiveFrameworkAsync(); Assumes.NotNull(configuredProject); return(await ProjectAccessor.OpenProjectForReadAsync(configuredProject, project => { string expandedString = rawString; // For each token we try to get a replacement value. foreach (Match match in matches) { // Resolve with msbuild. It will return the empty string if not found expandedString = expandedString.Replace(match.Value, project.ExpandString(match.Value)); } return expandedString; })); }
private static BuildMacroInfo CreateInstance(ConfiguredProject?configuredProject = null) { configuredProject ??= ConfiguredProjectFactory.Create(); var threadingService = IProjectThreadingServiceFactory.Create(); return(new BuildMacroInfo(ActiveConfiguredProjectFactory.ImplementValue(() => configuredProject), threadingService)); }
public void Fork(Func <Task> asyncAction, JoinableTaskFactory?factory = null, UnconfiguredProject?project = null, ConfiguredProject?configuredProject = null, ErrorReportSettings?watsonReportSettings = null, ProjectFaultSeverity faultSeverity = ProjectFaultSeverity.Recoverable, ForkOptions options = ForkOptions.Default) { JoinableTaskFactory.Run(asyncAction); }
public static UnconfiguredProject Create(object?hostObject = null, string?filePath = null, IProjectConfigurationsService?projectConfigurationsService = null, ConfiguredProject?configuredProject = null, Encoding?projectEncoding = null, IProjectAsynchronousTasksService?projectAsynchronousTasksService = null, IProjectCapabilitiesScope?scope = null, UnconfiguredProjectServices?unconfiguredProjectServices = null) { var service = IProjectServiceFactory.Create(); if (unconfiguredProjectServices == null) { var unconfiguredProjectServicesMock = new Mock <UnconfiguredProjectServices>(); unconfiguredProjectServicesMock.SetupGet <object?>(u => u.FaultHandler) .Returns(IProjectFaultHandlerServiceFactory.Create()); unconfiguredProjectServicesMock.SetupGet <object?>(u => u.HostObject) .Returns(hostObject); unconfiguredProjectServicesMock.SetupGet <IProjectConfigurationsService?>(u => u.ProjectConfigurationsService) .Returns(projectConfigurationsService); var activeConfiguredProjectProvider = IActiveConfiguredProjectProviderFactory.Create(getActiveConfiguredProject: () => configuredProject); unconfiguredProjectServicesMock.Setup(u => u.ActiveConfiguredProjectProvider) .Returns(activeConfiguredProjectProvider); unconfiguredProjectServicesMock.Setup(u => u.ProjectAsynchronousTasks) .Returns(projectAsynchronousTasksService !); unconfiguredProjectServices = unconfiguredProjectServicesMock.Object; } var project = CreateDefault(); project.Setup(u => u.ProjectService) .Returns(service); project.Setup(u => u.Services) .Returns(unconfiguredProjectServices); project.SetupGet <string?>(u => u.FullPath) .Returns(filePath); project.Setup(u => u.Capabilities) .Returns(scope !); project.Setup(u => u.GetSuggestedConfiguredProjectAsync()).ReturnsAsync(configuredProject); if (projectEncoding != null) { project.Setup(u => u.GetFileEncodingAsync()).ReturnsAsync(projectEncoding); } return(project.Object); }
private static async Task <CompatibilityLevel> GetProjectCompatibilityAsync(UnconfiguredProject project, VersionCompatibilityData compatData, bool isPreviewSDKInUse) { if (project.Capabilities.AppliesTo($"{ProjectCapability.DotNet} & {ProjectCapability.PackageReferences}")) { Assumes.Present(project.Services.ActiveConfiguredProjectProvider); ConfiguredProject?activeConfiguredProject = project.Services.ActiveConfiguredProjectProvider.ActiveConfiguredProject; Assumes.NotNull(activeConfiguredProject); Assumes.Present(activeConfiguredProject.Services.ProjectPropertiesProvider); IProjectProperties properties = activeConfiguredProject.Services.ProjectPropertiesProvider.GetCommonProperties(); string tfm = await properties.GetEvaluatedPropertyValueAsync("TargetFrameworkMoniker"); if (!string.IsNullOrEmpty(tfm)) { var fw = new FrameworkName(tfm); if (fw.Identifier.Equals(".NETCoreApp", StringComparisons.FrameworkIdentifiers)) { return(GetCompatibilityLevelFromVersion(fw.Version, compatData, isPreviewSDKInUse)); } else if (fw.Identifier.Equals(".NETFramework", StringComparisons.FrameworkIdentifiers)) { // The interesting case here is Asp.Net Core on full framework Assumes.Present(activeConfiguredProject.Services.PackageReferences); IImmutableSet <IUnresolvedPackageReference> pkgReferences = await activeConfiguredProject.Services.PackageReferences.GetUnresolvedReferencesAsync(); // Look through the package references foreach (IUnresolvedPackageReference pkgRef in pkgReferences) { if (string.Equals(pkgRef.EvaluatedInclude, "Microsoft.AspNetCore.All", StringComparisons.ItemNames) || string.Equals(pkgRef.EvaluatedInclude, "Microsoft.AspNetCore", StringComparisons.ItemNames)) { string verString = await pkgRef.Metadata.GetEvaluatedPropertyValueAsync("Version"); if (!string.IsNullOrWhiteSpace(verString)) { // This is a semantic version string. We only care about the non-semantic version part int index = verString.IndexOfAny(Delimiter.PlusAndMinus); if (index != -1) { verString = verString.Substring(0, index); } if (Version.TryParse(verString, out Version aspnetVersion)) { return(GetCompatibilityLevelFromVersion(aspnetVersion, compatData, isPreviewSDKInUse)); } } } } } } } return(CompatibilityLevel.Recommended); }
/// <summary> /// Gets the property values for the dimension. /// </summary> /// <param name="project">Unconfigured project.</param> /// <returns>Collection of values for the dimension.</returns> /// <remarks> /// From <see cref="IProjectConfigurationDimensionsProvider"/>. /// </remarks> private async Task <ImmutableArray <string> > GetOrderedPropertyValuesAsync(UnconfiguredProject project) { Requires.NotNull(project, nameof(project)); ConfiguredProject?configuredProject = await project.GetSuggestedConfiguredProjectAsync(); Assumes.NotNull(configuredProject); // Need evaluated property to get inherited properties defined in props or targets. return(await ProjectAccessor.OpenProjectForReadAsync(configuredProject, GetOrderedPropertyValues)); }
private static ConfiguredProjectImplicitActivationTracking CreateInstance(ConfiguredProject?project, IProjectAsynchronousTasksService?tasksService, out ProjectValueDataSource <IConfigurationGroup <ProjectConfiguration> > source) { project ??= ConfiguredProjectFactory.Create(); var services = IProjectCommonServicesFactory.CreateWithDefaultThreadingPolicy(); source = ProjectValueDataSourceFactory.Create <IConfigurationGroup <ProjectConfiguration> >(services); var activeConfigurationGroupService = IActiveConfigurationGroupServiceFactory.Implement(source); tasksService ??= IProjectAsynchronousTasksServiceFactory.Create(); return(new ConfiguredProjectImplicitActivationTracking(project, activeConfigurationGroupService, tasksService)); }
/// <summary> /// Modifies the project when there's a configuration change. /// </summary> /// <param name="args">Information about the configuration dimension value change.</param> /// <returns>A task for the async operation.</returns> public Task OnDimensionValueChangedAsync(ProjectConfigurationDimensionValueChangedEventArgs args) { if (StringComparers.ConfigurationDimensionNames.Equals(args.DimensionName, DimensionName)) { if (args.Stage == ChangeEventStage.Before) { switch (args.Change) { case ConfigurationDimensionChange.Add: return(UpdateUnderLockAsync(args.Project, (msbuildProject, evaluatedPropertyValue) => BuildUtilities.AppendPropertyValue(msbuildProject, evaluatedPropertyValue, PropertyName, args.DimensionValue))); case ConfigurationDimensionChange.Delete: return(UpdateUnderLockAsync(args.Project, (msbuildProject, evaluatedPropertyValue) => BuildUtilities.RemovePropertyValue(msbuildProject, evaluatedPropertyValue, PropertyName, args.DimensionValue))); case ConfigurationDimensionChange.Rename: // Need to wait until the core rename changes happen before renaming the property. break; } } else if (args.Stage == ChangeEventStage.After) { // Only change that needs to be handled here is renaming configurations which needs to happen after all // of the core changes to rename existing conditions have executed. if (args.Change == ConfigurationDimensionChange.Rename) { return(UpdateUnderLockAsync(args.Project, (msbuildProject, evaluatedPropertyValue) => BuildUtilities.RenamePropertyValue(msbuildProject, evaluatedPropertyValue, PropertyName, args.OldDimensionValue, args.DimensionValue))); } } } return(Task.CompletedTask); async Task UpdateUnderLockAsync(UnconfiguredProject project, Action <ProjectRootElement, string> action) { ConfiguredProject?configuredProject = await project.GetSuggestedConfiguredProjectAsync(); Assumes.NotNull(configuredProject); await ProjectAccessor.OpenProjectForUpgradeableReadAsync(configuredProject, evaluatedProject => { string evaluatedPropertyValue = evaluatedProject.GetPropertyValue(PropertyName); return(ProjectAccessor.OpenProjectXmlForWriteAsync(project, msbuildProject => { action(msbuildProject, evaluatedPropertyValue); })); }); } }
public async Task HintingAsync(IProjectChangeHint hint) { // This will only be called once even if you are adding multiple files from say, e.g. add existing item dialog // However we check to see if we captured the previous includes for sanity to ensure it only gets set once. if (CanMove() && _previousIncludes.IsEmpty) { ConfiguredProject?configuredProject = hint.UnconfiguredProject.Services.ActiveConfiguredProjectProvider.ActiveConfiguredProject; Assumes.NotNull(configuredProject); _previousIncludes = await OrderingHelper.GetAllEvaluatedIncludes(configuredProject, _accessor); _isHinting = true; } }
internal AbstractMoveCommand CreateAbstractInstance( IPhysicalProjectTree?projectTree = null, Shell.SVsServiceProvider?serviceProvider = null, ConfiguredProject?configuredProject = null, IProjectAccessor?accessor = null) { projectTree ??= IPhysicalProjectTreeFactory.Create(); serviceProvider ??= SVsServiceProviderFactory.Create(); configuredProject ??= ConfiguredProjectFactory.Create(); accessor ??= IProjectAccessorFactory.Create(); return(CreateInstance(projectTree, serviceProvider, configuredProject, accessor)); }
private PackageRestoreProgressTrackerInstance CreateInstance(ConfiguredProject?project = null, IDataProgressTrackerService?dataProgressTrackerService = null, IPackageRestoreService?packageRestoreService = null, IProjectSubscriptionService?projectSubscriptionService = null) { project ??= ConfiguredProjectFactory.Create(); dataProgressTrackerService ??= IDataProgressTrackerServiceFactory.Create(); packageRestoreService ??= IPackageRestoreServiceFactory.Create(); projectSubscriptionService ??= IProjectSubscriptionServiceFactory.Create(); return(new PackageRestoreProgressTrackerInstance( project, dataProgressTrackerService, packageRestoreService, projectSubscriptionService)); }
public async Task HintedAsync(IImmutableDictionary <Guid, IImmutableSet <IProjectChangeHint> > hints) { if (CanMove() && !_previousIncludes.IsEmpty && hints.TryGetValue(ProjectChangeFileSystemEntityHint.AddedFile, out IImmutableSet <IProjectChangeHint> addedFileHints)) { IProjectChangeHint hint = addedFileHints.First(); ConfiguredProject? configuredProject = hint.UnconfiguredProject.Services.ActiveConfiguredProjectProvider.ActiveConfiguredProject; Assumes.NotNull(configuredProject); await OrderingHelper.Move(configuredProject, _accessor, _previousIncludes, _target !, _action); } // Reset everything because we are done. // We need to make sure these are all reset so we can listen for changes again. Reset(); }
public static UnconfiguredProject Create(object?hostObject = null, string?fullPath = null, IProjectConfigurationsService?projectConfigurationsService = null, ConfiguredProject?configuredProject = null, IEnumerable <ConfiguredProject>?configuredProjects = null, Encoding?projectEncoding = null, IProjectAsynchronousTasksService?projectAsynchronousTasksService = null, IProjectCapabilitiesScope?scope = null, UnconfiguredProjectServices?unconfiguredProjectServices = null) { if (configuredProject is not null && configuredProjects is null) { configuredProjects = new[] { configuredProject }; }
/// <summary> /// Executes the specified delegate in a safe fire-and-forget manner, prevent the project from /// closing until it has completed. /// </summary> /// <param name="threadingService"> /// The <see cref="IProjectThreadingService"/> that handles the fork. /// </param> /// <param name="asyncAction"> /// The async delegate to invoke. It is invoked asynchronously with respect to the caller. /// </param> /// <param name="configuredProject"> /// The configured project which the delegate operates on, if applicable. Can be <see langword="null"/>. /// </param> /// <param name="faultSeverity"> /// Suggests to the user how severe the fault is if the delegate throws. /// </param> /// <param name="options"> /// Influences the environment in which the delegate is executed. /// </param> public static void RunAndForget( this IProjectThreadingService threadingService, Func <Task> asyncAction, ConfiguredProject?configuredProject, ProjectFaultSeverity faultSeverity = ProjectFaultSeverity.Recoverable, ForkOptions options = ForkOptions.Default) { Requires.NotNull(threadingService, nameof(threadingService)); // If you do not pass in a project it is not legal to ask the threading service to cancel this operation on project unloading if (configuredProject is null) { options &= ~ForkOptions.CancelOnUnload; } threadingService.Fork(asyncAction, factory: null, configuredProject: configuredProject, watsonReportSettings: s_defaultReportSettings, faultSeverity: faultSeverity, options: options); }
private static ConsoleDebugTargetsProvider CreateInstance( ConfiguredProject?configuredProject = null, IDebugTokenReplacer?tokenReplacer = null, IFileSystem?fileSystem = null, IEnvironmentHelper?environment = null, IActiveDebugFrameworkServices?activeDebugFramework = null, ProjectProperties?properties = null, IProjectThreadingService?threadingService = null, IVsDebugger10?debugger = null) { environment ??= Mock.Of <IEnvironmentHelper>(); tokenReplacer ??= IDebugTokenReplacerFactory.Create(); activeDebugFramework ??= IActiveDebugFrameworkServicesFactory.ImplementGetConfiguredProjectForActiveFrameworkAsync(configuredProject); threadingService ??= IProjectThreadingServiceFactory.Create(); debugger ??= IVsDebugger10Factory.ImplementIsIntegratedConsoleEnabled(enabled: false); return(new ConsoleDebugTargetsProvider(configuredProject, tokenReplacer, fileSystem, environment, activeDebugFramework, properties, threadingService, IVsUIServiceFactory.Create <SVsShellDebugger, IVsDebugger10>(debugger))); }
protected override void Initialize() { _activeConfiguredProjectProvider.Changed += OnActiveConfigurationChanged; ConfiguredProject?configuredProject = _activeConfiguredProjectProvider.ActiveConfiguredProject; if (configuredProject == null) { _threadingService.ExecuteSynchronously(async() => { configuredProject = await _project.GetSuggestedConfiguredProjectAsync(); }); } Assumes.NotNull(configuredProject); SetValueForConfiguration(configuredProject); }
public override async Task <string?> OnSetPropertyValueAsync(string propertyName, string unevaluatedPropertyValue, IProjectProperties defaultProperties, IReadOnlyDictionary <string, string>?dimensionalConditions = null) { ConfiguredProject?configuredProject = await _project.GetSuggestedConfiguredProjectAsync(); IPropertyPagesCatalogProvider?catalogProvider = configuredProject?.Services.PropertyPagesCatalog; if (catalogProvider == null) { return(null); } IPropertyPagesCatalog catalog = await catalogProvider.GetCatalogAsync(PropertyPageContexts.Project); Rule?rule = catalog.GetSchema(unevaluatedPropertyValue); if (rule == null) { return(null); } if (rule.Metadata.TryGetValue("CommandName", out object pageCommandNameObj) && pageCommandNameObj is string pageCommandName) { _projectThreadingService.RunAndForget(async() => { // Infinite timeout means this will not actually be null. ILaunchSettings?launchSettings = await _launchSettingsProvider.WaitForFirstSnapshot(Timeout.Infinite); Assumes.NotNull(launchSettings); IWritableLaunchSettings writableLaunchSettings = launchSettings.ToWritableLaunchSettings(); IWritableLaunchProfile?activeProfile = writableLaunchSettings.ActiveProfile; if (activeProfile != null) { activeProfile.CommandName = pageCommandName; await _launchSettingsProvider.UpdateAndSaveSettingsAsync(writableLaunchSettings.ToLaunchSettings()); } }, options: ForkOptions.HideLocks, unconfiguredProject: _project); } return(null); }
private async Task <string?> GetSubTypeAsync(string documentMoniker) { IProjectItemTree?item = await FindCompileItemByMonikerAsync(documentMoniker); if (item == null) { return(null); } ConfiguredProject?project = await _project.GetSuggestedConfiguredProjectAsync(); IRule?browseObject = GetBrowseObjectProperties(project !, item); if (browseObject == null) { return(null); } return(await browseObject.GetPropertyValueAsync(Compile.SubTypeProperty)); }
private static WorkspaceProjectContextHostInstance CreateInstance(ConfiguredProject?project = null, IProjectThreadingService?threadingService = null, IUnconfiguredProjectTasksService?tasksService = null, IProjectSubscriptionService?projectSubscriptionService = null, IActiveEditorContextTracker?activeWorkspaceProjectContextTracker = null, IWorkspaceProjectContextProvider?workspaceProjectContextProvider = null, IApplyChangesToWorkspaceContext?applyChangesToWorkspaceContext = null) { project ??= ConfiguredProjectFactory.Create(); threadingService ??= IProjectThreadingServiceFactory.Create(); tasksService ??= IUnconfiguredProjectTasksServiceFactory.Create(); projectSubscriptionService ??= IProjectSubscriptionServiceFactory.Create(); activeWorkspaceProjectContextTracker ??= IActiveEditorContextTrackerFactory.Create(); workspaceProjectContextProvider ??= IWorkspaceProjectContextProviderFactory.ImplementCreateProjectContextAsync(IWorkspaceProjectContextAccessorFactory.Create()); applyChangesToWorkspaceContext ??= IApplyChangesToWorkspaceContextFactory.Create(); IDataProgressTrackerService dataProgressTrackerService = IDataProgressTrackerServiceFactory.Create(); return(new WorkspaceProjectContextHostInstance(project, threadingService, tasksService, projectSubscriptionService, workspaceProjectContextProvider, activeWorkspaceProjectContextTracker, ExportFactoryFactory.ImplementCreateValueWithAutoDispose(() => applyChangesToWorkspaceContext), dataProgressTrackerService)); }
public static UnconfiguredProject Create(object?hostObject = null, string?filePath = null, IProjectConfigurationsService?projectConfigurationsService = null, ConfiguredProject?configuredProject = null, Encoding?projectEncoding = null, IProjectCapabilitiesScope?scope = null) { var service = IProjectServiceFactory.Create(); var unconfiguredProjectServices = new Mock <UnconfiguredProjectServices>(); unconfiguredProjectServices.Setup(u => u.HostObject) .Returns(hostObject !); unconfiguredProjectServices.Setup(u => u.ProjectConfigurationsService) .Returns(projectConfigurationsService !); var activeConfiguredProjectProvider = IActiveConfiguredProjectProviderFactory.Create(getActiveConfiguredProject: () => configuredProject !); unconfiguredProjectServices.Setup(u => u.ActiveConfiguredProjectProvider) .Returns(activeConfiguredProjectProvider); var project = new Mock <UnconfiguredProject>(); project.Setup(u => u.ProjectService) .Returns(service); project.Setup(u => u.Services) .Returns(unconfiguredProjectServices.Object); project.SetupGet(u => u.FullPath) .Returns(filePath !); project.Setup(u => u.Capabilities) .Returns(scope !); project.Setup(u => u.GetSuggestedConfiguredProjectAsync()).ReturnsAsync(configuredProject); project.Setup(u => u.GetFileEncodingAsync()).ReturnsAsync(projectEncoding); return(project.Object); }
private PackageRestoreProgressTrackerInstance CreateInstance(ConfiguredProject?project = null, IDataProgressTrackerService?dataProgressTrackerService = null, IPackageRestoreDataSource?packageRestoreDataSource = null, IProjectSubscriptionService?projectSubscriptionService = null) { project ??= ConfiguredProjectFactory.Create(); dataProgressTrackerService ??= IDataProgressTrackerServiceFactory.Create(); packageRestoreDataSource ??= IPackageRestoreServiceFactory.Create(); projectSubscriptionService ??= IProjectSubscriptionServiceFactory.Create(); IProjectThreadingService threadingService = IProjectThreadingServiceFactory.Create(); IProjectFaultHandlerService projectFaultHandlerService = IProjectFaultHandlerServiceFactory.Create(); IConfiguredProjectPackageRestoreTelemetryService packageReferenceTelemetryService = IConfiguredProjectPackageRestoreTelemetryServiceFactory.Create(); return(new PackageRestoreProgressTrackerInstance( project, threadingService, projectFaultHandlerService, dataProgressTrackerService, packageRestoreDataSource, projectSubscriptionService, packageReferenceTelemetryService, packageRestoreProgressTrackerId: 0)); }
private static ApplyChangesToWorkspaceContext CreateInstance(ConfiguredProject?project = null, ICommandLineParserService?commandLineParser = null, IProjectLogger?logger = null, params IWorkspaceContextHandler[] handlers) { if (project == null) { var unconfiguredProject = UnconfiguredProjectFactory.ImplementFullPath(@"C:\Project\Project.csproj"); project = ConfiguredProjectFactory.ImplementUnconfiguredProject(unconfiguredProject); } commandLineParser ??= ICommandLineParserServiceFactory.Create(); logger ??= IProjectLoggerFactory.Create(); var factories = handlers.Select(h => ExportFactoryFactory.ImplementCreateValueWithAutoDispose(() => h)) .ToArray(); var applyChangesToWorkspaceContext = new ApplyChangesToWorkspaceContext(project, logger, factories); applyChangesToWorkspaceContext.CommandLineParsers.Add(commandLineParser); return(applyChangesToWorkspaceContext); }
private async Task <string> GetPropertyValueAsync() { // Infinite timeout means this will not actually be null. ILaunchSettings?launchSettings = await _launchSettingsProvider.WaitForFirstSnapshot(Timeout.Infinite); Assumes.NotNull(launchSettings); string?commandName = launchSettings.ActiveProfile?.CommandName; if (commandName == null) { return(string.Empty); } ConfiguredProject?configuredProject = await _project.GetSuggestedConfiguredProjectAsync(); IPropertyPagesCatalogProvider?catalogProvider = configuredProject?.Services.PropertyPagesCatalog; if (catalogProvider == null) { return(string.Empty); } IPropertyPagesCatalog catalog = await catalogProvider.GetCatalogAsync(PropertyPageContexts.Project); foreach (string schemaName in catalog.GetPropertyPagesSchemas()) { Rule?rule = catalog.GetSchema(schemaName); if (rule != null && string.Equals(rule.PageTemplate, "CommandNameBasedDebugger", StringComparison.OrdinalIgnoreCase) && rule.Metadata.TryGetValue("CommandName", out object pageCommandNameObj) && pageCommandNameObj is string pageCommandName && pageCommandName.Equals(commandName)) { return(schemaName); } } return(string.Empty); }
private static ProjectLaunchTargetsProvider CreateInstance( ConfiguredProject?configuredProject = null, IDebugTokenReplacer?tokenReplacer = null, IFileSystem?fileSystem = null, IEnvironmentHelper?environment = null, IActiveDebugFrameworkServices?activeDebugFramework = null, ProjectProperties?properties = null, IProjectThreadingService?threadingService = null, IVsDebugger10?debugger = null) { environment ??= Mock.Of <IEnvironmentHelper>(); tokenReplacer ??= IDebugTokenReplacerFactory.Create(); activeDebugFramework ??= IActiveDebugFrameworkServicesFactory.ImplementGetConfiguredProjectForActiveFrameworkAsync(configuredProject); threadingService ??= IProjectThreadingServiceFactory.Create(); debugger ??= IVsDebugger10Factory.ImplementIsIntegratedConsoleEnabled(enabled: false); IUnconfiguredProjectVsServices unconfiguredProjectVsServices = IUnconfiguredProjectVsServicesFactory.Implement(() => IVsHierarchyFactory.Create()); IRemoteDebuggerAuthenticationService remoteDebuggerAuthenticationService = Mock.Of <IRemoteDebuggerAuthenticationService>(); return(new ProjectLaunchTargetsProvider(unconfiguredProjectVsServices, configuredProject !, tokenReplacer, fileSystem !, environment, activeDebugFramework, properties !, threadingService, IVsUIServiceFactory.Create <SVsShellDebugger, IVsDebugger10>(debugger), remoteDebuggerAuthenticationService)); }
public static IUnconfiguredProjectCommonServices Create(UnconfiguredProject?project = null, IProjectThreadingService?threadingService = null, ConfiguredProject?configuredProject = null, ProjectProperties?projectProperties = null, IProjectAccessor?projectAccessor = null) { var mock = new Mock <IUnconfiguredProjectCommonServices>(); if (project != null) { mock.Setup(s => s.Project) .Returns(project); } if (threadingService != null) { mock.Setup(s => s.ThreadingService) .Returns(threadingService); } if (configuredProject != null) { mock.Setup(s => s.ActiveConfiguredProject) .Returns(configuredProject); } if (projectProperties != null) { mock.Setup(s => s.ActiveConfiguredProjectProperties) .Returns(projectProperties); } if (projectAccessor != null) { mock.Setup(s => s.ProjectAccessor) .Returns(projectAccessor); } return(mock.Object); }
public static IActiveDebugFrameworkServices ImplementGetConfiguredProjectForActiveFrameworkAsync(ConfiguredProject?project) { var service = new IActiveDebugFrameworkServicesMock(); service.ImplementGetConfiguredProjectForActiveFrameworkAsync(project); return(service.Object); }
/// <summary> /// This is called on F5 to return the list of debug targets. What we return depends on the type /// of project. /// </summary> private async Task <DebugLaunchSettings> GetConsoleTargetForProfile(ILaunchProfile resolvedProfile, DebugLaunchOptions launchOptions, bool validateSettings) { var settings = new DebugLaunchSettings(launchOptions); string?executable, arguments; string projectFolder = Path.GetDirectoryName(_project.UnconfiguredProject.FullPath); 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; } } // 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 workingDirectory; (executable, arguments, workingDirectory) = await GetRunnableProjectInformationAsync(configuredProject, validateSettings); if (!string.IsNullOrWhiteSpace(workingDirectory)) { defaultWorkingDir = workingDirectory; } if (!string.IsNullOrWhiteSpace(resolvedProfile.CommandLineArgs)) { arguments = arguments + " " + resolvedProfile.CommandLineArgs; } } else { executable = resolvedProfile.ExecutablePath; arguments = resolvedProfile.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); } if (settings.Environment.Count > 0) { settings.LaunchOptions |= DebugLaunchOptions.MergeEnvironment; } bool useCmdShell = false; if (await IsConsoleAppAsync()) { 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; } } } return(settings); }
private static ApplyChangesToWorkspaceContext CreateInitializedInstance(out IWorkspaceProjectContext context, ConfiguredProject?project = null, ICommandLineParserService?commandLineParser = null, IProjectLogger?logger = null, params IWorkspaceContextHandler[] handlers) { var applyChangesToWorkspace = CreateInstance(project, commandLineParser, logger, handlers); context = IWorkspaceProjectContextMockFactory.Create(); applyChangesToWorkspace.Initialize(context); return(applyChangesToWorkspace); }