Ejemplo n.º 1
0
        public void CanReadSymlink()
        {
            var context = new Context
            {
                SuperBlock = new SuperBlock(),
                Options    = new XfsFileSystemOptions {
                    FileNameEncoding = Encoding.UTF8
                }
            };

            var inode = new Inode(1, context);

            inode.ReadFrom(GetInodeBuffer(), 0);

            var symlink = new Symlink(context, inode);

            Assert.Equal("init.d", symlink.TargetPath);


            inode = new Inode(1, context);
            var inodeBuffer = GetInodeBuffer();

            inodeBuffer[0x6C] = 60; //garbage after first null byte
            inode.ReadFrom(inodeBuffer, 0);

            symlink = new Symlink(context, inode);
            Assert.Equal("init.d", symlink.TargetPath);
        }
        public bool IsUnderSymbolicLink(string path)
        {
            if (path.Contains("*"))
            {
                return(false);
            }

            var fullPath = Path.Combine(BasePath, path);

            if (symPaths.Any(s => path.StartsWith(fullPath)))
            {
                return(true);
            }

            var symPath = Symlink.IsUnderSymbolicLink(path, BasePath);

            if (symPath != null)
            {
                symPaths.Add(symPath);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 3
0
        static void UnlinkDirectory(DirectoryInfo directory)
        {
            var link = Symlink.FromPath(directory.FullName);

            if (link.Exists)
            {
                link.Delete();
            }
        }
Ejemplo n.º 4
0
        private static bool AutoInstallService(string path)
        {
            if (!File.Exists(path))
            {
                return(false);
            }

            var root = PackageManagerSettings.CoAppRootDirectory;
            var coappBinDirectory = Path.Combine(root, "bin");

            if (!Directory.Exists(coappBinDirectory))
            {
                Directory.CreateDirectory(coappBinDirectory);
            }
            var canonicalServiceExePath = Path.Combine(coappBinDirectory, "coapp.service.exe");

            if (Symlink.IsSymlink(path))
            {
                // we found a symlink,
                if (!File.Exists(Symlink.GetActualPath(path)))
                {
                    // it is invalid anyway. trash it, try again.
                    Symlink.DeleteSymlink(path);
                }
                return(false);
            }

            try {
                Symlink.MakeFileLink(canonicalServiceExePath, path);

                // hey we found one where it's supposed to be!
                var processStartInfo = new ProcessStartInfo(canonicalServiceExePath)
                {
                    Arguments       = "--start",
                    CreateNoWindow  = true,
                    WindowStyle     = ProcessWindowStyle.Hidden,
                    UseShellExecute = false,
                };

                var process = Process.Start(processStartInfo);
                process.WaitForExit();

                // after it exits, lets see if we've got an installed service
                if (EngineServiceManager.IsServiceInstalled)
                {
                    // YAY!. We're outta here!
                    EngineServiceManager.TryToStartService();
                    return(true);
                }
            } catch {
                // hmm. not working...
            }
            return(false);
        }
Ejemplo n.º 5
0
        static void LinkDirectory(DirectoryInfo directory, string destination)
        {
            var link = Symlink.FromPath(directory.FullName);

            if (link.Exists)
            {
                link.DestinationPath = destination;
            }
            else
            {
                if (directory.Exists)
                {
                    directory.Delete(true);
                }
                link.Create(destination);
            }
        }
Ejemplo n.º 6
0
        internal static void EnsureCanonicalFoldersArePresent()
        {
            var root = PackageManagerSettings.CoAppRootDirectory;
            // try to make a convenience symlink:  %SYSTEMDRIVE%:\apps
            var appsdir = "{0}:\\apps".format(root[0]);

            if (!Directory.Exists(appsdir) && !File.Exists(appsdir))
            {
                Symlink.MakeDirectoryLink("{0}:\\apps".format(root[0]), root);
            }

            var pathext = EnvironmentUtility.GetSystemEnvironmentVariable("PATHEXT");

            if (pathext.IndexOf(".lnk", StringComparison.CurrentCultureIgnoreCase) == -1)
            {
                EnvironmentUtility.SetSystemEnvironmentVariable("PATHEXT", pathext + ";.lnk");
            }

            foreach (var path in CanonicalFolders.Select(folder => Path.Combine(root, folder)).Where(path => !Directory.Exists(path)))
            {
                Directory.CreateDirectory(path);
            }

            // make sure system paths are updated.
            var binPath = Path.Combine(root, "bin");
            var psPath  = Path.Combine(root, "powershell");

            if (!EnvironmentUtility.SystemPath.Contains(binPath))
            {
                EnvironmentUtility.SystemPath = EnvironmentUtility.SystemPath.Prepend(binPath);
            }
            if (!EnvironmentUtility.PowershellModulePath.Contains(psPath))
            {
                EnvironmentUtility.PowershellModulePath = EnvironmentUtility.PowershellModulePath.Prepend(psPath);
            }

            EnvironmentUtility.BroadcastChange();
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            // Initialize the wrapper library.
            var symLinkLib = new Symlink();

            // Here I'm using an example path.
            if (symLinkLib.Environment.Create("C:/ExampleSymlinkPath", "C:/Users/Public"))
            {
                // Success.
                Console.WriteLine("The symlink was successful");
                Environment.Exit(0);
            }
            else
            {
                // Get the error code
                var errorVal = Marshal.GetLastWin32Error();

                // Failure.
                Console.WriteLine("The symlink has failed.");
                Console.WriteLine("Marshal Error: {0} ({1})", errorVal, MarshalDecoder(errorVal));
                Environment.Exit(1);
            }
        }
Ejemplo n.º 8
0
        public static void Extract(string archive, string target)
        {
            const bool overwrite = true;

            void WriteSymbolicLink(string symlink, string pointTo)
            {
                if (Path.IsPathRooted(pointTo))
                {
                    throw new UnauthorizedAccessException();
                }
                pointTo = Path.Combine(Path.GetDirectoryName(symlink), pointTo);
                pointTo = Path.GetFullPath(pointTo);

                if (!PathEx.IsNested(target, symlink))
                {
                    throw new UnauthorizedAccessException();
                }

                if (overwrite)
                {
                    if (File.Exists(symlink))
                    {
                        File.Delete(symlink);
                    }
                    if (Directory.Exists(symlink))
                    {
                        Directory.Delete(symlink);
                    }
                }

                if (File.Exists(pointTo))
                {
                    Symlink.CreateForFile(filePath: pointTo, symlink: symlink);
                }
                else if (Directory.Exists(pointTo))
                {
                    Symlink.CreateForDirectory(directoryPath: pointTo, symlink: symlink);
                }
                else
                {
                    Directory.CreateDirectory(pointTo);
                    try {
                        Symlink.CreateForDirectory(directoryPath: pointTo, symlink: symlink);
                    } finally {
                        Directory.Delete(pointTo);
                    }
                }
            }

            var options = new ExtractionOptions {
                ExtractFullPath   = true,
                Overwrite         = overwrite,
                WriteSymbolicLink = WriteSymbolicLink,
            };

            using var stream = File.OpenRead(archive);
            using var reader = ReaderFactory.Open(stream);
            while (reader.MoveToNextEntry())
            {
                if (reader.Entry.IsDirectory)
                {
                    continue;
                }

                reader.WriteEntryToDirectory(target, options);
            }
        }
Ejemplo n.º 9
0
        private void btnPickFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                Filter = "Icons (*.exe;*.ico;*.dll;*.lnk)|*.exe;*.ico;*.dll;*.lnk|All files (*.*)|*.*",
                //DereferenceLinks = true, // This thing doesn't work sadly, idk why
                Title = "Pick an icon (.ico) or a file containing an icon (.exe, .dll)"
            })
            {
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);

                    // Dereference link cause MS can't make it work on OpenFileDialog
                    if (fileInfo.Extension == ".lnk")
                    {
                        iconPickerDialog.FileName = Symlink.ResolveShortcut(fileInfo.FullName);
                    }
                    else
                    {
                        iconPickerDialog.FileName = fileInfo.FullName;
                    }

                    if (iconPickerDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        var fileName = iconPickerDialog.FileName;
                        var index    = iconPickerDialog.IconIndex;

                        // Set FileName to further retrieve it
                        FileName = Path.GetFileNameWithoutExtension(fileName);

                        Icon   icon       = null;
                        Icon[] splitIcons = null;
                        try
                        {
                            if (Path.GetExtension(iconPickerDialog.FileName).ToLower() == ".ico")
                            {
                                icon = new Icon(iconPickerDialog.FileName);
                            }
                            else
                            {
                                var extractor = new IconExtractor(fileName);
                                icon = extractor.GetIcon(index);
                            }

                            splitIcons = IconUtil.Split(icon);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }

                        txtFileName.Text = string.Format("{0}, #{1}, {2} variations", fileName, index, splitIcons.Length);

                        // Update icons.

                        Icon = icon;
                        icon.Dispose();

                        lvwIcons.BeginUpdate();
                        ClearAllIcons();

                        foreach (var i in splitIcons)
                        {
                            // Exclude all icons which size is > 256 (Throw "Generic GDI+ error" when converting if size > 128x128)
                            if (i.Width > 128 || i.Height > 128)
                            {
                                continue;
                            }

                            var item = new IconListViewItem();
                            var size = i.Size;
                            var bits = IconUtil.GetBitCount(i);
                            item.ToolTipText = string.Format("{0}x{1}, {2} bits", size.Width, size.Height, bits);
                            item.Bitmap      = IconUtil.ToBitmap(i);
                            i.Dispose();

                            lvwIcons.Items.Add(item);
                        }

                        lvwIcons.EndUpdate();
                    }
                    else if (firstOpen)
                    {
                        DialogResult = DialogResult.Cancel;
                        this.Hide();
                    }
                }
            }
        }
