private static void LocateMSBuild() { // Attempt to set the version of MSBuild. var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray(); var instance = visualStudioInstances.Length == 1 // If there is only one instance of MSBuild on this machine, set that as the one to use. ? visualStudioInstances[0] // Handle selecting the version of MSBuild you want to use. : SelectVisualStudioInstance(visualStudioInstances); Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects."); // NOTE: Be sure to register an instance with the MSBuildLocator // before calling MSBuildWorkspace.Create() // otherwise, MSBuildWorkspace won't MEF compose. MSBuildLocator.RegisterInstance(instance); System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += (assemblyLoadContext, assemblyName) => { var path = Path.Combine(instance.MSBuildPath, assemblyName.Name + ".dll"); if (File.Exists(path)) { return(assemblyLoadContext.LoadFromAssemblyPath(path)); } return(null); }; }
public Windows(Context context) : base(context) { string[] pathext = Environment.GetEnvironmentVariable("PATHEXT")?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (pathext == null || pathext.Length == 0) { executableExtensions = new List <string> { ".exe", ".cmd", ".bat" }; } else { executableExtensions = new List <string> (); foreach (string ext in pathext) { executableExtensions.Add(ext.ToLowerInvariant()); } } vsInstance = MSBuildLocator.QueryLatest(); Log.DebugLine($"Visual Studio detected in {vsInstance.VisualStudioRootPath}"); Log.DebugLine($"MSBuild detected at {vsInstance.MSBuildPath}"); OSVersionInfo osinfo = OSVersionInfo.GetOSVersionInfo(); Flavor = osinfo.Name; Name = osinfo.FullName; Architecture = Is64Bit ? "x86" : "x86_64"; // Not good enough! (ARM) Release = $"{osinfo.Major}.{osinfo.Minor}.{osinfo.Build}"; }
public static async Task Main(string[] args) { if (!MSBuildLocator.IsRegistered) { MSBuildLocator.RegisterInstance(MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(vs => vs.Version).FirstOrDefault() ?? throw new InvalidOperationException("Visual studio could not be found. Please install visual studio build tools.")); } ProjectPath = args.ElementAt(1); DirectoryInfo projDir = new DirectoryInfo(Path.GetDirectoryName(ProjectPath)); while (projDir.Parent != null) { SolutionPaths = SolutionPaths.Union(Directory.EnumerateFiles(projDir.FullName, "*.sln")).ToArray(); _bitConfigFilePath = Path.Combine(projDir.FullName, BitConfigFileName); if (File.Exists(_bitConfigFilePath)) { break; } projDir = projDir.Parent; } BeingCompiledProjectName = Path.GetFileNameWithoutExtension(ProjectPath); InitPropjects(); await GenerateCodes(); }
/// <summary> /// Determine the TFM to use based on what is installed on the users machine /// </summary> public static string FindHighestInstalledTargetFramework(bool usePreviewSDK) { // Finds SDK path string?sdkPath = null; try { sdkPath = Path.GetFullPath(Path.Combine(MSBuildLocator.QueryVisualStudioInstances().Single().VisualStudioRootPath, "..", "..")); } catch (Exception) { Console.WriteLine("Unable to find the .NET SDK on this machine, manually pass '-tfm'"); throw; } try { // Find templates path var templatesPath = Path.Combine(sdkPath, "templates"); // Find highest SDK path (should include previews?) var largestVersion = NuGetVersion.Parse("0.0.0.0"); var templatePath = string.Empty; foreach (var templateDirectory in Directory.EnumerateDirectories(templatesPath)) { if (NuGetVersion.TryParse(Path.GetFileName(templateDirectory), out var templatesVersion) && templatesVersion > largestVersion) { if (usePreviewSDK) { largestVersion = templatesVersion; templatePath = Path.GetFullPath(templateDirectory); } else if (!templatesVersion.IsPrerelease) { largestVersion = templatesVersion; templatePath = Path.GetFullPath(templateDirectory); } } } // upzip the common project templates into memory var templateNugetPackagePath = Directory.EnumerateFiles(templatePath, "microsoft.dotnet.common.projecttemplates.*.nupkg", SearchOption.TopDirectoryOnly).Single(); using var templateNugetPackageFile = File.OpenRead(templateNugetPackagePath); using var templateNugetPackage = new ZipArchive(templateNugetPackageFile, ZipArchiveMode.Read); var templatesJsonFile = templateNugetPackage.Entries .Where(x => x.Name.Equals("template.json", StringComparison.OrdinalIgnoreCase) && x.FullName.Contains("ClassLibrary-CSharp", StringComparison.OrdinalIgnoreCase)).Single(); using var templatesJson = templatesJsonFile.Open(); // read the template.json file to see what the tfm is called var doc = JsonDocument.ParseAsync(templatesJson).GetAwaiter().GetResult(); return(doc.RootElement.GetProperty("baselines").GetProperty("app").GetProperty("defaultOverrides").GetProperty("Framework").GetString()); } catch (Exception) { return("netcoreapp3.1"); } }
public MSBuildLocatorFixture() { if (!MSBuildLocator.IsRegistered) { MSBuildLocator.RegisterDefaults(); } }
public Program(IConsole console, string workingDirectory) { // We can register the MSBuild that is bundled with the SDK to perform MSBuild things. dotnet-watch is in // a nested folder of the SDK's root, we'll back up to it. // AppContext.BaseDirectory = $sdkRoot\$sdkVersion\DotnetTools\dotnet-watch\$version\tools\net6.0\any\ // MSBuild.dll is located at $sdkRoot\$sdkVersion\MSBuild.dll var sdkRootDirectory = Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", ".."); #if DEBUG // In the usual case, use the SDK that contains the dotnet-watch. However during local testing, it's // much more common to run dotnet-watch from a different SDK. Use the ambient SDK in that case. MSBuildLocator.RegisterDefaults(); #else MSBuildLocator.RegisterMSBuildPath(sdkRootDirectory); #endif Ensure.NotNull(console, nameof(console)); Ensure.NotNullOrEmpty(workingDirectory, nameof(workingDirectory)); _console = console; _workingDirectory = workingDirectory; _cts = new CancellationTokenSource(); console.CancelKeyPress += OnCancelKeyPress; _reporter = CreateReporter(verbose: true, quiet: false, console: _console); // Register listeners that load Roslyn-related assemblies from the `Rosyln/bincore` directory. RegisterAssemblyResolutionEvents(sdkRootDirectory); }
static Solution() { if (MSBuildLocator.CanRegister) { MSBuildLocator.RegisterDefaults(); } }
/// <summary> /// Sets up the appdomain. Idempotent and thread-safe, though if different /// msBuildHintPaths are passed into multiple calls, the first one to get /// the internal lock wins. /// </summary> /// <param name="msBuildHintPath"> /// When not null, this path is used to load MSBuild Microsoft.Build.* assemblies if /// they have not already been loaded into the appdomain. When null, the fallback /// is to look for an installed copy of Visual Studio on Windows. /// </param> public static void Setup(string msBuildHintPath) { if (_alreadyExecuted) { return; } lock (_lock) { if (_alreadyExecuted) { return; } if (MSBuildLocator.CanRegister) { if (!string.IsNullOrEmpty(msBuildHintPath) && Directory.Exists(msBuildHintPath)) { MSBuildLocator.RegisterMSBuildPath(msBuildHintPath); } else { MSBuildLocator.RegisterDefaults(); } } _alreadyExecuted = true; } }
private static void Main(string[] args) { string projectToLoad = (args.Length == 0) ? null : args[0]; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Bring forward user preferences after a version update if (!Settings.Default.SettingsUpgraded) { Settings.Default.Upgrade(); Settings.Default.SettingsUpgraded = true; Settings.Default.Save(); } try { MSBuildLocator.RegisterDefaults(); } catch (Exception ex) { MessageBox.Show("Unable to register MSBuild defaults: " + ex.Message + "\r\n\r\nYou probably " + "need to install the Microsoft Build Tools for Visual Studio 2017 or later.", Constants.AppName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } Application.Run(new MainForm(projectToLoad)); }
private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { MSBuildLocator.RegisterDefaults(); this.flowGraphConverter = new FlowToMsaglGraphConverter(); this.csharpGraphConverter = new CSharpBuildToMsaglGraphConverter(); this.heapGraphConverter = new HeapToMsaglGraphConverter(); this.aglGraphViewer = new GraphViewer() { LayoutEditingEnabled = false }; this.aglGraphViewer.BindToPanel(this.graphViewerPanel); this.aglGraphViewer.MouseDown += this.AglGraphViewer_MouseDown; this.aglHeapViewer = new GraphViewer() { LayoutEditingEnabled = false }; this.aglHeapViewer.BindToPanel(this.heapViewerPanel); // Symbolic CFGs this.sampleGraphProvider = new TestFlowGraphProvider(typeof(SampleFlowGraphGenerator)); this.graphSelectionCombo.ItemsSource = this.sampleGraphProvider.GeneratedMethodLocations; this.graphSelectionCombo.SelectedIndex = 0; // C# CFGs built from the syntax trees of the sample methods var args = Environment.GetCommandLineArgs(); if (args.Length >= 2 && File.Exists(args[1])) { string file = args[1]; string suffix = System.IO.Path.GetExtension(file); if (suffix == ".cs") { this.csharpWorkspace = SampleCSharpWorkspaceProvider.CreateWorkspaceFromSingleFile(file); } else if (suffix == ".csproj") { this.csharpWorkspace = MSBuildWorkspace.Create(); var project = await((MSBuildWorkspace)this.csharpWorkspace).OpenProjectAsync(file); } } if (this.csharpWorkspace == null) { this.csharpMethodTab.IsEnabled = false; } else { this.foundPathsView.ItemsSource = this.foundPaths; this.cliModelManager = new TypeModelManager(); this.csharpGraphDepth = GraphDepth.Statement; this.documentSelectionCombo.ItemsSource = this.csharpWorkspace.CurrentSolution.Projects .SelectMany(project => project.Documents) .ToArray(); } }
private void OpenMenuItemCommandMethod() { try { OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "Harmony Core CodeGen JSON File (*.json)|*.json|All files (*.*)|*.*", FileName = "Harmony.Core.CodeGen.json", }; if (openFileDialog.ShowDialog() == true) { StatusBarTextBlockText = "Loading..."; // Create Solution _solutionDir = Path.GetDirectoryName(openFileDialog.FileName); // Calling Register methods will subscribe to AssemblyResolve event. After this we can // safely call code that use MSBuild types (in the Builder class). if (!MSBuildLocator.IsRegistered) { MSBuildLocator.RegisterMSBuildPath(MSBuildLocator.QueryVisualStudioInstances().ToList().FirstOrDefault().MSBuildPath); } _solution = Solution.LoadSolution(openFileDialog.FileName, _solutionDir); if (_solution != null) { StrongReferenceMessenger.Default.Send(_solution); InstructionalTabTextBlockText = "Select a tab to continue."; // Determine visibility of tabs bool?hasOdata = _solution.ExtendedStructures?.Any(k => k.EnabledGenerators.Contains("ODataGenerator")); bool?hasModels = _solution.ExtendedStructures?.Any(k => k.EnabledGenerators.Contains("ModelGenerator")); bool?hasTraditionalBridge = _solution.ExtendedStructures?.Any(k => k.EnabledGenerators.Contains("TraditionalBridgeGenerator")); SettingsTabVisibility = Visibility.Visible; ODataTabVisibility = hasOdata == true && hasModels == true ? Visibility.Visible : Visibility.Collapsed; StructureTabVisibility = hasOdata == true && hasModels == true ? Visibility.Visible : Visibility.Collapsed; InterfacesTabVisibility = hasTraditionalBridge == true ? Visibility.Visible : Visibility.Collapsed; TraditionalBridgeTabVisibillity = hasTraditionalBridge == true ? Visibility.Visible : Visibility.Collapsed; SaveMenuItemIsEnabled = true; CloseMenuItemIsEnabled = true; RegenerateFilesMenuItemIsEnabled = false; StatusBarTextBlockText = "Loaded successfully"; } else { MessageBox.Show($"Could not load the solution associated with this JSON file.{Environment.NewLine}{Environment.NewLine}Double check the paths inside the JSON file and try again. In addition, the JSON file must be placed at the root of the HarmonyCore solution.", Resources.Title, MessageBoxButton.OK, MessageBoxImage.Error); } } } catch (Exception e) { MessageBox.Show(e.ToString(), e.GetType().ToString(), MessageBoxButton.OK, MessageBoxImage.Error); throw; } }
private static void RegisterMSBuild() { MSBuildLocator.RegisterInstance(MSBuildLocator.QueryVisualStudioInstances( new VisualStudioInstanceQueryOptions() { DiscoveryTypes = DiscoveryType.DotNetSdk }).SingleOrDefault()); }
static void Main(string[] args) { var vsVersion = MSBuildLocator.QueryVisualStudioInstances().First(i => i.Version.Major == 15); MSBuildLocator.RegisterInstance(vsVersion); // Call method that will now resolve msbuild tools Stuff(); }
public ProjectDependencyResolverTests() { if (MSBuildLocator.CanRegister) { var instances = MSBuildLocator.QueryVisualStudioInstances().ToList(); MSBuildLocator.RegisterMSBuildPath(instances.First().MSBuildPath); } }
/// <summary> /// Initializes a new instance of the <see cref="CSharpRoslynChangeHandler"/> class. /// </summary> /// <param name="logger">The logger.</param> public CSharpRoslynChangeHandler(ILogger logger) { _logger = logger; if (!MSBuildLocator.IsRegistered) { MSBuildLocator.RegisterDefaults(); } }
public static void TestSetup(TestContext testContext) { MSBuildLocator.RegisterDefaults(); var project = MSBuildWorkspace.Create().OpenProjectAsync(PetshopProjectFilePath).Result; codeModel = new CodeModel("Petshop"); new CSharpCodeModelBuilder(codeModel).BuildFrom(project); }
static async Task <Workspace> GetWorkspace(string solutionPath) { MSBuildLocator.RegisterDefaults(); var workspace = MSBuildWorkspace.Create(); await workspace.OpenSolutionAsync(solutionPath); return(workspace); }
private static void SetUpWorkspace() { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); MSBuildLocator.RegisterInstance(msBuildInstance); }
public PackagingRunner(string outputName, string msbuildTarget, string commandName) { MSBuildLocator.RegisterDefaults(); this.outputName = outputName; this.msbuildTarget = msbuildTarget; this.commandName = commandName; }
public static IServiceCollection AddDotNetCodeAnalysisServices( this IServiceCollection services) { MSBuildLocator.RegisterDefaults(); return(services.AddSingleton <ProjectLoader>() .AddSingleton <ProjectWorkspace>()); }
static void RegisterVisualStudio() { var vsInstance = GetVisualStudioInstances(); MSBuildLocator.RegisterInstance(vsInstance); //MSBuildLocator.RegisterDefaults(); }
static async Task TransformQuickStart(string[] args) { // var test = CreateTestCompilation(); var solutionPath = @"..\..\..\..\SyntaxTransformationQuickStart.sln"; MSBuildLocator.RegisterDefaults(); var msWorkspace = MSBuildWorkspace.Create(); var originalSolution = await msWorkspace.OpenSolutionAsync(solutionPath); var newSolution = originalSolution; foreach (ProjectId projectId in originalSolution.ProjectIds) { var newProject = newSolution.GetProject(projectId); foreach (var documentId in newProject.DocumentIds) { var document = newSolution.GetDocument(documentId); var tree = await document.GetSyntaxTreeAsync(); var model = await document.GetSemanticModelAsync(); var rewriter = new TypeInferenceRewriter(model); var newSource = rewriter.Visit(tree.GetRoot()); var newDocument = document.WithText(newSource.GetText()); newSolution = newDocument.Project.Solution; } } if (msWorkspace.TryApplyChanges(newSolution)) { Console.WriteLine("Solution updated."); } else { Console.WriteLine("Update failed!"); } //foreach (SyntaxTree sourceTree in test.SyntaxTrees) //{ // var model = test.GetSemanticModel(sourceTree); // var rewriter = new TypeInferenceRewriter(model); // var newSource = rewriter.Visit(sourceTree.GetRoot()); // if (newSource != sourceTree.GetRoot()) // { // File.WriteAllText(sourceTree.FilePath, newSource.ToFullString()); // } //} }
private static MSBuildWorkspace CreateWorkspaceUnhandled() { MSBuildLocator.RegisterDefaults(); return(MSBuildWorkspace.Create(new Dictionary <string, string>() { { "Configuration", "Debug" }, { "Platform", "AnyCPU" } })); }
static async Task Main(string[] args) { var targetAssembly = "StackExchange.Redis"; var totalCounters = new Counters(); var projectFile = @"C:\panos\repos\CodeAnalyzer\TestClassLibrary1\TestClassLibrary1.csproj"; MSBuildLocator.RegisterDefaults(); using (var workspace = MSBuildWorkspace.Create()) { var project = await workspace.OpenProjectAsync(projectFile); var compilation = await project.GetCompilationAsync(); foreach (var document in project.Documents) { Console.WriteLine($" Document: {document.Name}"); var syntaxTree = await document.GetSyntaxTreeAsync(); var model = compilation.GetSemanticModel(syntaxTree, true); var symbols = syntaxTree .GetRoot() .DescendantNodes() .OfType <IdentifierNameSyntax>() .Select(node => model.GetSymbolInfo(node).Symbol) .Where(s => s?.ContainingAssembly?.Name == targetAssembly); symbols .OfType <INamedTypeSymbol>() .Select(s => s.Name) .GroupBy(s => s) .ToList() .ForEach(g => totalCounters.AddTypeReferences(document.Name, g.Key, g.Count())); symbols .OfType <IFieldSymbol>() .Select(s => s.ContainingType.Name) .GroupBy(s => s) .ToList() .ForEach(g => totalCounters.AddFieldReferences(document.Name, g.Key, g.Count())); var unknownSymbols = symbols .Where(s => !(s is INamedTypeSymbol || s is IFieldSymbol || s is INamespaceSymbol)); unknownSymbols.ToList().ForEach(s => Console.WriteLine($" >>> Unknown: {s}, {s.GetType().Name}")); var documentCounters = totalCounters.GetCounters(document.Name); foreach (var counter in documentCounters) { Console.WriteLine($" * {counter.Name,-64} {counter.TypeRefs,3} {counter.FieldRefs,3}"); } } var counters = totalCounters.GetTotals(); Console.WriteLine(new string('-', 77)); Console.WriteLine($"{counters.Count()} entries found."); foreach (var counter in counters) { Console.WriteLine($" * {counter.Name,-64} {counter.TypeRefs,3} {counter.FieldRefs,3}"); } } }
public static async Task Main(string[] args) { MSBuildLocator.RegisterDefaults(); using var workspace = MSBuildWorkspace.Create(); var solutionPath = args[0]; Console.WriteLine($"Loading {solutionPath}..."); var originalSolution = await workspace.OpenSolutionAsync(solutionPath); // Enables dynamically-loaded analyzers to resolve their dependencies. Utils.ResolveAssembliesWithVersionRollforward(AppDomain.CurrentDomain); Console.WriteLine($"Searching for unnecessary suppressions..."); var diagnosticsComparer = new SolutionDiagnosticsComparer(originalSolution); var newSolution = originalSolution; foreach (var projectId in originalSolution.ProjectIds) { var project = newSolution.GetProject(projectId); if (project is null) { continue; } foreach (var documentId in project.DocumentIds) { var document = newSolution.GetDocument(documentId); if (document is null) { continue; } var newDocument = await SuppressionFixer.FixAllInDocumentAsync(document, diagnosticsComparer, removal => { var fileLineSpan = removal.RemovalLocation.GetLineSpan(); Console.WriteLine($"Removed '{removal.RemovedText}' from {fileLineSpan.Path} ({fileLineSpan.StartLinePosition})"); }, CancellationToken.None); newSolution = newDocument.Project.Solution; Utils.UpdateWorkspace(workspace, ref newSolution); } } if (newSolution == originalSolution) { Console.WriteLine("No suppressions found that the tool could remove."); } else { Utils.UpdateWorkspace(workspace, ref newSolution); } }
public Session() { // Register access to MSBuild assembly - required to load project dependencies // Must be called before we touch any type from referenced MSBuild assembly // either via reflection on runtime's TypeLoader. // see https://github.com/microsoft/MSBuildLocator/issues/64 if (!MSBuildLocator.IsRegistered) MSBuildLocator.RegisterDefaults(); }
public static async Task BeforeTestRun() { MSBuildLocator.RegisterDefaults(); Solution = Path.Combine(AppContext.BaseDirectory, @"..\..\..\Analyzable Projects\Cucumis.sln"); var msBuildWorkspace = MSBuildWorkspace.Create(); await msBuildWorkspace.OpenSolutionAsync(Solution); Workspace = msBuildWorkspace; }
static void Main(string[] args) { var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToList(); for (int i = 0; i < visualStudioInstances.Count; i++) { PrintDuplicateFiles(visualStudioInstances[i].VisualStudioRootPath); } }
void Init() { if (!MSBuildLocator.IsRegistered) { VisualStudioInstance vsInst = MSBuildLocator.RegisterDefaults(); } FileSys = new FileSystemUtility(); }
/// <summary> /// Setup the environment in order MSBuild to work /// </summary> public static void Setup() { #if NETCOREAPP2_0 SetupMsBuildPath(GetNetCoreMsBuildPath); #endif #if NET461 if (IsMono) { SetupMsBuildPath(() => { return(GetMonoMsBuildPath(monoDir => { Environment.SetEnvironmentVariable("MSBuildExtensionsPath", Path.Combine(monoDir, "xbuild")); })); }); var msbuildPath = Path.GetDirectoryName(Environment.GetEnvironmentVariable("MSBUILD_EXE_PATH")); foreach (var assembly in MsBuildAssemblies) { var src = Path.GetFullPath(Path.Combine(msbuildPath, $"{assembly}.dll")); var dest = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{assembly}.dll")); File.Copy(src, dest, true); } // On OSX mono 5.10.0 NuGet assemblies are not loaded, use a custom resolver that loads them. var sdkPath = Path.Combine(msbuildPath, "Sdks", "Microsoft.NET.Sdk", "tools", "net46"); AppDomain.CurrentDomain.AssemblyResolve += (_, eventArgs) => { var assemblyName = new AssemblyName(eventArgs.Name); if (!NuGetAssemblies.Contains(assemblyName.Name, StringComparer.OrdinalIgnoreCase)) { return(null); } var path = Path.Combine(sdkPath, $"{assemblyName.Name}.dll"); return(File.Exists(path) ? Assembly.LoadFile(Path.Combine(sdkPath, $"{assemblyName.Name}.dll")) : null); }; return; } var vsInstallDir = Environment.GetEnvironmentVariable("VSINSTALLDIR"); if (string.IsNullOrEmpty(vsInstallDir) || !Directory.Exists(vsInstallDir)) { var instance = MSBuildLocator.QueryVisualStudioInstances() .OrderByDescending(o => o.Version) .FirstOrDefault(); if (instance != null) { MSBuildLocator.RegisterInstance(instance); } else { throw new InvalidOperationException( "Visual Studio installation directory was not found. " + "Install Visual Studio or set the environment variable VSINSTALLDIR"); } Environment.SetEnvironmentVariable("VSINSTALLDIR", instance.VisualStudioRootPath); } #endif }