Beispiel #1
0
        private static string InstanceJson(ISetupInstance2 setupInstance2)
        {
            // Visual Studio component directory:
            // https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids

            StringBuilder json = new StringBuilder();

            json.Append("{");

            string path = JsonString(setupInstance2.GetInstallationPath());

            json.Append(String.Format("\"path\":{0},", path));

            string version = JsonString(setupInstance2.GetInstallationVersion());

            json.Append(String.Format("\"version\":{0},", version));

            List <string> packages = new List <string>();

            foreach (ISetupPackageReference package in setupInstance2.GetPackages())
            {
                string id = JsonString(package.GetId());
                packages.Add(id);
            }
            json.Append(String.Format("\"packages\":[{0}]", string.Join(",", packages.ToArray())));

            json.Append("}");
            return(json.ToString());
        }
Beispiel #2
0
        public VisualStudioInstance(ISetupInstance2 FromInstance)
        {
            this.IsLaunchable = FromInstance.IsLaunchable();
            this.IsComplete   = FromInstance.IsComplete();
            this.Name         = FromInstance.GetInstallationName();
            this.Path         = FromInstance.GetInstallationPath();
            this.Version      = FromInstance.GetInstallationVersion();
            this.DisplayName  = FromInstance.GetDisplayName();
            this.Description  = FromInstance.GetDescription();
            this.ResolvePath  = FromInstance.ResolvePath();
            this.EnginePath   = FromInstance.GetEnginePath();
            this.InstanceId   = FromInstance.GetInstanceId();
            this.ProductPath  = FromInstance.GetProductPath();

            try
            {
                var   time     = FromInstance.GetInstallDate();
                ulong high     = (ulong)time.dwHighDateTime;
                uint  low      = (uint)time.dwLowDateTime;
                long  fileTime = (long)((high << 32) + low);

                this.InstallDate = DateTime.FromFileTimeUtc(fileTime);
            }
            catch
            {
                this.InstallDate = DateTime.UtcNow;
            }

            // FromInstance.GetState();
            // FromInstance.GetPackages();
            // FromInstance.GetProduct();
            // FromInstance.GetProperties();
            // FromInstance.GetErrors();
        }
Beispiel #3
0
        public Task <bool> IsInstalledAsync(CancellationToken cancellationToken)
        {
            var versionString = _visualStudioInstance.GetInstallationVersion();

            if (Version.TryParse(versionString, out var version) &&
                version >= MinimumVsVersion)
            {
                return(Task.FromResult(true));
            }

            return(Task.FromResult(false));
        }
        private static VisualStudioInstance FillInInstanceData(ISetupInstance2 instance,
                                                               int lcid,
                                                               Boolean includePackages)
        {
            VisualStudioInstance result = new VisualStudioInstance()
            {
                InstanceId             = instance.GetInstanceId(),
                InstalledVersionNumber = instance.GetInstallationVersion(),
                Description            = instance.GetDescription(lcid),
                DisplayName            = instance.GetDisplayName(lcid)
            };

            // Hides the non-CLS clompliant uint.
            var tempState = instance.GetState();

            if (tempState == InstanceState.Complete)
            {
                result.Status = InstanceStatus.Complete;
            }
            else
            {
                result.Status = (InstanceStatus)tempState;
            }

            result.InstallationPath = instance.GetInstallationPath();

            ISetupPackageReference prod = instance.GetProduct();

            if (prod != null)
            {
                result.ProductName = prod.GetId();
            }

            if ((result.Status & InstanceStatus.Local) == InstanceStatus.Local)
            {
                result.InstallationPath = instance.GetInstallationPath();
            }


            if (includePackages)
            {
                ProcessPackages(instance, result);
            }

            return(result);
        }
