/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex * */ namespace CustomBuildTool { /// /// Provides methods for discovering and managing installed Visual Studio instances using native setup configuration APIs. /// internal static class BuildVisualStudio { /// /// List of discovered Visual Studio instances on the system. /// private static readonly List VisualStudioInstanceList; /// /// The selected Visual Studio instance, typically the latest version with required dependencies. /// private static VisualStudioInstance VisualStudioInstance; /// /// Static constructor. Discovers all Visual Studio instances using the native setup configuration API and populates . /// static unsafe BuildVisualStudio() { VisualStudioInstanceList = new List(); if (NativeLibrary.TryLoad(GetLibraryPath(), out IntPtr baseAddress)) { if (NativeLibrary.TryGetExport(baseAddress, "GetSetupConfiguration", out IntPtr ExportAddressPtr)) { var GetSetupConfiguration_I = (delegate* unmanaged[Stdcall])ExportAddressPtr; IntPtr SetupConfigurationInterfacePtr; IntPtr SetupConfiguration2InterfacePtr; IntPtr EnumSetupInstancesInterfacePtr; IntPtr SetupInstancePtr; IntPtr SetupInstance2Ptr; uint instancesFetched; if (GetSetupConfiguration_I( &SetupConfigurationInterfacePtr, IntPtr.Zero ).Succeeded) { var setupInterface = *(ISetupConfigurationVTable**)SetupConfigurationInterfacePtr; if (setupInterface->QueryInterface( SetupConfigurationInterfacePtr, IID_ISetupConfiguration2, &SetupConfiguration2InterfacePtr ).Succeeded) { var setupConfiguration = *(ISetupConfiguration2VTable**)SetupConfiguration2InterfacePtr; if (setupConfiguration->EnumAllInstances( SetupConfiguration2InterfacePtr, &EnumSetupInstancesInterfacePtr ).Succeeded) { var enumSetupInstances = *(IEnumSetupInstancesVTable**)EnumSetupInstancesInterfacePtr; while (true) { if (enumSetupInstances->Next(EnumSetupInstancesInterfacePtr, 1, &SetupInstancePtr, &instancesFetched).Failed) break; if (instancesFetched == 0) break; var setupInstance = *(ISetupInstanceVTable**)SetupInstancePtr; if (setupInstance->QueryInterface( SetupInstancePtr, IID_ISetupInstance2, &SetupInstance2Ptr ).Succeeded) { var setupInstance2 = *(ISetupInstance2VTable**)SetupInstance2Ptr; VisualStudioInstanceList.Add(new VisualStudioInstance(setupInstance2, SetupInstance2Ptr)); setupInstance2->Release(SetupInstance2Ptr); } setupInstance->Release(SetupInstancePtr); } enumSetupInstances->Release(EnumSetupInstancesInterfacePtr); } setupConfiguration->Release(SetupConfiguration2InterfacePtr); } setupInterface->Release(SetupConfigurationInterfacePtr); } } NativeLibrary.Free(baseAddress); } // Environment Begin bool isEnterpriseWdk = IsEnterpriseWdk(); string environmentVersion = EnvironmentVersion(); if (Win32.GetEnvironmentVariable("VSINSTALLDIR", out string vsInstallDir) && Directory.Exists(vsInstallDir)) { VisualStudioInstanceList.Add(new VisualStudioInstance(isEnterpriseWdk ? "Enterprise WDK" : "Visual Studio (Environment)", vsInstallDir, environmentVersion)); } else if (Win32.GetEnvironmentVariable("VCINSTALLDIR", out string vcInstallDir)) { string vsPath = Path.GetFullPath(Path.Join([vcInstallDir, "..\\..\\"])); if (Directory.Exists(vsPath)) { VisualStudioInstanceList.Add(new VisualStudioInstance(isEnterpriseWdk ? "Enterprise WDK" : "Visual Studio (Environment)", vsPath, environmentVersion)); } } // Environment End VisualStudioInstanceList.Sort((p1, p2) => { if (Version.TryParse(p1.InstallationVersion, out Version version1) && Version.TryParse(p2.InstallationVersion, out Version version2)) { if (version1 < version2) return 1; else if (version1 > version2) return -1; return version1.CompareTo(version2); } return 1; }); } public static bool IsEnterpriseWdk() { if (Win32.GetEnvironmentVariable("EnterpriseWDK", out string enterpriseWdk)) { if (enterpriseWdk.Equals("true", StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } public static string EnvironmentVersion() { string environmentVersion = "17.0"; if (Win32.GetEnvironmentVariable("EWDKVisualStudioVersion", out string ewdkVisualStudioVersion) && !string.IsNullOrWhiteSpace(ewdkVisualStudioVersion)) { environmentVersion = ewdkVisualStudioVersion.Trim(); } else if (Win32.GetEnvironmentVariable("VisualStudioVersion", out string visualStudioVersion) && !string.IsNullOrWhiteSpace(visualStudioVersion)) { environmentVersion = visualStudioVersion.Trim(); } return environmentVersion; } /// /// Gets the preferred Visual Studio instance, typically the latest version with required dependencies. /// /// /// The selected or null if none are available. /// public static VisualStudioInstance GetVisualStudioInstance() { if (VisualStudioInstance == null && VisualStudioInstanceList != null) { foreach (VisualStudioInstance instance in VisualStudioInstanceList) { //if (instance.HasRequiredDependency) { VisualStudioInstance = instance; break; } //else //{ // Program.PrintColorMessage($"[WARN] {instance.DisplayName} does not have required the packages:\n{instance.MissingDependencyList}", ConsoleColor.Yellow); //} } } return VisualStudioInstance; } /// /// GUID for the ISetupConfiguration2 COM interface. /// private static readonly Guid IID_ISetupConfiguration2 = new Guid("26AAB78C-4A60-49D6-AF3B-3C35BC93365D"); /// /// GUID for the ISetupInstance2 COM interface. /// private static readonly Guid IID_ISetupInstance2 = new Guid("89143C9A-05AF-49B0-B717-72E218A2185C"); //private static readonly Guid IID_ISetupConfiguration = new Guid("42843719-DB4C-46C2-8E7C-64F1816EFD5B"); //private static readonly Guid IID_IEnumSetupInstances = new Guid("6380BCFF-41D3-4B2E-8B2E-BF8A6810C848"); //private static readonly Guid IID_ISetupInstance = new Guid("B41463C3-8866-43B5-BC33-2B0676F7F42E"); //private static readonly Guid IID_ISetupPackageReference = new Guid("DA8D8A16-B2B6-4487-A2F1-594CCCCD6BF5"); //private static readonly Guid IID_ISetupHelper = new Guid("42B21B78-6192-463E-87BF-D577838F1D5C"); private static string GetLibraryPath() { string path = null; if (Win32.GetEnvironmentVariable("ProgramData", out string programData)) { string directory = Environment.Is64BitProcess ? "x64" : "x86"; path = Path.Join([programData, @"\Microsoft\VisualStudio\Setup\", directory, @"\Microsoft.VisualStudio.Setup.Configuration.Native.dll"]); } //if (!File.Exists(path)) //{ // string directory = Environment.Is64BitProcess ? "x64" : "x86"; // path = Path.Join([programData, @"\Microsoft\VisualStudio\Setup\", directory, @"\Microsoft.VisualStudio.Setup.Configuration.NativeMethods.dll"]); //} return path; } internal static unsafe string BStrToStringAndFree(IntPtr Value) { if (Value == IntPtr.Zero) return null; try { uint byteLength = *(uint*)((byte*)Value - sizeof(uint)); if (byteLength == 0) return string.Empty; ReadOnlySpan valueSpan = new ReadOnlySpan((char*)Value, (int)(byteLength / sizeof(char))); return valueSpan.ToString(); } finally { Marshal.FreeBSTR(Value); } } /// /// Required workloads for Visual Studio. /// private static readonly FrozenSet RequiredWorkloads = new[] { "Microsoft.VisualStudio.Workload.NativeDesktop" }.ToFrozenSet(StringComparer.OrdinalIgnoreCase); /// /// Required components for Visual Studio. /// private static readonly FrozenSet RequiredComponents = new[] { "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "Microsoft.VisualStudio.Component.VC.Tools.ARM64", "Microsoft.VisualStudio.Component.Windows11SDK.26100", "Microsoft.VisualStudio.Component.Windows10SDK", "Component.Microsoft.Windows.DriverKit", "Microsoft.Component.MSBuild", "Microsoft.VisualStudio.Component.VC.ATL", "Microsoft.VisualStudio.Component.VC.ATLMFC", "Microsoft.VisualStudio.Component.VC.Redist.14.Latest", "Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre", "Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre", "Microsoft.VisualStudio.Component.VC.Runtimes.ARM64EC.Spectre", "Microsoft.VisualStudio.Component.NuGet", "Microsoft.VisualStudio.Component.Git" }.ToFrozenSet(StringComparer.OrdinalIgnoreCase); /// /// Recommended components for Visual Studio. /// private static readonly FrozenSet RecommendedComponents = new[] { "Microsoft.VisualStudio.Component.VC.CMake.Project", "Microsoft.VisualStudio.Component.VC.14.45.17.12.CLI.Support" }.ToFrozenSet(StringComparer.OrdinalIgnoreCase); /// /// Checks whether all required build dependencies are installed and available on the system. /// /// Specifies whether to suppress console output during the check. /// /// true if all dependencies are found; otherwise, false. /// public static bool CheckBuildDependencies(bool Quiet = false) { bool result = true; try { if (GetVisualStudioInstance() != null) { if (!Quiet) Program.PrintColorMessage($"\u2705 - {VisualStudioInstance.DisplayName} - {VisualStudioInstance.InstallationVersion}", ConsoleColor.Green); } else { result = false; if (!Quiet) Program.PrintColorMessage("\u274C - Visual Studio - Not found", ConsoleColor.Yellow); } if (Win32.IsGitInstalled()) { if (!Quiet) Program.PrintColorMessage("\u2705 - Git - Installed", ConsoleColor.Green); } else { result = false; if (!Quiet) Program.PrintColorMessage("\u274C - Git - Not found", ConsoleColor.Yellow); } string dotnet = Win32.GetDotNetPath(); if (!string.IsNullOrWhiteSpace(dotnet)) { string version = Win32.GetDotNetVersion(); if (!Quiet) Program.PrintColorMessage($"\u2705 - DotNET - {version.Trim()}", ConsoleColor.Green); } else { if (!Quiet) Program.PrintColorMessage("\u274C - DotNET - Not found", ConsoleColor.Yellow); } } catch { if (!Quiet) Program.PrintColorMessage("\u274C - DotNET - Not found", ConsoleColor.Yellow); } return result; } /// /// Installs required Visual Studio build dependencies and components for the current environment. /// /// The method downloads the Visual Studio Community installer if it is not already /// present, then installs required workloads and components. A restart may be required to complete /// installation. The method returns if the installer download or installation /// fails. /// Specifies whether to install only the minimal set of required components. If , /// recommended components are excluded; otherwise, all recommended components are installed. /// A task that represents the asynchronous operation. The task result is if the /// installation completes successfully; otherwise, . public static async Task InstallBuildDependencies(bool Minimal = false) { string installerPath = Path.Combine(Path.GetTempPath(), "vs_community.exe"); try { if (!File.Exists(installerPath)) { Program.PrintColorMessage("Downloading Visual Studio 2022 Community installer...", ConsoleColor.Cyan); using var client = BuildHttpClient.CreateHttpClient(); using var request = new HttpRequestMessage(HttpMethod.Get, "https://aka.ms/vs/17/release/vs_community.exe"); using var response = await BuildHttpClient.SendMessageResponse(client, request); if (response.IsSuccessStatusCode) { await using var fs = new FileStream(installerPath, FileMode.Create); await response.Content.CopyToAsync(fs); } } if (!File.Exists(installerPath)) { Program.PrintColorMessage("Failed to download Visual Studio installer.", ConsoleColor.Red); return false; } } catch (Exception ex) { Program.PrintColorMessage($"Failed to download Visual Studio installer: {ex}", ConsoleColor.Red); return false; } var args = new List { "--passive", "--wait", "--norestart" }; foreach (var w in RequiredWorkloads) { args.Add("--add"); args.Add(w); } foreach (var c in RequiredComponents) { args.Add("--add"); args.Add(c); } if (!Minimal) { foreach (var c in RecommendedComponents) { args.Add("--add"); args.Add(c); } } args.Add("--add"); args.Add("Microsoft.NetCore.Component.Runtime.10.0"); Program.PrintColorMessage($"Installing Visual Studio components... {string.Join(' ', args)}", ConsoleColor.Cyan); int exitCode = Win32.CreateProcess(installerPath, args, out _, false, false); if (exitCode == 0 || exitCode == 3010) { Program.PrintColorMessage("Visual Studio installation completed successfully.", ConsoleColor.Green); if (exitCode == 3010) Program.PrintColorMessage("A restart is required to complete installation.", ConsoleColor.Yellow); return true; } else { if (exitCode == 8006) { Program.PrintColorMessage("The Visual Studio installation failed because it attempted to install or modify workloads while Visual Studio (or related processes) are open.", ConsoleColor.Red); } else { Program.PrintColorMessage($"Visual Studio installation failed with exit code: {exitCode}", ConsoleColor.Red); } return false; } } /// /// Gets the latest Windows SDK BuildTools package version from NuGet. /// /// /// Latest stable version if available, otherwise latest version (including prerelease), or string.Empty on failure. /// public static string GetLatestWindowsSdkNuGetVersion() { return NugetMetadataClient.GetLatestVersion("Microsoft.Windows.SDK.CPP").GetAwaiter().GetResult(); //return NugetMetadataClient.GetLatestVersion("Microsoft.Windows.SDK.CPP.x64").GetAwaiter().GetResult(); //return NugetMetadataClient.GetLatestVersion("Microsoft.Windows.SDK.CPP.x64").GetAwaiter().GetResult(); } public static string GetLatestBuildToolsNuGetVersion() { return NugetMetadataClient.GetLatestVersion("Microsoft.Windows.SDK.BuildTools").GetAwaiter().GetResult(); } public static string GetLatestWindowsWdkNuGetVersion() { return NugetMetadataClient.GetLatestVersion("Microsoft.Windows.WDK.x64").GetAwaiter().GetResult(); } } /// /// Represents a single Visual Studio instance and its installed packages. /// internal unsafe class VisualStudioInstance : IComparable, IComparable { /// /// Gets the display name of the Visual Studio instance. /// public string DisplayName { get; } /// /// Gets the internal name of the Visual Studio instance. /// public string Name { get; } /// /// Gets the installation path of the Visual Studio instance. /// public string Path { get; } /// /// Gets the installation version string of the Visual Studio instance. /// public string InstallationVersion { get; } /// /// Gets the instance identifier of the Visual Studio instance. /// public string InstanceId { get; } /// /// Gets the state flags of the Visual Studio instance. /// public uint State { get; } /// /// Gets the list of installed packages for this Visual Studio instance. /// public List Packages { get; } /// /// Gets a value indicating whether the instance has ARM64 build tools components installed. /// public bool HasARM64BuildToolsComponents { get; } /// /// Initializes a new instance of the class. /// public VisualStudioInstance() { this.Packages = new List(); } /// /// Initializes a new instance of the class with manual parameters. /// /// Display name. /// Installation path. /// Installation version. public VisualStudioInstance(string Name, string Path, string Version) { this.Name = Name; this.DisplayName = Name; this.Path = Path; this.InstallationVersion = Version; this.Packages = new List(); this.HasARM64BuildToolsComponents = ProbeArm64BuildTools(Path); } /// /// Probes whether ARM64-targeting cl.exe is available beneath a manual/ESDK instance path. /// EWDK exposes the launched arch via the Platform env var; honor it directly to avoid a /// directory enumeration on every cold start. /// private static bool ProbeArm64BuildTools(string InstallPath) { if (BuildVisualStudio.IsEnterpriseWdk()) { if (Win32.GetEnvironmentVariable("Platform", out string platform) && platform.Equals("arm64", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } if (string.IsNullOrEmpty(InstallPath)) return false; string msvcRoot = System.IO.Path.Combine(InstallPath, @"VC\Tools\MSVC"); if (!Directory.Exists(msvcRoot)) return false; try { foreach (string clPath in Directory.EnumerateFiles(msvcRoot, "cl.exe", SearchOption.AllDirectories)) { if (clPath.Contains(@"\Hostarm64\arm64\", StringComparison.OrdinalIgnoreCase) || clPath.Contains(@"\Hostx64\arm64\", StringComparison.OrdinalIgnoreCase) || clPath.Contains(@"\Hostx86\arm64\", StringComparison.OrdinalIgnoreCase)) { return true; } } } catch { // ignored } return false; } /// /// Initializes a new instance of the class from a native setup instance pointer. /// /// Pointer to the native ISetupInstance2 vtable. /// Pointer to the native setup instance. public VisualStudioInstance(ISetupInstance2VTable* FromInstance, IntPtr SetupInstancePtr) { IntPtr NamePtr; IntPtr PathPtr; IntPtr VersionPtr; IntPtr DisplayNamePtr; Windows.Win32.System.Com.SAFEARRAY* SetupPackagesArrayPtr; IntPtr SetupPackagePtr; uint SetupPackageState; //if (FromInstance->GetInstanceId(SetupInstancePtr, out IntPtr InstancePtr) == NativeMethods.HRESULT_S_OK && InstancePtr != IntPtr.Zero) //{ // this.InstanceId = Marshal.PtrToStringBSTR(InstancePtr); //} if (FromInstance->GetInstallationName(SetupInstancePtr, &NamePtr).Succeeded && NamePtr != IntPtr.Zero) { this.Name = BuildVisualStudio.BStrToStringAndFree(NamePtr); } if (FromInstance->GetInstallationPath(SetupInstancePtr, &PathPtr).Succeeded && PathPtr != IntPtr.Zero) { this.Path = BuildVisualStudio.BStrToStringAndFree(PathPtr); } if (FromInstance->GetInstallationVersion(SetupInstancePtr, &VersionPtr).Succeeded && VersionPtr != IntPtr.Zero) { this.InstallationVersion = BuildVisualStudio.BStrToStringAndFree(VersionPtr); } if (FromInstance->GetDisplayName(SetupInstancePtr, 0, &DisplayNamePtr).Succeeded && DisplayNamePtr != IntPtr.Zero) { this.DisplayName = BuildVisualStudio.BStrToStringAndFree(DisplayNamePtr); } if (FromInstance->GetState(SetupInstancePtr, &SetupPackageState).Succeeded) { this.State = SetupPackageState; } this.Packages = new List(); if (FromInstance->GetPackages(SetupInstancePtr, &SetupPackagesArrayPtr).Succeeded) { try { if (PInvoke.SafeArrayGetLBound(SetupPackagesArrayPtr, 1, out var lbound).Succeeded && PInvoke.SafeArrayGetUBound(SetupPackagesArrayPtr, 1, out var ubound).Succeeded) { var count = ubound - lbound + 1; for (int i = 0; i < count; i++) { int index = lbound + i; if (PInvoke.SafeArrayGetElement( SetupPackagesArrayPtr, &index, &SetupPackagePtr ).Succeeded) { var package = *(ISetupPackageReferenceVTable**)SetupPackagePtr; this.Packages.Add(new VisualStudioPackage(package, SetupPackagePtr)); package->Release(SetupPackagePtr); } } } } finally { PInvoke.SafeArrayDestroy(SetupPackagesArrayPtr); } } // https://learn.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community var found = this.Packages.FindAll(p => p.Id.Equals("Microsoft.VisualStudio.Component.VC.Tools.ARM64", StringComparison.OrdinalIgnoreCase) || p.Id.Equals("Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre", StringComparison.OrdinalIgnoreCase)); this.HasARM64BuildToolsComponents = found.Count >= 2; } /// /// Gets the latest installed Windows SDK package for this Visual Studio instance. /// /// /// The representing the latest Windows SDK, or null if none found. /// private VisualStudioPackage GetLatestSdkPackage() { var found = this.Packages.FindAll(p => p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows11SDK", StringComparison.OrdinalIgnoreCase)); if (found.Count == 0) return null; found.Sort((p1, p2) => { if (Version.TryParse(p1.Version, out Version v1) && Version.TryParse(p2.Version, out Version v2)) return v1.CompareTo(v2); else return 1; }); return found[^1]; } //public string GetWindowsSdkVersion() //{ // List versions = new List(); // VisualStudioPackage package = GetLatestSdkPackage(); // // if (package == null) // return string.Empty; // // var found = this.Packages.FindAll(p => // { // return p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows10SDK", StringComparison.OrdinalIgnoreCase) || // p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows11SDK", StringComparison.OrdinalIgnoreCase); // }); // // foreach (var sdk in found) // { // foreach (var name in sdk.Id.AsSpan().Split('.')) // { // if (uint.TryParse(sdk.Id.AsSpan(name), out uint version)) // { // versions.Add(sdk.Id.AsSpan(name).ToString()); // break; // } // } // } // // versions.Sort((p1, p2) => // { // if (Version.TryParse(p1, out Version v1) && Version.TryParse(p2, out Version v2)) // return v1.CompareTo(v2); // else // return 1; // }); // // if (versions.Count > 0) // { // return versions[^1]; // } // else // { // return package.Id; // } //} // /// /// Gets the full version string of the latest installed Windows SDK package. /// /// /// The version string of the latest Windows SDK package, or string.Empty if none found. /// public string GetWindowsSdkFullVersion() { VisualStudioPackage package = GetLatestSdkPackage(); return package == null ? string.Empty : package.Version; } /// /// Gets the Enterprise WDK version from version.txt or Visual Studio metadata. /// /// /// The version string, or string.Empty if it cannot be determined. /// public string GetProductVersion() { try { if (BuildVisualStudio.IsEnterpriseWdk()) { // EWDK's version.txt sits at the extraction root, not the drive root. // Walk up from VSINSTALLDIR until version.txt is found. string dir = this.Path; while (!string.IsNullOrEmpty(dir)) { string versionFilePath = System.IO.Path.Combine(dir, "version.txt"); if (File.Exists(versionFilePath)) { string versionText = File.ReadAllText(versionFilePath).Trim(); if (!string.IsNullOrWhiteSpace(versionText)) { if (versionText.StartsWith("Version ", StringComparison.OrdinalIgnoreCase)) { versionText = versionText.Substring("Version ".Length); } return versionText; } } string parent = System.IO.Path.GetDirectoryName(dir); if (string.IsNullOrEmpty(parent) || parent.Equals(dir, StringComparison.OrdinalIgnoreCase)) break; dir = parent; } } string devenvPath = System.IO.Path.Combine(this.Path, "Common7\\IDE\\devenv.exe"); if (File.Exists(devenvPath)) { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(devenvPath); return versionInfo.ProductVersion ?? string.Empty; } string msbuildPath = System.IO.Path.Combine(this.Path, "MSBuild\\Current\\Bin\\amd64\\MSBuild.exe"); if (File.Exists(msbuildPath)) { FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(msbuildPath); return versionInfo.ProductVersion ?? string.Empty; } } catch { } return string.Empty; } //public bool HasRequiredDependency //{ // get // { // bool hasbuild = false; // bool hasruntimes = false; // bool haswindowssdk = false; // // hasbuild = this.Packages.Exists(p => p.Id.StartsWith("Microsoft.Component.MSBuild", StringComparison.OrdinalIgnoreCase)); // hasruntimes = this.Packages.Exists(p => p.Id.StartsWith("Microsoft.VisualStudio.Component.VC", StringComparison.OrdinalIgnoreCase)); // haswindowssdk = this.Packages.Exists(p => // { // return p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows10SDK", StringComparison.OrdinalIgnoreCase) || // p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows11SDK", StringComparison.OrdinalIgnoreCase); // }); // // return hasbuild && hasruntimes && haswindowssdk; // } //} // //public string MissingDependencyList //{ // get // { // string list = string.Empty; // // if (!this.Packages.Exists(p => p.Id.StartsWith("Microsoft.Component.MSBuild", StringComparison.OrdinalIgnoreCase))) // { // list += "MSBuild" + Environment.NewLine; // } // // if (!this.Packages.Exists(p => p.Id.StartsWith("Microsoft.VisualStudio.Component.VC", StringComparison.OrdinalIgnoreCase))) // { // list += "VC.14.Redist" + Environment.NewLine; // } // // if (!this.Packages.Exists(p => // { // return p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows10SDK", StringComparison.OrdinalIgnoreCase) || // p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows11SDK", StringComparison.OrdinalIgnoreCase); // })) // { // list += "Windows SDK" + Environment.NewLine; // } // // return list; // } //} /// /// Returns the internal name of the Visual Studio instance. /// /// The internal name. public override string ToString() { return this.Name; } /// /// Compares this instance to another object by name. /// /// The object to compare to. /// /// A value indicating the relative order of the instances. /// public int CompareTo(object Obj) { if (Obj == null) return 1; if (Obj is VisualStudioInstance instance) return string.Compare(this.Name, instance.Name, StringComparison.OrdinalIgnoreCase); else return 1; } /// /// Compares this instance to another by name. /// /// The instance to compare to. /// /// A value indicating the relative order of the instances. /// public int CompareTo(VisualStudioInstance Obj) { if (Obj == null) return 1; return string.Compare(this.Name, Obj.Name, StringComparison.OrdinalIgnoreCase); } } /// /// Represents a Visual Studio package/component installed in an instance. /// internal unsafe class VisualStudioPackage : IComparable, IComparable { /// /// Gets the package/component ID. /// public string Id { get; } /// /// Gets the version string of the package/component. /// public string Version { get; } /// /// Initializes a new instance of the class from a native package reference pointer. /// /// Pointer to the native ISetupPackageReference vtable. /// Pointer to the native package reference. public VisualStudioPackage(ISetupPackageReferenceVTable* FromInstance, IntPtr SetupInstancePtr) { IntPtr idPtr; IntPtr versionPtr; if (FromInstance->GetId(SetupInstancePtr, &idPtr).Succeeded && idPtr != IntPtr.Zero) { this.Id = BuildVisualStudio.BStrToStringAndFree(idPtr); } if (FromInstance->GetVersion(SetupInstancePtr, &versionPtr).Succeeded && versionPtr != IntPtr.Zero) { this.Version = BuildVisualStudio.BStrToStringAndFree(versionPtr); } } /// /// Returns the package/component ID. /// /// The package/component ID. public override string ToString() { return this.Id; } /// /// Compares this package to another object by ID. /// /// The object to compare to. /// /// A value indicating the relative order of the packages. /// public int CompareTo(object Obj) { if (Obj == null) return 1; if (Obj is VisualStudioPackage package) return string.Compare(this.Id, package.Id, StringComparison.OrdinalIgnoreCase); else return 1; } /// /// Compares this package to another by ID. /// /// The package to compare to. /// /// A value indicating the relative order of the packages. /// public int CompareTo(VisualStudioPackage obj) { if (obj == null) return 1; return string.Compare(this.Id, obj.Id, StringComparison.OrdinalIgnoreCase); } } [Flags] public enum InstanceState : uint { None = 0u, Local = 1u, Registered = 2u, NoRebootRequired = 4u, NoErrors = 8u, Complete = 4294967295u } [StructLayout(LayoutKind.Sequential)] internal readonly unsafe struct ISetupHelperVTable { public readonly delegate* unmanaged[Stdcall] QueryInterface; public readonly delegate* unmanaged[Stdcall] AddRef; public readonly delegate* unmanaged[Stdcall] Release; // ISetupHelper public readonly delegate* unmanaged[Stdcall] ParseVersion; public readonly delegate* unmanaged[Stdcall] ParseVersionRange; } [StructLayout(LayoutKind.Sequential)] internal readonly unsafe struct ISetupConfigurationVTable { public readonly delegate* unmanaged[Stdcall] QueryInterface; public readonly delegate* unmanaged[Stdcall] AddRef; public readonly delegate* unmanaged[Stdcall] Release; // STDMETHOD(EnumInstances)(_Out_ IEnumSetupInstances **ppEnumInstances) = 0; public readonly delegate* unmanaged[Stdcall] EnumInstances; // STDMETHOD(GetInstanceForCurrentProcess)(_Out_ ISetupInstance ** ppInstance) = 0; public readonly delegate* unmanaged[Stdcall] GetInstanceForCurrentProcess; // STDMETHOD(GetInstanceForPath)(_In_z_ LPCWSTR wzPath, _Out_ ISetupInstance **ppInstance) = 0; public readonly delegate* unmanaged[Stdcall] GetInstanceForPath; } [StructLayout(LayoutKind.Sequential)] internal readonly unsafe struct ISetupConfiguration2VTable { public readonly delegate* unmanaged[Stdcall] QueryInterface; public readonly delegate* unmanaged[Stdcall] AddRef; public readonly delegate* unmanaged[Stdcall] Release; // STDMETHOD(EnumAllInstances)(_Out_ IEnumSetupInstances **ppEnumInstances) = 0; public readonly delegate* unmanaged[Stdcall] EnumAllInstances; } [StructLayout(LayoutKind.Sequential)] internal readonly unsafe struct IEnumSetupInstancesVTable { public readonly delegate* unmanaged[Stdcall] QueryInterface; public readonly delegate* unmanaged[Stdcall] AddRef; public readonly delegate* unmanaged[Stdcall] Release; // STDMETHOD(Next)(_In_ ULONG celt, _Out_writes_to_(celt, *pceltFetched) ISetupInstance** rgelt, _Out_opt_ _Deref_out_range_(0, celt) ULONG* pceltFetched) = 0; public readonly delegate* unmanaged[Stdcall] Next; // STDMETHOD(Skip)(_In_ ULONG celt) = 0; public readonly delegate* unmanaged[Stdcall] Skip; // STDMETHOD(Reset)(void) = 0; public readonly delegate* unmanaged[Stdcall] Reset; // STDMETHOD(Clone)(_Deref_out_opt_ IEnumSetupInstances **ppenum) = 0; public readonly delegate* unmanaged[Stdcall] Clone; } [StructLayout(LayoutKind.Sequential)] internal readonly unsafe struct ISetupInstanceVTable { public readonly delegate* unmanaged[Stdcall] QueryInterface; public readonly delegate* unmanaged[Stdcall] AddRef; public readonly delegate* unmanaged[Stdcall] Release; // ISetupInstance // STDMETHOD(GetInstanceId)(_Out_ BSTR *pbstrInstanceId) = 0; public readonly delegate* unmanaged[Stdcall] GetInstanceId; // STDMETHOD(GetInstallDate)(_Out_ LPFILETIME pInstallDate) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallDate; // STDMETHOD(GetInstallationName)(_Out_ BSTR *pbstrInstallationName) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallationName; // STDMETHOD(GetInstallationPath)(_Out_ BSTR *pbstrInstallationPath) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallationPath; // STDMETHOD(GetInstallationVersion)(_Out_ BSTR *pbstrInstallationVersion) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallationVersion; // STDMETHOD(GetDisplayName)(_In_ LCID lcid, _Out_ BSTR *pbstrDisplayName) = 0; public readonly delegate* unmanaged[Stdcall] GetDisplayName; // STDMETHOD(GetDescription)(_In_ LCID lcid, _Out_ BSTR *pbstrDescription) = 0; public readonly delegate* unmanaged[Stdcall] GetDescription; // STDMETHOD(ResolvePath)(_In_opt_z_ LPCOLESTR pwszRelativePath, _Out_ BSTR* pbstrAbsolutePath) = 0; public readonly delegate* unmanaged[Stdcall] ResolvePath; } [StructLayout(LayoutKind.Sequential)] internal readonly unsafe struct ISetupInstance2VTable { public readonly delegate* unmanaged[Stdcall] QueryInterface; public readonly delegate* unmanaged[Stdcall] AddRef; public readonly delegate* unmanaged[Stdcall] Release; // ISetupInstance // STDMETHOD(GetInstanceId)(_Out_ BSTR *pbstrInstanceId) = 0; public readonly delegate* unmanaged[Stdcall] GetInstanceId; // STDMETHOD(GetInstallDate)(_Out_ LPFILETIME pInstallDate) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallDate; // STDMETHOD(GetInstallationName)(_Out_ BSTR *pbstrInstallationName) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallationName; // STDMETHOD(GetInstallationPath)(_Out_ BSTR *pbstrInstallationPath) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallationPath; // STDMETHOD(GetInstallationVersion)(_Out_ BSTR *pbstrInstallationVersion) = 0; public readonly delegate* unmanaged[Stdcall] GetInstallationVersion; // STDMETHOD(GetDisplayName)(_In_ LCID lcid, _Out_ BSTR *pbstrDisplayName) = 0; public readonly delegate* unmanaged[Stdcall] GetDisplayName; // STDMETHOD(GetDescription)(_In_ LCID lcid, _Out_ BSTR *pbstrDescription) = 0; public readonly delegate* unmanaged[Stdcall] GetDescription; // STDMETHOD(ResolvePath)(_In_opt_z_ LPCOLESTR pwszRelativePath, _Out_ BSTR* pbstrAbsolutePath) = 0; public readonly delegate* unmanaged[Stdcall] ResolvePath; // ISetupInstance2 // STDMETHOD(GetState)(_Out_ InstanceState *pState) = 0; public readonly delegate* unmanaged[Stdcall] GetState; // STDMETHOD(GetPackages)(_Out_ LPSAFEARRAY *ppsaPackages) = 0; public readonly delegate* unmanaged[Stdcall] GetPackages; // STDMETHOD(GetProduct)(_Outptr_result_maybenull_ ISetupPackageReference **ppPackage) = 0; public readonly delegate* unmanaged[Stdcall] GetProduct; // STDMETHOD(GetProductPath)(_Outptr_result_maybenull_ BSTR *pbstrProductPath) = 0; public readonly delegate* unmanaged[Stdcall] GetProductPath; // STDMETHOD(GetErrors)(_Outptr_result_maybenull_ ISetupErrorState** ppErrorState) = 0; public readonly delegate* unmanaged[Stdcall] GetErrors; // STDMETHOD(IsLaunchable)(_Out_ VARIANT_BOOL* pfIsLaunchable) = 0; public readonly delegate* unmanaged[Stdcall] IsLaunchable; // STDMETHOD(IsComplete)(_Out_ VARIANT_BOOL* pfIsComplete) = 0; public readonly delegate* unmanaged[Stdcall] IsComplete; // STDMETHOD(GetProperties)(_Outptr_result_maybenull_ ISetupPropertyStore** ppProperties) = 0; public readonly delegate* unmanaged[Stdcall] GetProperties; // STDMETHOD(GetEnginePath)(_Outptr_result_maybenull_ BSTR* pbstrEnginePath) = 0; public readonly delegate* unmanaged[Stdcall] GetEnginePath; } [StructLayout(LayoutKind.Sequential)] internal readonly unsafe struct ISetupPackageReferenceVTable { public readonly delegate* unmanaged[Stdcall] QueryInterface; public readonly delegate* unmanaged[Stdcall] AddRef; public readonly delegate* unmanaged[Stdcall] Release; // ISetupPackageReference // STDMETHOD(GetId)(_Out_ BSTR* pbstrId) = 0; public readonly delegate* unmanaged[Stdcall] GetId; // STDMETHOD(GetVersion)(_Out_ BSTR* pbstrVersion) = 0; public readonly delegate* unmanaged[Stdcall] GetVersion; // STDMETHOD(GetChip)(_Out_ BSTR* pbstrChip) = 0; public readonly delegate* unmanaged[Stdcall] GetChip; // STDMETHOD(GetLanguage)(_Out_ BSTR* pbstrLanguage) = 0; public readonly delegate* unmanaged[Stdcall] GetLanguage; // STDMETHOD(GetBranch)(_Out_ BSTR* pbstrBranch) = 0; public readonly delegate* unmanaged[Stdcall] GetBranch; // STDMETHOD(GetType)(_Out_ BSTR* pbstrType) = 0; public readonly delegate* unmanaged[Stdcall] GetPackageType; // STDMETHOD(GetUniqueId)(_Out_ BSTR* pbstrUniqueId) = 0; public readonly delegate* unmanaged[Stdcall] GetUniqueId; // STDMETHOD(GetIsExtension)(_Out_ BSTR* pfIsExtension) = 0; public readonly delegate* unmanaged[Stdcall] GetIsExtension; } }