Ejemplo n.º 10
0
 public SymlinkRequest(string containerName, Symlink link)
     : base(containerName)
 {
     this.link = link.Link;
     SetCustomHeaders(link.GetHeaders());
 }
Ejemplo n.º 11
0
        /// <summary>
        ///   Mains this instance.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private Task Main()
        {
            if (IsRunning)
            {
                return(_engineTask);
            }
            Signals.EngineStartupStatus = 0;

            if (!IsInteractive)
            {
                EngineServiceManager.EnsureServiceAclsCorrect();
            }

            var npmi = PackageManagerImpl.Instance;

            _cancellationTokenSource = new CancellationTokenSource();
            _isRunning = true;

            Signals.StartingUp = true;
            // make sure coapp is properly set up.
            Task.Factory.StartNew(() => {
                try {
                    Logger.Warning("CoApp Startup Beginning------------------------------------------");

                    // this ensures that composition rules are run for toolkit.
                    Signals.EngineStartupStatus = 5;
                    EnsureCanonicalFoldersArePresent();
                    Signals.EngineStartupStatus = 10;
                    var v = Package.GetCurrentPackageVersion(CanonicalName.CoAppItself);
                    if (v > 0)
                    {
                        var p = InstalledPackageFeed.Instance.FindPackages(CanonicalName.CoAppItself).HighestPackages().FirstOrDefault();
                        if (p != null)
                        {
                            p.DoPackageComposition();
                            // put the coapp.exe symlink right into the OS directory. Yeah, evil, .... what are ya gonna do about that?
                            var coappexe = Path.Combine(p.PackageDirectory, "coapp.exe");
                            if (File.Exists(coappexe))
                            {
                                Symlink.MakeFileLink(Path.Combine(Environment.GetEnvironmentVariable("SYSTEMROOT") ?? "c:\\windows", "coapp.exe"), coappexe);
                            }
                        }
                    }
                    Signals.EngineStartupStatus = 95;
                    Logger.Warning("CoApp Version : " + v);

                    /*
                     * what can we do if the right version isn't here?
                     *
                     * FourPartVersion thisVersion = Assembly.GetExecutingAssembly().Version();
                     * if( thisVersion > v ) {
                     *
                     * }
                     * */

                    // Completes startup.

                    Signals.EngineStartupStatus = 100;
                    Signals.Available           = true;
                    Logger.Warning("CoApp Startup Finished------------------------------------------");
                } catch (Exception e) {
                    Logger.Error(e);
                    RequestStop();
                }
            });

            _engineTask = Task.Factory.StartNew(() => {
                _pipeSecurity = new PipeSecurity();
                _pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
                _pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));

                // start a few listeners by default--each listener will also spawn a new empty one.
                StartListener();
                StartListener();
            }, _cancellationTokenSource.Token).AutoManage();

            _engineTask = _engineTask.ContinueWith(antecedent => {
                RequestStop();
                // ensure the sessions are all getting closed.
                Session.CancelAll();
                _engineTask = null;
            }, TaskContinuationOptions.AttachedToParent).AutoManage();
            return(_engineTask);
        }
