Example #1
0
 public IEnumerable <IJunkResult> FindJunk(ApplicationUninstallerEntry target)
 {
     // Do nothing when called by the manager
     yield break;
 }
        public IEnumerable <IJunkResult> FindJunk(ApplicationUninstallerEntry target)
        {
            var returnList = new List <IJunkResult>();

            if (string.IsNullOrEmpty(target.InstallLocation))
            {
                return(returnList);
            }

            string pathRoot;

            try
            {
                pathRoot = Path.GetPathRoot(target.InstallLocation);
            }
            catch (SystemException ex)
            {
                Console.WriteLine(ex);
                return(returnList);
            }

            var unrootedLocation = pathRoot.Length >= 1
                ? target.InstallLocation.Replace(pathRoot, string.Empty)
                : target.InstallLocation;

            if (string.IsNullOrEmpty(unrootedLocation.Trim()))
            {
                return(returnList);
            }

            try
            {
                using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Tracing", true))
                {
                    if (key != null && target.SortedExecutables != null)
                    {
                        var exeNames = target.SortedExecutables.Select(Path.GetFileNameWithoutExtension).ToList();

                        foreach (var keyGroup in key.GetSubKeyNames()
                                 .Where(x => x.EndsWith("_RASAPI32") || x.EndsWith("_RASMANCS"))
                                 .Select(name => new { name, trimmed = name.Substring(0, name.LastIndexOf('_')) })
                                 .GroupBy(x => x.trimmed))
                        {
                            if (exeNames.Contains(keyGroup.Key, StringComparison.InvariantCultureIgnoreCase))
                            {
                                foreach (var keyName in keyGroup)
                                {
                                    var junk = new RegistryKeyJunk(Path.Combine(key.Name, keyName.name), target, this);
                                    junk.Confidence.Add(ConfidenceRecords.ExplicitConnection);
                                    returnList.Add(junk);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is UnauthorizedAccessException || ex is SecurityException || ex is IOException)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    throw;
                }
            }

            return(returnList);
        }
 private FileSystemJunk CreateJunkNode(Shortcut source, ApplicationUninstallerEntry entry)
 {
     return(new FileSystemJunk(new FileInfo(source.LinkFilename), entry, this));
 }
Example #4
0
        private static string GetTrimmedName(ApplicationUninstallerEntry entry)
        {
            var displayNameTrimmed = entry.DisplayNameTrimmed;

            return(displayNameTrimmed.Length > 3 ? displayNameTrimmed : entry.DisplayName);
        }
        public override IEnumerable <IJunkResult> FindJunk(ApplicationUninstallerEntry target)
        {
            var isStoreApp = target.UninstallerKind == UninstallerType.StoreApp;

            if (isStoreApp && string.IsNullOrEmpty(target.RatingId))
            {
                throw new ArgumentException("StoreApp entry has no ID");
            }

            if (isStoreApp)
            {
                foreach (var regAppEntry in _regAppsValueCache)
                {
                    if (regAppEntry.AppName == null)
                    {
                        continue;
                    }

                    if (string.Equals(regAppEntry.AppName, target.RatingId, StringComparison.OrdinalIgnoreCase))
                    {
                        // Handle the value under RegisteredApps itself
                        var regAppResult = new RegistryValueJunk(regAppEntry.RegAppFullPath, regAppEntry.ValueName, target, this);
                        regAppResult.Confidence.Add(ConfidenceRecords.ExplicitConnection);
                        yield return(regAppResult);

                        // Handle the key pointed at by the value
                        var appEntryKey = new RegistryKeyJunk(regAppEntry.AppKey, target, this);
                        appEntryKey.Confidence.Add(ConfidenceRecords.ExplicitConnection);
                        appEntryKey.Confidence.Add(ConfidenceRecords.IsStoreApp);
                        yield return(appEntryKey);
                    }
                }
            }
            else
            {
                foreach (var regAppEntry in _regAppsValueCache)
                {
                    if (regAppEntry.AppName != null)
                    {
                        continue;
                    }

                    var generatedConfidence = ConfidenceGenerators.GenerateConfidence(regAppEntry.ValueName, target).ToList();

                    if (generatedConfidence.Count > 0)
                    {
                        // Handle the value under RegisteredApps itself
                        var regAppResult = new RegistryValueJunk(regAppEntry.RegAppFullPath, regAppEntry.ValueName, target, this);
                        regAppResult.Confidence.AddRange(generatedConfidence);
                        yield return(regAppResult);

                        // Handle the key pointed at by the value
                        const string capabilitiesSubkeyName = "\\Capabilities";
                        if (regAppEntry.TargetSubKeyPath.EndsWith(capabilitiesSubkeyName, StringComparison.Ordinal))
                        {
                            var capabilitiesKeyResult = new RegistryKeyJunk(regAppEntry.TargetFullPath, target, this);
                            capabilitiesKeyResult.Confidence.AddRange(generatedConfidence);
                            yield return(capabilitiesKeyResult);

                            var ownerKey = regAppEntry.TargetFullPath.Substring(0,
                                                                                regAppEntry.TargetFullPath.Length - capabilitiesSubkeyName.Length);

                            var subConfidence = ConfidenceGenerators.GenerateConfidence(Path.GetFileName(ownerKey),
                                                                                        target).ToList();
                            if (subConfidence.Count > 0)
                            {
                                var subResult = new RegistryKeyJunk(ownerKey, target, this);
                                subResult.Confidence.AddRange(subConfidence);
                                yield return(subResult);
                            }
                        }
                    }
                }
            }
        }
Example #6
0
        // TODO read the app manifests for more info, requires json parsing - var manifest = Path.Combine(installDir, "current\\manifest.json");
        public IList <ApplicationUninstallerEntry> GetUninstallerEntries(ListGenerationProgress.ListGenerationCallback progressCallback)
        {
            var results = new List <ApplicationUninstallerEntry>();

            if (!ScoopIsAvailable)
            {
                return(results);
            }

            // Make uninstaller for scoop itself
            var scoopEntry = new ApplicationUninstallerEntry
            {
                RawDisplayName  = "Scoop",
                Comment         = "Automated program installer",
                AboutUrl        = "https://github.com/lukesampson/scoop",
                InstallLocation = _scoopUserPath
            };

            // Make sure the global directory gets removed as well
            var junk = new FileSystemJunk(new DirectoryInfo(_scoopGlobalPath), scoopEntry, null);

            junk.Confidence.Add(ConfidenceRecords.ExplicitConnection);
            junk.Confidence.Add(4);
            scoopEntry.AdditionalJunk.Add(junk);

            scoopEntry.UninstallString = MakeScoopCommand("uninstall scoop").ToString();
            scoopEntry.UninstallerKind = UninstallerType.PowerShell;
            results.Add(scoopEntry);

            // Make uninstallers for apps installed by scoop
            var result = RunScoopCommand("export");

            if (string.IsNullOrEmpty(result))
            {
                return(results);
            }

            var appEntries  = result.Split(StringTools.NewLineChars.ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
            var exeSearcher = new AppExecutablesSearcher();

            foreach (var str in appEntries)
            {
                // Format should be "$app (v:$ver) $global_display $bucket $arch"
                // app has no spaces, $global_display is *global*, bucket is inside [] brackets like [main]
                // version should always be there but the check errored out for some users, everything after version is optional
                string name;
                string version    = null;
                bool   isGlobal   = false;
                var    spaceIndex = str.IndexOf(" ", StringComparison.Ordinal);
                if (spaceIndex > 0)
                {
                    name = str.Substring(0, spaceIndex);

                    var startIndex = str.IndexOf("(v:", StringComparison.Ordinal);
                    if (startIndex > 0)
                    {
                        var verEndIndex = str.IndexOf(')', startIndex);
                        version = str.Substring(Math.Min(startIndex + 3, str.Length - 1), Math.Max(verEndIndex - startIndex - 3, 0));
                        if (version.Length == 0)
                        {
                            version = null;
                        }
                    }
                    isGlobal = str.Substring(spaceIndex).Contains("*global*");
                }
                else
                {
                    name = str;
                }

                var entry = new ApplicationUninstallerEntry
                {
                    RawDisplayName = name,
                    DisplayVersion = ApplicationEntryTools.CleanupDisplayVersion(version),
                    RatingId       = "Scoop " + name
                };

                var installDir = Path.Combine(isGlobal ? _scoopGlobalPath : _scoopUserPath, "apps\\" + name);
                if (Directory.Exists(installDir))
                {
                    // Avoid looking for executables in old versions
                    entry.InstallLocation = Path.Combine(installDir, "current");
                    exeSearcher.AddMissingInformation(entry);

                    entry.InstallLocation = installDir;
                }

                entry.UninstallerKind = UninstallerType.PowerShell;
                entry.UninstallString = MakeScoopCommand("uninstall " + name + (isGlobal ? " --global" : "")).ToString();

                results.Add(entry);
            }

            return(results);
        }
 public DriveJunk(ApplicationUninstallerEntry entry, IEnumerable <ApplicationUninstallerEntry> otherUninstallers)
     : base(entry, otherUninstallers)
 {
 }
 private static IEnumerable <ApplicationUninstallerEntry> GetRelatedUninstallers(
     ApplicationUninstallerEntry thisUninstaller, IEnumerable <ApplicationUninstallerEntry> other)
 {
     return(other.Where(y => ApplicationEntryTools.AreEntriesRelated(thisUninstaller, y, -3)));
 }
Example #9
0
        public IEnumerable <ApplicationUninstallerEntry> GetUninstallerEntries(ListGenerationProgress.ListGenerationCallback progressCallback)
        {
            if (!HelperAvailable)
            {
                yield break;
            }

            var output = FactoryTools.StartHelperAndReadOutput(HelperPath, "/query");

            if (string.IsNullOrEmpty(output))
            {
                yield break;
            }

            foreach (var data in FactoryTools.ExtractAppDataSetsFromHelperOutput(output))
            {
                if (!data.ContainsKey("CanonicalName"))
                {
                    continue;
                }
                var name = data["CanonicalName"];
                if (string.IsNullOrEmpty(name))
                {
                    continue;
                }

                var uninstallStr = $"\"{HelperPath}\" /uninstall {name}";

                var entry = new ApplicationUninstallerEntry
                {
                    RatingId = name,
                    //RegistryKeyName = name,
                    UninstallString      = uninstallStr,
                    QuietUninstallString = uninstallStr,
                    IsValid         = true,
                    UninstallerKind = UninstallerType.Oculus,
                    InstallLocation = data["InstallLocation"],
                    DisplayVersion  = data["Version"],
                    IsProtected     = "true".Equals(data["IsCore"], StringComparison.OrdinalIgnoreCase),
                };

                var executable = data["LaunchFile"];
                if (File.Exists(executable))
                {
                    ExecutableAttributeExtractor.FillInformationFromFileAttribs(entry, executable, true);
                    entry.DisplayIcon = executable;
                }

                if (Directory.Exists(entry.InstallLocation))
                {
                    entry.InstallDate = Directory.GetCreationTime(entry.InstallLocation);
                }

                if (string.IsNullOrEmpty(entry.RawDisplayName))
                {
                    entry.RawDisplayName = name.Replace('-', ' ').ToTitleCase();
                }

                yield return(entry);
            }
        }
Example #10
0
        /// <summary>
        ///     Test if the input matches this condition. Returns null if it is impossible to determine.
        /// </summary>
        public bool?TestEntry(ApplicationUninstallerEntry input)
        {
            if (!Enabled)
            {
                return(null);
            }

            var targets = ReferenceEquals(TargetProperty, ComparisonTargetInfo.AllTargetComparison)
                ? ComparisonTargetInfo.ComparisonTargets.Where(x => x.PossibleStrings == null)
                          .Select(x => x.Getter(input))
                : new[] { TargetProperty.Getter(input) };

            bool?result = null;

            foreach (var target in targets.Where(target => !string.IsNullOrEmpty(target)))
            {
                try
                {
                    switch (ComparisonMethod)
                    {
                    case ComparisonMethod.Equals:
                        result = target.Equals(FilterText, StringComparison.InvariantCultureIgnoreCase);
                        break;

                    case ComparisonMethod.Any:
                        result = target.ContainsAny(
                            FilterText.Split((char[])null, StringSplitOptions.RemoveEmptyEntries),
                            StringComparison.InvariantCultureIgnoreCase);
                        break;

                    case ComparisonMethod.StartsWith:
                        result = target.StartsWith(FilterText, StringComparison.InvariantCultureIgnoreCase);
                        break;

                    case ComparisonMethod.EndsWith:
                        result = target.EndsWith(FilterText, StringComparison.InvariantCultureIgnoreCase);
                        break;

                    case ComparisonMethod.Contains:
                        result = target.Contains(FilterText, StringComparison.InvariantCultureIgnoreCase);
                        break;

                    case ComparisonMethod.Regex:
                        result = Regex.IsMatch(target, FilterText, RegexOptions.CultureInvariant);
                        break;

                    default:
                        throw new InvalidOperationException("Unknown FilterComparisonMethod");
                    }
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
                catch
                {
                    //result = null;
                }

                if (result == true)
                {
                    return(!InvertResults);
                }
            }

            if (!result.HasValue)
            {
                return(null);
            }
            return(InvertResults ? !result.Value : result.Value);
        }
 public CacheEntry(ApplicationUninstallerEntry entry, byte[] icon)
 {
     Entry = entry;
     Icon  = icon;
 }
Example #12
0
 public StartupJunk(ApplicationUninstallerEntry entry)
     : base(entry, Enumerable.Empty <ApplicationUninstallerEntry>())
 {
 }
 protected JunkResultBase(ApplicationUninstallerEntry application, IJunkCreator source, ConfidenceCollection confidence)
 {
     Application = application;
     Source      = source;
     Confidence  = confidence;
 }
 protected JunkResultBase(ApplicationUninstallerEntry application, IJunkCreator source) : this(application, source, new ConfidenceCollection())
 {
 }
        private static IEnumerable <ApplicationUninstallerEntry> GetUpdates()
        {
            if (!HelperIsAvailable)
            {
                yield break;
            }

            var output = FactoryTools.StartProcessAndReadOutput(HelperPath, "list");

            if (string.IsNullOrEmpty(output) || output.Contains("error", StringComparison.OrdinalIgnoreCase))
            {
                yield break;
            }

            foreach (var group in ProcessInput(output))
            {
                var entry = new ApplicationUninstallerEntry
                {
                    UninstallerKind = UninstallerType.WindowsUpdate,
                    IsUpdate        = true,
                    Publisher       = "Microsoft Corporation"
                };
                foreach (var valuePair in group)
                {
                    switch (valuePair.Key)
                    {
                    case "UpdateID":
                        entry.RatingId = valuePair.Value;
                        Guid result;
                        if (GuidTools.TryExtractGuid(valuePair.Value, out result))
                        {
                            entry.BundleProviderKey = result;
                        }
                        break;

                    case "RevisionNumber":
                        entry.DisplayVersion = ApplicationEntryTools.CleanupDisplayVersion(valuePair.Value);
                        break;

                    case "Title":
                        entry.RawDisplayName = valuePair.Value;
                        break;

                    case "IsUninstallable":
                        bool isUnins;
                        if (bool.TryParse(valuePair.Value, out isUnins))
                        {
                            entry.IsValid = isUnins;
                        }
                        break;

                    case "SupportUrl":
                        entry.AboutUrl = valuePair.Value;
                        break;

                    case "MinDownloadSize":
                        long size;
                        if (long.TryParse(valuePair.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out size))
                        {
                            entry.EstimatedSize = FileSize.FromBytes(size);
                        }
                        break;

                    case "LastDeploymentChangeTime":
                        DateTime date;
                        if (DateTime.TryParse(valuePair.Value, CultureInfo.InvariantCulture, DateTimeStyles.None, out date) &&
                            !DateTime.MinValue.Equals(date))
                        {
                            entry.InstallDate = date;
                        }
                        break;
                    }
                }

                if (entry.IsValid)
                {
                    entry.UninstallString      = $"\"{HelperPath}\" uninstall {entry.RatingId}";
                    entry.QuietUninstallString = entry.UninstallString;
                }

                yield return(entry);
            }
        }
Example #16
0
        /// <summary>
        /// Check how related are the two entries.
        /// Values above 0 mean there is good confidence
        /// </summary>
        public static int AreEntriesRelated(ApplicationUninstallerEntry baseEntry, ApplicationUninstallerEntry otherEntry)
        {
            //Debug.Assert(!(otherEntry.DisplayName.Contains("Steam", StringComparison.OrdinalIgnoreCase) &&
            //    baseEntry.DisplayName.Contains("Steam", StringComparison.OrdinalIgnoreCase)));

            if (PathTools.PathsEqual(baseEntry.InstallLocation, otherEntry.InstallLocation))
            {
                return(100);
            }

            if (!string.IsNullOrEmpty(baseEntry.UninstallString))
            {
                if (PathTools.PathsEqual(baseEntry.UninstallString, otherEntry.UninstallString))
                {
                    return(100);
                }

                if (!string.IsNullOrEmpty(otherEntry.InstallLocation) &&
                    baseEntry.UninstallString.Contains(otherEntry.InstallLocation, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(100);
                }
            }

            if (!string.IsNullOrEmpty(baseEntry.UninstallerLocation) && !string.IsNullOrEmpty(otherEntry.InstallLocation) &&
                baseEntry.UninstallerLocation.StartsWith(otherEntry.InstallLocation, StringComparison.InvariantCultureIgnoreCase))
            {
                return(100);
            }

            var score = 0;

            if (!string.IsNullOrEmpty(baseEntry.InstallLocation) && !string.IsNullOrEmpty(otherEntry.InstallLocation))
            {
                AddScore(ref score, -8, 0, -3, baseEntry.InstallLocation.Contains(otherEntry.InstallLocation,
                                                                                  StringComparison.InvariantCultureIgnoreCase));
            }

            AddScore(ref score, -5, 0, 3, baseEntry.Is64Bit != MachineType.Unknown && otherEntry.Is64Bit != MachineType.Unknown ?
                     baseEntry.Is64Bit == otherEntry.Is64Bit : (bool?)null);
            AddScore(ref score, -3, -1, 5, CompareDates(baseEntry.InstallDate, otherEntry.InstallDate));

            AddScore(ref score, -2, 0, 5, CompareStrings(baseEntry.DisplayVersion, otherEntry.DisplayVersion, true));
            AddScore(ref score, -5, 0, 5, CompareStrings(baseEntry.Publisher, otherEntry.Publisher));

            // Check if base entry was installed from inside other entry's install directory
            if (string.IsNullOrEmpty(baseEntry.InstallLocation) && !string.IsNullOrEmpty(baseEntry.InstallSource) &&
                !string.IsNullOrEmpty(otherEntry.InstallLocation) && otherEntry.InstallLocation.Length >= 5)
            {
                AddScore(ref score, 0, 0, 5, baseEntry.InstallSource.Contains(
                             otherEntry.InstallLocation, StringComparison.InvariantCultureIgnoreCase));
            }

            var nameSimilarity = CompareStrings(baseEntry.DisplayName, otherEntry.DisplayName);

            AddScore(ref score, -5, -2, 8, nameSimilarity);
            if (!nameSimilarity.HasValue || nameSimilarity == false)
            {
                var trimmedSimilarity = CompareStrings(baseEntry.DisplayNameTrimmed, otherEntry.DisplayNameTrimmed);
                // Don't risk it if names can't be compared at all
                //if (!trimmedSimilarity.HasValue && !nameSimilarity.HasValue) return false;
                AddScore(ref score, -5, -2, 8, trimmedSimilarity);
            }

            try
            {
                AddScore(ref score, -2, -2, 5, CompareStrings(baseEntry.DisplayNameTrimmed.Length < 5 ?
                                                              baseEntry.DisplayName : baseEntry.DisplayNameTrimmed, Path.GetFileName(otherEntry.InstallLocation)));
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.Message);
            }
            //Debug.Assert(score <= 0);
            return(score);
        }
Example #17
0
        // TODO read the app manifests for more info, requires json parsing - var manifest = Path.Combine(installDir, "current\\manifest.json");
        public IEnumerable <ApplicationUninstallerEntry> GetUninstallerEntries(ListGenerationProgress.ListGenerationCallback progressCallback)
        {
            if (!ScoopIsAvailable)
            {
                yield break;
            }

            // Make uninstaller for scoop itself
            var scoopEntry = new ApplicationUninstallerEntry();

            scoopEntry.RawDisplayName  = "Scoop";
            scoopEntry.Comment         = "Automated program installer";
            scoopEntry.AboutUrl        = "https://github.com/lukesampson/scoop";
            scoopEntry.InstallLocation = _scoopUserPath;

            // Make sure the global directory gets removed as well
            var junk = new FileSystemJunk(new DirectoryInfo(_scoopGlobalPath), scoopEntry, null);

            junk.Confidence.Add(ConfidenceRecords.ExplicitConnection);
            junk.Confidence.Add(4);
            scoopEntry.AdditionalJunk.Add(junk);

            scoopEntry.UninstallString = MakeScoopCommand("uninstall scoop").ToString();
            scoopEntry.UninstallerKind = UninstallerType.PowerShell;
            yield return(scoopEntry);

            // Make uninstallers for apps installed by scoop
            var result = RunScoopCommand("export");

            if (string.IsNullOrEmpty(result))
            {
                yield break;
            }

            var appEntries  = result.Split(StringTools.NewLineChars.ToArray(), StringSplitOptions.RemoveEmptyEntries);
            var exeSearcher = new AppExecutablesSearcher();

            foreach (var str in appEntries)
            {
                var startIndex  = str.IndexOf("(v:", StringComparison.Ordinal);
                var verEndIndex = str.IndexOf(')', startIndex);

                var name     = str.Substring(0, startIndex - 1);
                var version  = str.Substring(startIndex + 3, verEndIndex - startIndex - 3);
                var isGlobal = str.Substring(verEndIndex).Contains("*global*");

                var entry = new ApplicationUninstallerEntry();
                entry.RawDisplayName = name;
                entry.DisplayVersion = version;
                entry.RatingId       = "Scoop " + name;

                var installDir = Path.Combine(isGlobal ? _scoopGlobalPath : _scoopUserPath, "apps\\" + name);
                if (Directory.Exists(installDir))
                {
                    // Avoid looking for executables in old versions
                    entry.InstallLocation = Path.Combine(installDir, "current");
                    exeSearcher.AddMissingInformation(entry);

                    entry.InstallLocation = installDir;
                }

                entry.UninstallerKind = UninstallerType.PowerShell;
                entry.UninstallString = MakeScoopCommand("uninstall " + name + (isGlobal ? " --global" : "")).ToString();

                yield return(entry);
            }
        }
Example #18
0
 public RegistryValueJunk(string containingKeyPath, string valueName, ApplicationUninstallerEntry application,
                          IJunkCreator source) : base(containingKeyPath, application, source)
 {
     ValueName = valueName;
 }
Example #19
0
 protected JunkBase(ApplicationUninstallerEntry entry, IEnumerable <ApplicationUninstallerEntry> otherUninstallers)
 {
     Uninstaller       = entry;
     OtherUninstallers = otherUninstallers;
 }
        private static IEnumerable <ApplicationUninstallerEntry> GetSteamApps()
        {
            if (!SteamHelperIsAvailable)
            {
                yield break;
            }

            var output = FactoryTools.StartProcessAndReadOutput(SteamHelperPath, "list");

            if (string.IsNullOrEmpty(output) || output.Contains("error", StringComparison.InvariantCultureIgnoreCase))
            {
                yield break;
            }

            foreach (var idString in output.SplitNewlines(StringSplitOptions.RemoveEmptyEntries))
            {
                int appId;
                if (!int.TryParse(idString, out appId))
                {
                    continue;
                }

                output = FactoryTools.StartProcessAndReadOutput(SteamHelperPath,
                                                                "info " + appId.ToString("G"));
                if (string.IsNullOrEmpty(output) ||
                    output.Contains("error", StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                var lines = output.SplitNewlines(StringSplitOptions.RemoveEmptyEntries).Select(x =>
                {
                    var o = x.Split(new[] { " - " }, StringSplitOptions.None);
                    return(new KeyValuePair <string, string>(o[0], o[1]));
                }).ToList();

                var entry = new ApplicationUninstallerEntry
                {
                    DisplayName =
                        lines.Single(x => x.Key.Equals("Name", StringComparison.InvariantCultureIgnoreCase)).Value,
                    UninstallString =
                        lines.Single(x => x.Key.Equals("UninstallString", StringComparison.InvariantCultureIgnoreCase))
                        .Value,
                    InstallLocation =
                        lines.Single(x => x.Key.Equals("InstallDirectory", StringComparison.InvariantCultureIgnoreCase))
                        .Value,
                    UninstallerKind = UninstallerType.Steam,
                    IsValid         = true,
                    IsOrphaned      = true,
                    RatingId        = "Steam App " + appId.ToString("G")
                };

                long bytes;
                if (
                    long.TryParse(
                        lines.Single(x => x.Key.Equals("SizeOnDisk", StringComparison.InvariantCultureIgnoreCase)).Value,
                        out bytes))
                {
                    entry.EstimatedSize = FileSize.FromBytes(bytes);
                }

                yield return(entry);
            }
        }
Example #21
0
        public IEnumerable <ApplicationUninstallerEntry> GetUninstallerEntries(ListGenerationProgress.ListGenerationCallback progressCallback)
        {
            if (!ChocoIsAvailable)
            {
                yield break;
            }

            var result = StartProcessAndReadOutput(ChocoLocation, @"list -l -nocolor -y -r");

            if (string.IsNullOrEmpty(result))
            {
                yield break;
            }

            var appEntries = result.Split(NewlineSeparators, StringSplitOptions.RemoveEmptyEntries);
            var appNames   = appEntries.Select(x =>
            {
                var i = x.IndexOf('|');
                if (i <= 0)
                {
                    return(null);
                }
                return(new { name = x.Substring(0, i), version = x.Substring(i + 1) });
            }).Where(x => x != null);

            foreach (var appName in appNames)
            {
                var info = StartProcessAndReadOutput(ChocoLocation, "info -l -nocolor -y -v " + appName.name);
                var kvps = ExtractPackageInformation(info);
                if (kvps.Count == 0)
                {
                    continue;
                }

                var entry = new ApplicationUninstallerEntry();

                AddInfo(entry, kvps, "Title", (e, s) => e.RawDisplayName = s);

                entry.DisplayVersion  = appName.version;
                entry.RatingId        = "Choco " + appName.name;
                entry.UninstallerKind = UninstallerType.Chocolatey;

                AddInfo(entry, kvps, "Summary", (e, s) => e.Comment = s);
                if (string.IsNullOrEmpty(entry.Comment))
                {
                    AddInfo(entry, kvps, "Description", (e, s) => e.Comment = s);
                    if (string.IsNullOrEmpty(entry.Comment))
                    {
                        AddInfo(entry, kvps, "Tags", (e, s) => e.Comment = s);
                    }
                }

                AddInfo(entry, kvps, "Documentation", (e, s) => e.AboutUrl = s);
                if (string.IsNullOrEmpty(entry.AboutUrl))
                {
                    AddInfo(entry, kvps, "Software Site", (e, s) => e.AboutUrl = s);
                    if (string.IsNullOrEmpty(entry.AboutUrl))
                    {
                        AddInfo(entry, kvps, "Chocolatey Package Source", (e, s) => e.AboutUrl = s);
                    }
                }

                var psc = new ProcessStartCommand(ChocoLocation, $"uninstall {appName.name} -y -r");

                entry.UninstallString = psc.ToString();

                // Prevent chocolatey from trying to run the original uninstaller (it's deleted by now), only remove the package
                psc.Arguments += " -n --skipautouninstaller";
                var junk = new Junk.Containers.RunProcessJunk(entry, null, psc, Localisation.ChocolateyFactory_UninstallInChocolateyJunkName);
                junk.Confidence.Add(Junk.Confidence.ConfidenceRecords.ExplicitConnection);
                entry.AdditionalJunk.Add(junk);

                yield return(entry);
            }
        }
        private static ApplicationUninstallerEntry GetOneDrive()
        {
            var result = new ApplicationUninstallerEntry();

            // Check if installed
            try
            {
                using (var key = RegistryTools.OpenRegistryKey(@"HKEY_CURRENT_USER\SOFTWARE\Microsoft\OneDrive", false))
                {
                    result.RegistryPath    = key.Name;
                    result.RegistryKeyName = key.GetKeyName();

                    result.InstallLocation = key.GetValue("CurrentVersionPath") as string;
                    if (result.InstallLocation == null || !Directory.Exists(result.InstallLocation))
                    {
                        return(null);
                    }

                    result.DisplayIcon    = key.GetValue("OneDriveTrigger") as string;
                    result.DisplayVersion = ApplicationEntryTools.CleanupDisplayVersion(key.GetValue("Version") as string);
                }
            }
            catch
            {
                return(null);
            }

            // Check if the uninstaller is available
            var systemRoot    = WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_WINDOWS);
            var uninstallPath = Path.Combine(systemRoot, @"System32\OneDriveSetup.exe");

            if (!File.Exists(uninstallPath))
            {
                uninstallPath = Path.Combine(systemRoot, @"SysWOW64\OneDriveSetup.exe");
                if (!File.Exists(uninstallPath))
                {
                    uninstallPath = null;
                }
            }

            if (uninstallPath != null)
            {
                result.IsValid              = true;
                result.UninstallString      = $"\"{uninstallPath}\" /uninstall";
                result.QuietUninstallString = result.UninstallString;
                if (!File.Exists(result.DisplayIcon))
                {
                    result.DisplayIcon = uninstallPath;
                }
            }

            result.AboutUrl       = @"https://onedrive.live.com/";
            result.RawDisplayName = "OneDrive";
            result.Publisher      = "Microsoft Corporation";
            result.EstimatedSize  = FileSize.FromKilobytes(1024 * 90);
            result.Is64Bit        = MachineType.X86;
            result.IsRegistered   = true;

            result.UninstallerKind = UninstallerType.Unknown;

            result.InstallDate = Directory.GetCreationTime(result.InstallLocation);

            if (!string.IsNullOrEmpty(result.DisplayIcon))
            {
                result.IconBitmap = UninstallToolsGlobalConfig.TryExtractAssociatedIcon(result.DisplayIcon);
            }

            return(result);
        }
Example #23
0
 private static string GetFullName(ApplicationUninstallerEntry entry)
 {
     return(entry.DisplayName);
 }
 public static IEnumerable <ConfidenceRecord> GenerateConfidence(string itemName, ApplicationUninstallerEntry applicationUninstallerEntry)
 {
     return(GenerateConfidence(itemName, null, 0, applicationUninstallerEntry));
 }
        private static bool CheckAreEntriesRelated(ApplicationUninstallerEntry baseEntry, ApplicationUninstallerEntry otherEntry)
        {
            if (PathTools.PathsEqual(baseEntry.InstallLocation, otherEntry.InstallLocation))
            {
                return(true);
            }

            if (!string.IsNullOrEmpty(baseEntry.UninstallerLocation) && (!string.IsNullOrEmpty(otherEntry.InstallLocation) &&
                                                                         baseEntry.UninstallerLocation.StartsWith(otherEntry.InstallLocation, StringComparison.InvariantCultureIgnoreCase)))
            {
                return(true);
            }

            if (!string.IsNullOrEmpty(baseEntry.UninstallString) && !string.IsNullOrEmpty(otherEntry.InstallLocation) &&
                baseEntry.UninstallString.Contains(otherEntry.InstallLocation))
            {
                return(true);
            }

            if (CompareStrings(baseEntry.Publisher, otherEntry.Publisher))
            {
                if (CompareStrings(baseEntry.DisplayName, otherEntry.DisplayName))
                {
                    return(true);
                }
                if (CompareStrings(baseEntry.DisplayNameTrimmed, otherEntry.DisplayNameTrimmed))
                {
                    return(true);
                }
                try
                {
                    if (CompareStrings(baseEntry.DisplayNameTrimmed, Path.GetFileName(otherEntry.InstallLocation)))
                    {
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    Debug.Fail(ex.Message);
                }
            }

            return(false);
        }
        internal static IEnumerable <ConfidenceRecord> GenerateConfidence(string itemName, string itemParentPath, int level, ApplicationUninstallerEntry applicationUninstallerEntry)
        {
            var matchResult = MatchStringToProductName(applicationUninstallerEntry, itemName);

            return(GenerateConfidence(itemName, matchResult, itemParentPath, level, applicationUninstallerEntry));
        }
Example #27
0
        public override string CategoryName => Localisation.Junk_Clsid_GroupName; // "COM Objects";

        public override IEnumerable <IJunkResult> FindJunk(ApplicationUninstallerEntry target)
        {
            if (string.IsNullOrEmpty(target.InstallLocation))
            {
                yield break;
            }

            try
            {
                if (UninstallToolsGlobalConfig.IsSystemDirectory(target.InstallLocation))
                {
                    yield break;
                }
            }
            catch (ArgumentException ex) { Console.WriteLine(ex); }

            foreach (var comEntry in _comEntries.Where(x => PathTools.SubPathIsInsideBasePath(target.InstallLocation, x.FullFilename, true)))
            {
                foreach (var interfacePath in comEntry.InterfaceNames)
                {
                    using (var interfaceKey = RegistryTools.OpenRegistryKey(interfacePath, false, true))
                    {
                        if (interfaceKey != null)
                        {
                            yield return(JunkFromKey(target, interfaceKey));
                        }
                    }
                }

                foreach (var classesKeyPath in _classesKeys)
                {
                    using (var classesKey = RegistryTools.OpenRegistryKey(classesKeyPath, false, true))
                    {
                        if (classesKey == null)
                        {
                            continue;
                        }

                        foreach (var targetSubKeyPath in new[]
                        {
                            Path.Combine("CLSID", comEntry.Guid),
                            Path.Combine("TypeLib", comEntry.Guid),
                            comEntry.ProgId,
                            comEntry.VersionIndependentProgId
                        })
                        {
                            if (targetSubKeyPath != null)
                            {
                                var result = TryGetFromPath(target, classesKey, targetSubKeyPath);
                                if (result != null)
                                {
                                    yield return(result);
                                }
                            }
                        }

                        foreach (var extensionKeyName in GetExtensionNames(classesKeyPath))
                        {
                            using (var extensionKey = classesKey.OpenSubKey(extensionKeyName))
                            {
                                if (extensionKey == null)
                                {
                                    continue;
                                }

                                // Contains subkeys with default values containing class guids of the extensions
                                using (var shellExKey = extensionKey.OpenSubKey("ShellEx"))
                                {
                                    if (shellExKey != null)
                                    {
                                        foreach (var shellSubKeyName in shellExKey.GetSubKeyNames())
                                        {
                                            using (var shellSubKey = shellExKey.OpenSubKey(shellSubKeyName))
                                            {
                                                if (string.Equals(shellSubKey?.GetValue(null, null) as string, comEntry.Guid, StringComparison.OrdinalIgnoreCase))
                                                {
                                                    yield return(JunkFromKey(target, shellSubKey));
                                                }
                                            }
                                        }
                                    }
                                }

                                // Contains default value pointing to a class guid
                                using (var persistentHandlerKey = extensionKey.OpenSubKey("PersistentHandler"))
                                {
                                    if (string.Equals(persistentHandlerKey?.GetValue(null, null) as string, comEntry.Guid, StringComparison.OrdinalIgnoreCase))
                                    {
                                        yield return(JunkFromKey(target, persistentHandlerKey));
                                    }
                                }

                                if (comEntry.ProgId != null || comEntry.VersionIndependentProgId != null)
                                {
                                    // Contains values with names corresponding to ProgIDs
                                    using (var openWithProgidsKey = extensionKey.OpenSubKey("OpenWithProgIDs"))
                                    {
                                        if (openWithProgidsKey != null)
                                        {
                                            foreach (var progIdName in openWithProgidsKey.GetValueNames())
                                            {
                                                if (string.Equals(progIdName, comEntry.ProgId, StringComparison.OrdinalIgnoreCase) ||
                                                    string.Equals(progIdName, comEntry.VersionIndependentProgId, StringComparison.OrdinalIgnoreCase))
                                                {
                                                    yield return(JunkFromValue(target, openWithProgidsKey.Name, progIdName));
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public IList <ApplicationUninstallerEntry> GetUninstallerEntries(
            ListGenerationProgress.ListGenerationCallback progressCallback)
        {
            var results = new List <ApplicationUninstallerEntry>();

            if (StoreAppHelperPath == null)
            {
                return(results);
            }

            var output = FactoryTools.StartHelperAndReadOutput(StoreAppHelperPath, "/query");

            if (string.IsNullOrEmpty(output))
            {
                return(results);
            }

            var windowsPath = WindowsTools.GetEnvironmentPath(CSIDL.CSIDL_WINDOWS);

            foreach (var data in FactoryTools.ExtractAppDataSetsFromHelperOutput(output))
            {
                if (!data.ContainsKey("InstalledLocation") || !Directory.Exists(data["InstalledLocation"]))
                {
                    continue;
                }

                var fullName     = data["FullName"];
                var uninstallStr = $"\"{StoreAppHelperPath}\" /uninstall \"{fullName}\"";
                var isProtected  = data.ContainsKey("IsProtected") && Convert.ToBoolean(data["IsProtected"], CultureInfo.InvariantCulture);
                var result       = new ApplicationUninstallerEntry
                {
                    Comment              = fullName,
                    CacheIdOverride      = fullName,
                    RatingId             = fullName.Substring(0, fullName.IndexOf("_", StringComparison.Ordinal)),
                    UninstallString      = uninstallStr,
                    QuietUninstallString = uninstallStr,
                    RawDisplayName       = string.IsNullOrEmpty(data["DisplayName"]) ? fullName : data["DisplayName"],
                    Publisher            = data["PublisherDisplayName"],
                    IsValid              = true,
                    UninstallerKind      = UninstallerType.StoreApp,
                    InstallLocation      = data["InstalledLocation"],
                    InstallDate          = Directory.GetCreationTime(data["InstalledLocation"]),
                    IsProtected          = isProtected,
                    SystemComponent      = isProtected
                };

                if (File.Exists(data["Logo"]))
                {
                    try
                    {
                        result.DisplayIcon = data["Logo"];
                        result.IconBitmap  = DrawingTools.IconFromImage(new Bitmap(data["Logo"]));
                    }
                    catch
                    {
                        result.DisplayIcon = null;
                        result.IconBitmap  = null;
                    }
                }

                if (result.InstallLocation.StartsWith(windowsPath, StringComparison.InvariantCultureIgnoreCase))
                {
                    result.SystemComponent = true;
                    //result.IsProtected = true;
                }

                results.Add(result);
            }

            return(results);
        }
Example #29
0
        private static void CreateFromDirectoryHelper(ICollection <ApplicationUninstallerEntry> results,
                                                      DirectoryInfo directory, int level, ICollection <string> dirsToSkip)
        {
            // Level 0 is for the pf folder itself. First subfolder is level 1.
            if (level > 2 || dirsToSkip.Any(x => directory.FullName.Contains(x, StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            // Get contents of this installDir
            AppExecutablesSearcher.ScanDirectoryResult result;

            try
            {
                result = AppExecutablesSearcher.ScanDirectory(directory);
            }
            catch (IOException)
            {
                return;
            }
            catch (UnauthorizedAccessException)
            {
                return;
            }

            // Check if it is potentially dangerous to process this installDir.
            if (result.ExecutableFiles.Count > 40)
            {
                return;
            }

            var anyFiles = result.ExecutableFiles.Any();

            if (!anyFiles && !result.BinSubdirs.Any())
            {
                foreach (var dir in result.OtherSubdirs)
                {
                    CreateFromDirectoryHelper(results, dir, level + 1, dirsToSkip);
                }
            }
            else if (anyFiles)
            {
                var entry = new ApplicationUninstallerEntry();

                // Parse directories into useful information
                if (level > 0 && directory.Name.StartsWithAny(AppExecutablesSearcher.BinaryDirectoryNames, StringComparison.OrdinalIgnoreCase))
                {
                    entry.InstallLocation = directory.Parent?.FullName;
                    entry.RawDisplayName  = directory.Parent?.Name;
                }
                else
                {
                    entry.InstallLocation = directory.FullName;
                    entry.RawDisplayName  = directory.Name;

                    if (level > 0)
                    {
                        entry.Publisher = directory.Parent?.Name;
                    }
                }

                var sorted = AppExecutablesSearcher.SortListExecutables(result.ExecutableFiles, entry.DisplayNameTrimmed).ToArray();
                entry.SortedExecutables = sorted.Select(x => x.FullName).ToArray();

                entry.InstallDate = directory.CreationTime;
                //entry.IconBitmap = TryExtractAssociatedIcon(compareBestMatchFile.FullName);

                // Extract info from file metadata and overwrite old values
                var compareBestMatchFile = sorted.First();
                ExecutableAttributeExtractor.FillInformationFromFileAttribs(entry, compareBestMatchFile.FullName, false);

                results.Add(entry);
            }
        }
        public IList <ApplicationUninstallerEntry> GetUninstallerEntries(
            ListGenerationProgress.ListGenerationCallback progressCallback)
        {
            var results = new List <ApplicationUninstallerEntry>();

            if (ScriptHelperPath == null)
            {
                return(results);
            }

            var result = FactoryTools.StartHelperAndReadOutput(ScriptHelperPath, string.Empty);

            if (string.IsNullOrEmpty(result))
            {
                return(results);
            }

            var dataSets = FactoryTools.ExtractAppDataSetsFromHelperOutput(result);

            foreach (var dataSet in dataSets)
            {
                var entry = new ApplicationUninstallerEntry();

                // Automatically fill in any supplied static properties
                foreach (var entryProp in EntryProps)
                {
                    if (!dataSet.TryGetValue(entryProp.Name, out var item) || string.IsNullOrEmpty(item))
                    {
                        continue;
                    }

                    try
                    {
                        entryProp.SetValue(entry, item, null);
                    }
                    catch (SystemException ex)
                    {
                        Console.WriteLine(ex);
                    }
                }

                if (!entry.UninstallPossible && !entry.QuietUninstallPossible)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(entry.Publisher))
                {
                    entry.Publisher = "Script";
                }

                if (dataSet.TryGetValue("SystemIcon", out var icon) && !string.IsNullOrEmpty(icon))
                {
                    var iconObj = SystemIconProps
                                  .FirstOrDefault(p => p.Name.Equals(icon, StringComparison.OrdinalIgnoreCase))
                                  ?.GetValue(null, null) as Icon;
                    entry.IconBitmap = iconObj;
                }

                results.Add(entry);
            }

            return(results);
        }