Beispiel #5
0
        public VisualStudioInstance(ISetupInstance2 FromInstance)
        {
            this.Packages            = new List <VisualStudioPackage>();
            this.Name                = FromInstance.GetInstallationName();
            this.Path                = FromInstance.GetInstallationPath();
            this.InstallationVersion = FromInstance.GetInstallationVersion();
            this.DisplayName         = FromInstance.GetDisplayName();
            this.ResolvePath         = FromInstance.ResolvePath();
            this.InstanceId          = FromInstance.GetInstanceId();
            this.ProductPath         = FromInstance.GetProductPath();
            this.State               = FromInstance.GetState();

            var packages = FromInstance.GetPackages();

            foreach (var item in packages)
            {
                this.Packages.Add(new VisualStudioPackage(item));
            }
        }
        private string GetVS2019Path()
        {
            try
            {
                SetupConfiguration setupConfiguration = new SetupConfiguration();

                ISetupInstance[] iSetupInstance = new ISetupInstance[1];

                IEnumSetupInstances iEnumSetupInstances = setupConfiguration.EnumAllInstances();
                while (true)
                {
                    {
                        int test;
                        iEnumSetupInstances.Next(1, iSetupInstance, out test);
                        if (test == 0)
                        {
                            break;
                        }
                    }

                    ISetupInstance2 iSetupInstance2 = (ISetupInstance2)iSetupInstance[0];
                    if ((iSetupInstance2.GetState() & InstanceState.Local) == InstanceState.Local)
                    {
                        string InstallationVersion = iSetupInstance2.GetInstallationVersion();
                        if (!string.IsNullOrEmpty(InstallationVersion))
                        {
                            string vs = InstallationVersion.Remove(InstallationVersion.IndexOf('.'));
                            if (vs == "16")
                            {
                                return(iSetupInstance2.GetInstallationPath());
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            throw new Exception("Visual Studio 2019 неустановлена.");
            return(null);
        }
Beispiel #7
0
        private static List <ISetupInstance> GetVisualStudioInstances()
        {
            List <ISetupInstance> vsInstances = new();

            try
            {
                SetupConfiguration   setupConfiguration  = new();
                ISetupConfiguration2 setupConfiguration2 = setupConfiguration;
                IEnumSetupInstances  setupInstances      = setupConfiguration2.EnumInstances();
                ISetupInstance[]     instances           = new ISetupInstance[1];
                int fetched = 0;

                do
                {
                    setupInstances.Next(1, instances, out fetched);

                    if (fetched > 0)
                    {
                        ISetupInstance2 instance = (ISetupInstance2)instances[0];

                        // .NET Workloads only shipped in 17.0 and later and we should only look at IDE based SKUs
                        // such as community, professional, and enterprise.
                        if (Version.TryParse(instance.GetInstallationVersion(), out Version version) &&
                            version.Major >= 17 &&
                            s_visualStudioProducts.Contains(instance.GetProduct().GetId()))
                        {
                            vsInstances.Add(instances[0]);
                        }
                    }
                }while (fetched > 0);
            }
            catch (COMException e) when(e.ErrorCode == REGDB_E_CLASSNOTREG)
            {
                // Query API not registered, good indication there are no VS installations of 15.0 or later.
                // Other exceptions are passed through since that likely points to a real error.
            }

            return(vsInstances);
        }
        private static IEnumerable <IVisualStudioInfo> DetectNewVisualStudios()
        {
            SetupConfiguration configuration;

            try
            {
                configuration = new SetupConfiguration();
            }
            catch (COMException ex)
            {
                // class not registered, no VS2017+ installations
                if ((uint)ex.HResult == 0x80040154)
                {
                    yield break;
                }

                throw;
            }
            IEnumSetupInstances e = configuration.EnumAllInstances();

            int fetched;

            ISetupInstance[] instances = new ISetupInstance[1];
            do
            {
                e.Next(1, instances, out fetched);
                if (fetched <= 0)
                {
                    continue;
                }

                ISetupInstance2 instance2 = (ISetupInstance2)instances[0];
                string          filename  = Path.Combine(instance2.GetInstallationPath(), @"Common7\IDE\devenv.exe");
                if (File.Exists(filename))
                {
                    yield return(new VisualStudio2017Info(Version.Parse(instance2.GetInstallationVersion()), instance2.GetDisplayName(), filename));
                }
            }while (fetched > 0);
        }
Beispiel #9
0
        private static VSInstance ParseInstance(ISetupInstance2 setupInstance2)
        {
            VSInstance inst = new VSInstance();

            string[] prodParts = setupInstance2.GetProduct().GetId().Split('.');
            Array.Reverse(prodParts);
            inst["Product"]              = prodParts[0];
            inst["ID"]                   = setupInstance2.GetInstanceId();
            inst["Name"]                 = setupInstance2.GetDisplayName(0x1000);
            inst["Description"]          = setupInstance2.GetDescription(0x1000);
            inst["InstallationName"]     = setupInstance2.GetInstallationName();
            inst["Version"]              = setupInstance2.GetInstallationVersion();
            inst["State"]                = Enum.GetName(typeof(InstanceState), setupInstance2.GetState());
            inst["InstallationPath"]     = setupInstance2.GetInstallationPath();
            inst["IsComplete"]           = setupInstance2.IsComplete();
            inst["IsLaunchable"]         = setupInstance2.IsLaunchable();
            inst["Common7ToolsPath"]     = inst["InstallationPath"] + @"\Common7\Tools\";
            inst["CmdPath"]              = inst["Common7ToolsPath"] + "VsDevCmd.bat";
            inst["VCAuxiliaryBuildPath"] = inst["InstallationPath"] + @"\VC\Auxiliary\Build\";
            inst["VCVarsAllPath"]        = inst["VCAuxiliaryBuildPath"] + "vcvarsall.bat";

            inst["Win8SDK"]        = "";
            inst["SDK10Full"]      = "";
            inst["VisualCppTools"] = "";

            Regex trimmer = new Regex(@"\.\d+$");

            List <string> packs = new List <String>();

            foreach (ISetupPackageReference package in setupInstance2.GetPackages())
            {
                string id = package.GetId();

                string ver    = package.GetVersion();
                string detail = "{\"id\": \"" + id + "\", \"version\":\"" + ver + "\"}";
                packs.Add("        " + detail);

                if (id.Contains("Component.MSBuild"))
                {
                    inst["MSBuild"]        = detail;
                    inst["MSBuildVerFull"] = ver;
                }
                else if (id.Contains("Microsoft.VisualCpp.Tools.Core"))
                {
                    inst["VCTools"] = detail;
                    inst["VisualCppToolsFullVersion"] = ver;
                    string majorMinor = trimmer.Replace(trimmer.Replace(ver, ""), "");
                    inst["VisualCppToolsVersionMinor"] = majorMinor;
                    inst["VCToolsVersionCode"]         = "vc" + majorMinor.Replace(".", "");
                }
                else if (id.Contains("Microsoft.Windows.81SDK"))
                {
                    if (inst["Win8SDK"].ToString().CompareTo(ver) > 0)
                    {
                        continue;
                    }
                    inst["Win8SDK"] = ver;
                }
                else if (id.Contains("Win10SDK_10"))
                {
                    if (inst["SDK10Full"].ToString().CompareTo(ver) > 0)
                    {
                        continue;
                    }
                    inst["SDK10Full"] = ver;
                }
            }
            packs.Sort();
            inst["Packages"] = packs.ToArray();

            string[] sdk10Parts = inst["SDK10Full"].ToString().Split('.');
            sdk10Parts[sdk10Parts.Length - 1] = "0";
            inst["SDK10"] = String.Join(".", sdk10Parts);
            inst["SDK"]   = inst["SDK10"].ToString() != "0" ? inst["SDK10"] : inst["Win8SDK"];
            if (inst.ContainsKey("MSBuildVerFull"))
            {
                string ver = trimmer.Replace(trimmer.Replace((string)inst["MSBuildVerFull"], ""), "");
                inst["MSBuildVer"]       = ver;
                inst["MSBuildToolsPath"] = inst["InstallationPath"] + @"\MSBuild\" + ver + @"\Bin\";
                inst["MSBuildPath"]      = inst["MSBuildToolsPath"] + "MSBuild.exe";
            }
            if (inst.ContainsKey("VCTools"))
            {
                string ver = trimmer.Replace((string)inst["VisualCppToolsFullVersion"], "");
                inst["VisualCppToolsX64"]   = inst["InstallationPath"] + @"\VC\Tools\MSVC\" + ver + @"\bin\HostX64\x64\";
                inst["VisualCppToolsX64CL"] = inst["VisualCppToolsX64"] + "cl.exe";
                inst["VisualCppToolsX86"]   = inst["InstallationPath"] + @"\VC\Tools\MSVC\" + ver + @"\bin\HostX86\x86\";
                inst["VisualCppToolsX86CL"] = inst["VisualCppToolsX86"] + "cl.exe";
                inst["VisualCppTools"]      = Is64() ? inst["VisualCppToolsX64"] : inst["VisualCppToolsX86"];
                inst["VisualCppToolsCL"]    = Is64() ? inst["VisualCppToolsX64CL"] : inst["VisualCppToolsX86CL"];
            }
            inst["IsVcCompatible"] = inst.JSONBool("SDK") && inst.JSONBool("MSBuild") && inst.JSONBool("VisualCppTools");
            return(inst);
        }
Beispiel #10
0
        private static string GetPathOfFirstInstalledVisualStudioInstance()
        {
            Tuple <Version, string> highestVersion = null;

            try
            {
                IEnumSetupInstances setupInstances = new SetupConfiguration().EnumAllInstances();

                ISetupInstance[] instances = new ISetupInstance[1];

                for (setupInstances.Next(1, instances, out int fetched); fetched > 0; setupInstances.Next(1, instances, out fetched))
                {
                    ISetupInstance2 instance = (ISetupInstance2)instances.First();

                    if (instance.GetState() == InstanceState.Complete)
                    {
                        string installationPath = instance.GetInstallationPath();

                        if (!string.IsNullOrWhiteSpace(installationPath) && Version.TryParse(instance.GetInstallationVersion(), out Version version))
                        {
                            if (highestVersion == null || version > highestVersion.Item1)
                            {
                                highestVersion = new Tuple <Version, string>(version, installationPath);
                            }
                        }
                    }
                }

                if (highestVersion != null)
                {
                    return(Path.Combine(highestVersion.Item2, "MSBuild", GetMSBuildVersionDirectory($"{highestVersion.Item1.Major}.0"), "Bin"));
                }
            }
            catch
            {
                // Ignored
            }

            return(null);
        }
Beispiel #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Instance"/> class.
        /// </summary>
        /// <param name="instance">The <see cref="ISetupInstance2"/> to adapt.</param>
        /// <exception cref="ArgumentNullException"><paramref name="instance"/> is null.</exception>
        internal Instance(ISetupInstance2 instance)
        {
            Validate.NotNull(instance, nameof(instance));

            // The instance ID is required, but then try to set other properties to release the COM object and its resources ASAP.
            InstanceId = instance.GetInstanceId();

            TrySet(ref installationName, nameof(InstallationName), instance.GetInstallationName);
            TrySet(ref installationPath, nameof(InstallationPath), instance.GetInstallationPath);
            TrySet(ref installationVersion, nameof(InstallationVersion), () =>
            {
                Version version;

                var versionString = instance.GetInstallationVersion();
                if (Version.TryParse(versionString, out version))
                {
                    return(version.Normalize());
                }

                return(null);
            });

            TrySet(ref installDate, nameof(InstallDate), () =>
            {
                var ft = instance.GetInstallDate();
                var l  = ((long)ft.dwHighDateTime << 32) + ft.dwLowDateTime;

                return(DateTime.FromFileTime(l));
            });

            TrySet(ref state, nameof(State), instance.GetState);

            var lcid = CultureInfo.CurrentUICulture.LCID;

            TrySet(ref displayName, nameof(DisplayName), () =>
            {
                return(instance.GetDisplayName(lcid));
            });

            TrySet(ref description, nameof(Description), () =>
            {
                return(instance.GetDescription(lcid));
            });

            TrySet(ref productPath, nameof(ProductPath), () =>
            {
                var path = instance.GetProductPath();
                return(instance.ResolvePath(path));
            });

            TrySet(ref product, nameof(Product), () =>
            {
                var reference = instance.GetProduct();
                if (reference != null)
                {
                    return(new PackageReference(reference));
                }

                return(null);
            });

            TrySet(ref packages, nameof(Packages), () =>
            {
                return(new List <PackageReference>(GetPackages(instance)));
            });

            if (packages != null && packages.Any())
            {
                Packages = new ReadOnlyCollection <PackageReference>(packages);
            }

            TrySet(ref properties, nameof(Properties), () =>
            {
                var properties = instance.GetProperties();
                return(properties?.GetNames()
                       .ToDictionary(name => name.ToPascalCase(), name => properties.GetValue(name), StringComparer.OrdinalIgnoreCase));
            });

            if (properties != null)
            {
                Properties = new ReadOnlyDictionary <string, object>(properties);
            }
            else
            {
                // While accessing properties on a null object succeeds in PowerShell, accessing the indexer does not.
                Properties = ReadOnlyDictionary <string, object> .Empty;
            }

            TrySet(ref enginePath, nameof(EnginePath), instance.GetEnginePath);
            TrySet(ref isComplete, nameof(IsComplete), instance.IsComplete);
            TrySet(ref isLaunchable, nameof(IsLaunchable), instance.IsLaunchable);

            // Get all properties of the instance not explicitly declared.
            var store = (ISetupPropertyStore)instance;

            AdditionalProperties = store.GetNames()
                                   .Where(name => !DeclaredProperties.Contains(name))
                                   .ToDictionary(name => name.ToPascalCase(), name => store.GetValue(name), StringComparer.OrdinalIgnoreCase);
        }
Beispiel #12
0
        static List <VisualStudioInstallation> GetVisualStudioInstallations()
        {
            CachedInstalls.Clear();

            try
            {
                SetupConfiguration  Setup      = new SetupConfiguration();
                IEnumSetupInstances Enumerator = Setup.EnumAllInstances();

                ISetupInstance[] Instances = new ISetupInstance[1];
                for (; ;)
                {
                    int NumFetched;
                    Enumerator.Next(1, Instances, out NumFetched);

                    if (NumFetched == 0)
                    {
                        break;
                    }

                    ISetupInstance2 Instance = (ISetupInstance2)Instances[0];
                    if ((Instance.GetState() & InstanceState.Local) == InstanceState.Local)
                    {
                        string   VersionString = Instance.GetInstallationVersion();
                        string[] Components    = VersionString.Split('.');

                        if (Components.Length == 0)
                        {
                            continue;
                        }

                        int    MajorVersion;
                        string InstallationPath = Instance.GetInstallationPath();
                        string DevEnvPath       = Path.Combine(InstallationPath, "Common7\\IDE\\devenv.exe");

                        if (!int.TryParse(Components[0], out MajorVersion) || (MajorVersion != 15 && MajorVersion != 16))
                        {
                            continue;
                        }


                        if (!File.Exists(DevEnvPath))
                        {
                            continue;
                        }

                        VisualStudioInstallation Installation = new VisualStudioInstallation()
                        {
                            BaseDir = InstallationPath, DevEnvPath = DevEnvPath, MajorVersion = MajorVersion, ROTMoniker = string.Format("!VisualStudio.DTE.{0}.0", MajorVersion)
                        };

                        CachedInstalls.Add(Installation);
                    }
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(string.Format("Exception while finding Visual Studio installations {0}", Ex.Message));
            }

            // prefer newer versions
            CachedInstalls.Sort((A, B) => { return(-A.MajorVersion.CompareTo(B.MajorVersion)); });

            return(CachedInstalls);
        }