Ejemplo n.º 12
0
        private bool ApplyRule(CompositionRule rule)
        {
            switch (rule.Action)
            {
            case CompositionAction.DownloadFile:
                if (!File.Exists(rule.Destination))
                {
                    PackageSessionData.DownloadFile(rule.Source, rule.Destination);
                }
                return(true);

            case CompositionAction.InstallCommand:
                return(ExecuteCommand(rule.Source, rule.Destination));

            case CompositionAction.RemoveCommand:
                // we never 'apply' remove commands. Just remove em'
                return(true);

            case CompositionAction.FileCopy:
                // file copy operations may only manipulate files in the package directory.
                if (string.IsNullOrEmpty(rule.Source))
                {
                    Logger.Error("ERROR: Illegal file copy rule. Source must be in package directory [{0}] => [{1}]", rule.Source, rule.Destination);
                    return(false);
                }

                if (string.IsNullOrEmpty(rule.Destination))
                {
                    Logger.Error("ERROR: Illegal file copy rule. Destination must be in package directory [{0}] => [{1}]", rule.Source, rule.Destination);
                    return(false);
                }

                if (!File.Exists(rule.Source))
                {
                    Logger.Error("ERROR: Illegal file copy rule. Source file does not exist [{0}] => [{1}]", rule.Source, rule.Destination);
                    return(false);
                }
                try {
                    var destParent = Path.GetDirectoryName(rule.Destination);
                    if (!string.IsNullOrEmpty(destParent))
                    {
                        if (!Directory.Exists(destParent))
                        {
                            Directory.CreateDirectory(destParent);
                        }
                        File.Copy(rule.Source, rule.Destination, true);
                    }
                }
                catch (Exception e) {
                    Logger.Error(e);
                }
                return(true);

            case CompositionAction.FileRewrite:
                // file copy operations may only manipulate files in the package directory.
                if (string.IsNullOrEmpty(rule.Source))
                {
                    Logger.Error("ERROR: Illegal file rewrite rule. Source must be in package directory [{0}] => [{1}]", rule.Source, rule.Destination);
                    return(false);
                }

                if (string.IsNullOrEmpty(rule.Destination))
                {
                    Logger.Error("ERROR: Illegal file rewrite rule. Destination must be in package directory [{0}] => [{1}]", rule.Source, rule.Destination);
                    return(false);
                }

                if (!File.Exists(rule.Source))
                {
                    Logger.Error("ERROR: Illegal file rewrite rule. Source file does not exist [{0}] => [{1}]", rule.Source, rule.Destination);
                    return(false);
                }
                File.WriteAllText(rule.Destination, ResolveVariables(File.ReadAllText(rule.Source)));
                return(true);

            case CompositionAction.SymlinkFile:
                if (string.IsNullOrEmpty(rule.Destination))
                {
                    Logger.Error("ERROR: Illegal file symlink rule. Destination location '{0}' must be a subpath of apps dir", rule.Destination);
                    return(false);
                }

                if (string.IsNullOrEmpty(rule.Source))
                {
                    Logger.Error("ERROR: Illegal file symlink rule. Source file '{0}' must be a subpath of package directory", rule.Source);
                    return(false);
                }

                if (!File.Exists(rule.Source))
                {
                    Logger.Error("ERROR: Illegal folder symlink rule. Source file '{0}' does not exist.", rule.Source);
                    return(false);
                }

                var parentDir = Path.GetDirectoryName(rule.Destination);
                if (!string.IsNullOrEmpty(parentDir))
                {
                    if (!Directory.Exists(parentDir))
                    {
                        Directory.CreateDirectory(parentDir);
                    }
                    try {
                        // Logger.Message("Creating file Symlink [{0}] => [{1}]", rule.Destination, rule.Source);
                        Symlink.MakeFileLink(rule.Destination, rule.Source);
                    }
                    catch (Exception) {
                        Logger.Error("Warning: File Symlink Link Failed. [{0}] => [{1}]", rule.Destination, rule.Source);
                    }
                }
                return(true);

            case CompositionAction.SymlinkFolder:
                if (string.IsNullOrEmpty(rule.Destination))
                {
                    Logger.Error("ERROR: Illegal folder symlink rule. Destination location '{0}' must be a subpath of appsdir", rule.Destination);
                    return(false);
                }

                if (string.IsNullOrEmpty(rule.Source))
                {
                    Logger.Error("ERROR: Illegal folder symlink rule. Source folder '{0}' must be a subpath of package directory{1}", rule.Source);
                    return(false);
                }

                if (!Directory.Exists(rule.Source))
                {
                    Logger.Error("ERROR: Illegal folder symlink rule. Source folder '{0}' does not exist.", rule.Source);
                    return(false);
                }

                try {
                    // Logger.Message("Creatign Directory Symlink [{0}] => [{1}]", rule.Destination, rule.Source);
                    Symlink.MakeDirectoryLink(rule.Destination, rule.Source);
                }
                catch (Exception) {
                    Logger.Error("Warning: Directory Symlink Link Failed. [{0}] => [{1}]", rule.Destination, rule.Source);
                    return(false);
                }
                return(true);

            case CompositionAction.Shortcut:
                if (string.IsNullOrEmpty(rule.Source))
                {
                    Logger.Error("ERROR: Illegal shortcut rule. Source file '{0}' must be a subpath of package directory", rule.Source);
                    return(false);
                }

                if (!File.Exists(rule.Source))
                {
                    Logger.Error("ERROR: Illegal shortcut rule. Source file '{0}' does not exist.", rule.Source);
                    return(false);
                }

                var pDir = Path.GetDirectoryName(rule.Destination);
                if (!string.IsNullOrEmpty(pDir))
                {
                    if (!Directory.Exists(pDir))
                    {
                        Directory.CreateDirectory(pDir);
                    }
                    // Logger.Message("Creating Shortcut [{0}] => [{1}]", rule.Destination, rule.Source);
                    ShellLink.CreateShortcut(rule.Destination, rule.Source, workingDirectory: "");
                }

                return(true);

            case CompositionAction.EnvironmentVariable:
                switch (rule.Key.ToLower())
                {
                case "path":
                case "pathext":
                case "psmodulepath":
                case "comspec":
                case "temp":
                case "tmp":
                case "username":
                case "windir":
                case "allusersprofile":
                case "appdata":
                case "commonprogramfiles":
                case "commonprogramfiles(x86)":
                case "commonprogramw6432":
                case "computername":
                case "current_cpu":
                case "FrameworkVersion":
                case "homedrive":
                case "homepath":
                case "logonserver":
                case "number_of_processors":
                case "os":
                case "processor_architecture":
                case "processor_identifier":
                case "processor_level":
                case "processor_revision":
                case "programdata":
                case "programfiles":
                case "programfiles(x86)":
                case "programw6432":
                case "prompt":
                case "public":
                case "systemdrive":
                case "systemroot":
                case "userdomain":
                case "userprofile":
                    Logger.Warning("Package may not set environment variable '{0}'", rule.Key);
                    return(true);

                default:
                    EnvironmentUtility.SetSystemEnvironmentVariable(rule.Key, rule.Value);
                    return(true);
                }


            case CompositionAction.Registry:
                if (CanonicalName.Architecture == Architecture.x64 && Environment.Is64BitOperatingSystem)
                {
                    RegistryView.System["SOFTWARE"][rule.Key].StringValue = rule.Value;
                }
                else
                {
                    RegistryView.System["SOFTWARE\\Wow6432Node"][rule.Key].StringValue = rule.Value;
                }
                return(true);
            }
            return(true);
        }
Ejemplo n.º 13
0
        internal void UndoPackageComposition()
        {
            var rulesThatISuperceed = InstalledPackageFeed.Instance.FindPackages(CanonicalName.AllPackages)
                                      .Except(this.SingleItemAsEnumerable())
                                      .OrderBy(each => each, new Toolkit.Extensions.Comparer <Package>((packageA, packageB) => GeneralPackageSettings.Instance.WhoWins(packageA, packageB)))
                                      .Where(WinsVersus)
                                      .SelectMany(package => package.ResolvedRules.Select(rule => new { package, rule }))
                                      .WhereDistinct(each => each.rule.Destination)
                                      .ToArray();

            var rulesThatSuperceedMine = InstalledPackageFeed.Instance.FindPackages(CanonicalName.AllPackages).Where(package => !WinsVersus(package)).SelectMany(package => package.ResolvedRules).ToArray();

            foreach (var rule in ResolvedRules)
            {
                // there are three possibilities
                if (rule.Action == CompositionAction.DownloadFile || rule.Action == CompositionAction.InstallCommand)
                {
                    //skip these types of rules.
                    continue;
                }

                // never supercede RemoveCommand.
                if (rule.Action != CompositionAction.RemoveCommand)
                {
                    // 1. my rule was already superceded by another rule: do nothing.
                    if (rulesThatSuperceedMine.Any(each => each.Destination.Equals(rule.Destination, StringComparison.CurrentCultureIgnoreCase)))
                    {
                        continue;
                    }

                    // 2. my rule was superceding another: run that rule.
                    var runRule = rulesThatISuperceed.FirstOrDefault(each => each.rule.Destination.Equals(rule.Destination, StringComparison.CurrentCultureIgnoreCase));
                    if (runRule != null)
                    {
                        runRule.package.ApplyRule(runRule.rule);
                        continue;
                    }
                }

                // 3. my rule should be the current rule, let's undo it.
                switch (rule.Action)
                {
                case CompositionAction.Shortcut:
                    if (ShellLink.PointsTo(rule.Destination, rule.Source))
                    {
                        rule.Destination.TryHardToDelete();
                    }
                    break;

                case CompositionAction.SymlinkFile:
                    if (File.Exists(rule.Destination) && Symlink.IsSymlink(rule.Destination) && Symlink.GetActualPath(rule.Destination).Equals(rule.Source))
                    {
                        Symlink.DeleteSymlink(rule.Destination);
                    }
                    break;

                case CompositionAction.SymlinkFolder:
                    if (Symlink.IsSymlink(rule.Destination) && Symlink.GetActualPath(rule.Destination).Equals(rule.Source))
                    {
                        Symlink.DeleteSymlink(rule.Destination);
                    }
                    break;

                case CompositionAction.Registry:
                    if (CanonicalName.Architecture == Architecture.x64 && Environment.Is64BitOperatingSystem)
                    {
                        RegistryView.System["SOFTWARE"][rule.Key].StringValue = null;
                    }
                    else
                    {
                        RegistryView.System["SOFTWARE\\Wow6432Node"][rule.Key].StringValue = null;
                    }
                    break;

                case CompositionAction.EnvironmentVariable:
                    // not implemented yet.
                    break;

                case CompositionAction.RemoveCommand:
                    ExecuteCommand(rule.Source, rule.Destination);
                    break;
                }
            }
        }
Ejemplo n.º 14
0
        public static void Start()
        {
            try {
                MessageText     = "It will be just a moment while we \r\nremove old versions of the\r\nCoApp Package Manager.";
                StatusText      = "Status: Shutting down CoApp Service";
                OverallProgress = 5;
                OnPropertyChanged();


                var tsk = Task.Factory.StartNew(FilesystemExtensions.RemoveTemporaryFiles);

                // try to gracefully kill coapp.service
                try {
                    var psi = new ProcessStartInfo {
                        FileName    = "sc.exe",
                        Arguments   = @"stop  ""CoApp Package Installer Service""",
                        WindowStyle = ProcessWindowStyle.Hidden
                    };
                    var p = Process.Start(psi);
                    p.WaitForExit();
                } catch {
                    // it's ok.
                }

                // try to gracefully kill coapp.service ( new )
                try {
                    var psi = new ProcessStartInfo {
                        FileName    = "sc.exe",
                        Arguments   = @"stop  ""CoApp""",
                        WindowStyle = ProcessWindowStyle.Hidden
                    };
                    var p = Process.Start(psi);
                    p.WaitForExit();
                }
                catch {
                    // it's ok.
                }

                // let's just kill the processes if they exist
                var serviceProcs = Process.GetProcessesByName("CoApp.Service");
                if (serviceProcs.Any())
                {
                    foreach (var proc in serviceProcs)
                    {
                        try {
                            proc.Kill();
                        } catch {
                            // it's ok.
                        }
                    }
                }

                StatusText      = "Status: Removing Service";
                OverallProgress = 10;
                OnPropertyChanged();
                // remove service if it exists
                try {
                    var psi = new ProcessStartInfo {
                        FileName    = "sc.exe",
                        Arguments   = @"delete  ""CoApp Package Installer Service""",
                        WindowStyle = ProcessWindowStyle.Hidden
                    };
                    var p = Process.Start(psi);
                    p.WaitForExit();
                } catch {
                    // it's ok.
                }

                try {
                    var psi = new ProcessStartInfo {
                        FileName    = "sc.exe",
                        Arguments   = @"delete  ""CoApp""",
                        WindowStyle = ProcessWindowStyle.Hidden
                    };
                    var p = Process.Start(psi);
                    p.WaitForExit();
                }
                catch {
                    // it's ok.
                }

                MsiSetInternalUI(2, IntPtr.Zero);
                MsiSetExternalUI((context, messageType, message) => 1, 0x400, IntPtr.Zero);

                StatusText      = "Status: Finding installed packages.";
                OverallProgress = 15;
                OnPropertyChanged();

                var installedMSIs = GetInstalledCoAppMSIs().ToArray();
                StatusText      = string.Format("Status: Found {0} installed packages.", installedMSIs.Length);
                OverallProgress = 20;
                OnPropertyChanged();



                // Remove CoApp toolkit MSIs
                var toolkits = installedMSIs.Where(each => (each.ProductName.Equals("CoApp.Toolkit", StringComparison.InvariantCultureIgnoreCase) || each.ProductName.Equals("CoApp", StringComparison.InvariantCultureIgnoreCase)) && each.Manufacturer.Equals("OUTERCURVE FOUNDATION", StringComparison.CurrentCultureIgnoreCase)).ToArray();

                if (toolkits.Any())
                {
                    StatusText      = "Status: Removing CoApp Toolkit.";
                    OverallProgress = 25;
                    OnPropertyChanged();

                    foreach (var pkg in toolkits)
                    {
                        OverallProgress++;
                        OnPropertyChanged();

                        MsiInstallProduct(pkg.Path, @"REMOVE=ALL ALLUSERS=1 COAPP=1 COAPP_INSTALLED=1 REBOOT=REALLYSUPPRESS");
                    }
                }

                if (installedMSIs.Any())
                {
                    installedMSIs = GetInstalledCoAppMSIs().ToArray();

                    if (AllPackages && installedMSIs.Any())
                    {
                        var eachProgress = 45 / installedMSIs.Count();
                        StatusText      = "Status: Removing other packages.";
                        OverallProgress = 30;
                        OnPropertyChanged();

                        foreach (var pkg in installedMSIs)
                        {
                            OverallProgress += eachProgress;
                            OnPropertyChanged();

                            MsiInstallProduct(pkg.Path, @"REMOVE=ALL ALLUSERS=1 COAPP=1 COAPP_INSTALLED=1 REBOOT=REALLYSUPPRESS");
                        }
                    }
                }
                //
                // installedMSIs = GetInstalledCoAppMSIs().ToArray();
                // if (!installedMSIs.Any()) {
                StatusText      = "Status: Removing CoApp Folder.";
                OverallProgress = 75;
                OnPropertyChanged();

                // get rid of c:\windows\coapp.exe
                var coappexe = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), "coapp.exe");
                if (File.Exists(coappexe))
                {
                    coappexe.TryHardToDelete();
                }

                // try to get rid of c:\apps
                var apps = String.Format("{0}\\apps", Environment.GetEnvironmentVariable("SystemDrive"));
                if (Symlink.IsSymlink(apps))
                {
                    Symlink.DeleteSymlink(apps);
                }
                else if (Directory.Exists(apps))
                {
                    FilesystemExtensions.TryHardToDelete(String.Format("{0}\\apps", Environment.GetEnvironmentVariable("SystemDrive")));
                }
                // no more packages installed-- remove the c:\apps directory
                var rootFolder = CoAppRootFolder.Value;

                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, ".cache"));
                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "ReferenceAssemblies"));
                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "x86"));
                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "x64"));
                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "bin"));
                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "powershell"));
                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "lib"));
                FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "include"));
                // FilesystemExtensions.TryHardToDelete(Path.Combine(rootFolder, "etc"));

                StatusText      = "Status: Removing Dead Links.";
                OverallProgress = 80;
                OnPropertyChanged();

                FilesystemExtensions.RemoveDeadLnks(rootFolder);

                StatusText      = "Status: Removing Empty Folders.";
                OverallProgress = 81;
                OnPropertyChanged();


                FilesystemExtensions.RemoveEssentiallyEmptyFolders(rootFolder);

                // }

                // clean out the CoApp registry keys
                try {
                    StatusText      = "Status: Removing CoApp Registry Settings.";
                    OverallProgress = 83;
                    OnPropertyChanged();

                    var registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).CreateSubKey(@"Software");
                    if (registryKey != null)
                    {
                        registryKey.DeleteSubKeyTree("CoApp");
                    }
                } catch {
                }

                StatusText      = "Status: Cleaning up Temp Folder.";
                OverallProgress = 85;
                OnPropertyChanged();

                foreach (var f in Directory.EnumerateFiles(FilesystemExtensions.TempPath, "*.msi"))
                {
                    FilesystemExtensions.TryHardToDelete(f);
                }
                OverallProgress = 88;
                OnPropertyChanged();

                foreach (var f in Directory.EnumerateFiles(FilesystemExtensions.TempPath, "*.tmp"))
                {
                    FilesystemExtensions.TryHardToDelete(f);
                }

                OverallProgress = 91;
                OnPropertyChanged();

                foreach (var f in Directory.EnumerateFiles(FilesystemExtensions.TempPath, "*.exe"))
                {
                    FilesystemExtensions.TryHardToDelete(f);
                }
                OverallProgress = 93;
                OnPropertyChanged();

                foreach (var f in Directory.EnumerateFiles(FilesystemExtensions.TempPath, "*.dll"))
                {
                    FilesystemExtensions.TryHardToDelete(f);
                }

                OverallProgress = 95;
                OnPropertyChanged();


                MsiSetExternalUI(null, 0x400, IntPtr.Zero);
                FilesystemExtensions.RemoveTemporaryFiles();

                StatusText      = "Status: Complete";
                OverallProgress = 100;
                OnPropertyChanged();
            } catch {
                // meh.
            }

            Environment.Exit(0);
        }