Пример #1
0
 private void ShowTaskDialog()
 {
     if( TaskDialog.OSSupportsTaskDialogs )
     {
         using( TaskDialog dialog = new TaskDialog() )
         {
             dialog.WindowTitle = "Task dialog sample";
             dialog.MainInstruction = "This is an example task dialog.";
             dialog.Content = "Task dialogs are a more flexible type of message box. Among other things, task dialogs support custom buttons, command links, scroll bars, expandable sections, radio buttons, a check box (useful for e.g. \"don't show this again\"), custom icons, and a footer. Some of those things are demonstrated here.";
             dialog.ExpandedInformation = "Ookii.org's Task Dialog doesn't just provide a wrapper for the native Task Dialog API; it is designed to provide a programming interface that is natural to .Net developers.";
             dialog.Footer = "Task Dialogs support footers and can even include <a href=\"http://www.ookii.org\">hyperlinks</a>.";
             dialog.FooterIcon = TaskDialogIcon.Information;
             dialog.EnableHyperlinks = true;
             TaskDialogButton customButton = new TaskDialogButton("A custom button");
             TaskDialogButton okButton = new TaskDialogButton(ButtonType.Ok);
             TaskDialogButton cancelButton = new TaskDialogButton(ButtonType.Cancel);
             dialog.Buttons.Add(customButton);
             dialog.Buttons.Add(okButton);
             dialog.Buttons.Add(cancelButton);
             dialog.HyperlinkClicked += new EventHandler<HyperlinkClickedEventArgs>(TaskDialog_HyperLinkClicked);
             TaskDialogButton button = dialog.ShowDialog(this);
             if( button == customButton )
                 MessageBox.Show(this, "You clicked the custom button", "Task Dialog Sample");
             else if( button == okButton )
                 MessageBox.Show(this, "You clicked the OK button.", "Task Dialog Sample");
         }
     }
     else
     {
         MessageBox.Show(this, "This operating system does not support task dialogs.", "Task Dialog Sample");
     }
 }
Пример #2
0
        private void WarnAboutPythonSymbols(string moduleName) {
            const string content =
                "Python/native mixed-mode debugging requires symbol files for the Python interpreter that is being debugged. Please add the folder " +
                "containing those symbol files to your symbol search path, and force a reload of symbols for {0}.";

            var dialog = new TaskDialog(_serviceProvider);

            var openSymbolSettings = new TaskDialogButton("Open symbol settings dialog");
            var downloadSymbols = new TaskDialogButton("Download symbols for my interpreter");
            dialog.Buttons.Add(openSymbolSettings);
            dialog.Buttons.Add(downloadSymbols);

            dialog.Buttons.Add(TaskDialogButton.Close);
            dialog.UseCommandLinks = true;
            dialog.Title = "Python Symbols Required";
            dialog.Content = string.Format(content, moduleName);
            dialog.Width = 0;

            dialog.ShowModal();

            if (dialog.SelectedButton == openSymbolSettings) {
                var cmdId = new CommandID(VSConstants.GUID_VSStandardCommandSet97, VSConstants.cmdidToolsOptions);
                _serviceProvider.GlobalInvoke(cmdId,  "1F5E080F-CBD2-459C-8267-39fd83032166");
            } else if (dialog.SelectedButton == downloadSymbols) {
                PythonToolsPackage.OpenWebBrowser(
                    string.Format("http://go.microsoft.com/fwlink/?LinkId=308954&clcid=0x{0:X}", CultureInfo.CurrentCulture.LCID));
            }
        }
Пример #3
0
        private static Result InternalShow(IntPtr parent, string title, string instruction, string content, TaskDialogButton commonButtons, TaskDialogIcon icon)
        {
            int dlgValue;

            try {
                //Get handle for parent window if none specified (behave like MessageBox)
                if (parent == IntPtr.Zero)
                    parent = Native.Windows.GetActiveWindow();

                if (NativeMethods.TaskDialog(parent, IntPtr.Zero, title, instruction, content, (int)commonButtons, new IntPtr((long)icon), out dlgValue) != 0)
                    throw new Exception(String.Format(Resources.ExceptionMessages.NativeCallFailure, "TaskDialog"));
            }
            catch (EntryPointNotFoundException ex) {
                throw new Exception(Resources.ExceptionMessages.CommonControlEntryPointNotFound, ex);
            }
            catch (Exception ex) {
                throw new Exception(Resources.ExceptionMessages.TaskDialogFailure, ex);
            }

            //Convert int value to common dialog result
            if (dlgValue > 0 && dlgValue <= 8)
                return (Result)dlgValue;
            else
                return Result.None;
        }
Пример #4
0
        private bool ShouldIncludeNodeModulesFolderInProject() {
            var includeNodeModulesButton = new TaskDialogButton(Resources.IncludeNodeModulesIncludeTitle, Resources.IncludeNodeModulesIncludeDescription);
            var cancelOperationButton = new TaskDialogButton(Resources.IncludeNodeModulesCancelTitle);
            var taskDialog = new TaskDialog(_project.ProjectMgr.Site) {
                AllowCancellation = true,
                EnableHyperlinks = true,
                Title = SR.ProductName,
                MainIcon = TaskDialogIcon.Warning,
                Content = Resources.IncludeNodeModulesContent,
                Buttons = {
                    cancelOperationButton,
                    includeNodeModulesButton
                },
                FooterIcon = TaskDialogIcon.Information,
                Footer = Resources.IncludeNodeModulesInformation,
                SelectedButton = cancelOperationButton
            };

            var button = taskDialog.ShowModal();

            return button == includeNodeModulesButton;
        }
Пример #5
0
        private void DefaultButton_Click(object sender, RoutedEventArgs e)
        {
            if (TemplateData != null)
            {
                if (TaskDialog.OSSupportsTaskDialogs)
                {
                    using (TaskDialog dialog = new TaskDialog())
                    {
                        dialog.CenterParent = true;
                        dialog.WindowTitle  = "Reset " + TemplateData.Name + " to Default?";
                        dialog.Content      = "Current changes will be lost.";
                        //dialog.ExpandedInformation = "";
                        //dialog.Footer = "Task Dialogs support footers and can even include <a href=\"http://www.ookii.org\">hyperlinks</a>.";
                        dialog.FooterIcon = TaskDialogIcon.Information;
                        dialog.AllowDialogCancellation = true;
                        //dialog.EnableHyperlinks = true;
                        TaskDialogButton okButton     = new TaskDialogButton(ButtonType.Ok);
                        TaskDialogButton cancelButton = new TaskDialogButton(ButtonType.Cancel);
                        dialog.Buttons.Add(okButton);
                        dialog.Buttons.Add(cancelButton);
                        dialog.ButtonStyle = TaskDialogButtonStyle.Standard;

                        //dialog.HyperlinkClicked += new EventHandler<HyperlinkClickedEventArgs>(TaskDialog_HyperLinkClicked);
                        TaskDialogButton button = dialog.ShowDialog(App.Current.MainWindow);
                        if (button == okButton)
                        {
                            TemplateData.SetToDefault();
                        }
                    }
                }
                else
                {
                    TemplateData.SetToDefault();
                }
            }
        }
Пример #6
0
 private void ShowTaskDialog()
 {
     if (TaskDialog.OSSupportsTaskDialogs)
     {
         using (TaskDialog dialog = new TaskDialog())
         {
             dialog.WindowTitle         = "Task dialog sample";
             dialog.MainInstruction     = "This is an example task dialog.";
             dialog.Content             = "Task dialogs are a more flexible type of message box. Among other things, task dialogs support custom buttons, command links, scroll bars, expandable sections, radio buttons, a check box (useful for e.g. \"don't show this again\"), custom icons, and a footer. Some of those things are demonstrated here.";
             dialog.ExpandedInformation = "Ookii.org's Task Dialog doesn't just provide a wrapper for the native Task Dialog API; it is designed to provide a programming interface that is natural to .Net developers.";
             dialog.Footer           = "Task Dialogs support footers and can even include <a href=\"http://www.ookii.org\">hyperlinks</a>.";
             dialog.FooterIcon       = TaskDialogIcon.Information;
             dialog.EnableHyperlinks = true;
             TaskDialogButton customButton = new TaskDialogButton("A custom button");
             TaskDialogButton okButton     = new TaskDialogButton(ButtonType.Ok);
             TaskDialogButton cancelButton = new TaskDialogButton(ButtonType.Cancel);
             dialog.Buttons.Add(customButton);
             dialog.Buttons.Add(okButton);
             dialog.Buttons.Add(cancelButton);
             dialog.HyperlinkClicked += new EventHandler <HyperlinkClickedEventArgs>(TaskDialog_HyperLinkClicked);
             TaskDialogButton button = dialog.ShowDialog(this);
             if (button == customButton)
             {
                 MessageBox.Show(this, "You clicked the custom button", "Task Dialog Sample");
             }
             else if (button == okButton)
             {
                 MessageBox.Show(this, "You clicked the OK button.", "Task Dialog Sample");
             }
         }
     }
     else
     {
         MessageBox.Show(this, "This operating system does not support task dialogs.", "Task Dialog Sample");
     }
 }
Пример #7
0
        public void ProjectFinishedGenerating(Project project) {
            if (project.DTE.SuppressUI) {
                return;
            }

            string description = null;
            try {
                var p = project.Properties.Item("InterpreterDescription");
                if (p != null) {
                    description = p.Value as string;
                }
            } catch (ArgumentException) {
            }

            if (string.IsNullOrEmpty(description)) {
                bool isValid = false;
                try {
                    var p = project.Properties.Item("InterpreterId");
                    isValid = p != null && !string.IsNullOrEmpty(p.Value as string);
                } catch (ArgumentException) {
                }
                if (!isValid) {
                    // We don't have a usable interpreter, so there's no point
                    // going ahead.
                    // Fall out - the user will find what they need when they
                    // try and run or edit, but until then there's no reason to
                    // block them or duplicate all of our help messages into yet
                    // another assembly.
                    return;
                }
            }

            ProjectItem requirementsTxt = null;
            try {
                requirementsTxt = project.ProjectItems.Item("requirements.txt");
            } catch (ArgumentException) {
            }

            if (requirementsTxt == null) {
                return;
            }

            var txt = requirementsTxt.FileNames[0];
            if (!File.Exists(txt)) {
                return;
            }

            var provider = WizardHelpers.GetProvider(project.DTE);
            if (provider == null) {
                return;
            }

            var td = new TaskDialog(provider) {
                Title = string.Format("{0} - {1}", project.Name, Strings.ProductTitle),
                MainInstruction = Strings.InstallRequirementsHeading,
                Content = Strings.InstallRequirementsMessage,
                EnableHyperlinks = true,
                AllowCancellation = true,
            };

            var venv = new TaskDialogButton(
                Strings.InstallRequirementsIntoVirtualEnv,
                Strings.InstallRequirementsIntoVirtualEnvTip
            );
            description = description ?? Strings.DefaultInterpreterDescription;
            var install = new TaskDialogButton(
                string.Format(Strings.InstallRequirementsIntoGlobalEnv, description),
                Strings.InstallRequirementsIntoGlobalEnvTip
            );
            var goAway = new TaskDialogButton(Strings.InstallRequirementsNowhere);
            td.Buttons.Add(venv);
            td.Buttons.Add(install);
            td.Buttons.Add(goAway);

            try {
                td.ExpandedInformation = File.ReadAllText(txt);
                td.CollapsedControlText = Strings.InstallRequirementsShowPackages;
                td.ExpandedControlText = Strings.InstallRequirementsHidePackages;
            } catch (IOException) {
            } catch (NotSupportedException) {
            } catch (UnauthorizedAccessException) {
            }

            var btn = td.ShowModal();
            int cmdId = 0;
            if (btn == venv) {
                cmdId = (int)PkgCmdIDList.cmdidAddVirtualEnv;
            } else if (btn == install) {
                cmdId = (int)PkgCmdIDList.cmdidInstallRequirementsTxt;
            }
            if (cmdId != 0) {
                object inObj = (object)true, outObj = null;
                try {
                    project.DTE.Commands.Raise(
                        GuidList.guidPythonToolsCmdSet.ToString("B"),
                        cmdId,
                        ref inObj,
                        ref outObj
                    );
                } catch (Exception ex) {
                    if (ex.IsCriticalException()) {
                        throw;
                    }
                    TaskDialog.ForException(
                        provider,
                        ex,
                        Strings.InstallRequirementsFailed,
                        PythonConstants.IssueTrackerUrl
                    ).ShowModal();
                }
            }
        }
Пример #8
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            try {
                Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
                Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
            } catch {
                // If it fails (doesn't exist/contains files/read-only), let the directory stay.
            }

            var oleProvider = automationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

            if (oleProvider == null)
            {
                MessageBox.Show("Unable to start wizard: no automation object available.", "Visual Studio");
                throw new WizardBackoutException();
            }

            using (var serviceProvider = new ServiceProvider(oleProvider)) {
                int hr = EnsurePythonPackageLoaded(serviceProvider);
                if (ErrorHandler.Failed(hr))
                {
                    MessageBox.Show(string.Format("Unable to start wizard: failed to load Python support Package (0x{0:X08})", hr), "Visual Studio");
                    throw new WizardBackoutException();
                }

                // Cookiecutter is installed by default, but can be deselected/uninstalled separately from Python component
                hr = EnsureCookiecutterPackageLoaded(serviceProvider);
                if (ErrorHandler.Failed(hr))
                {
                    var dlg = new TaskDialog(serviceProvider)
                    {
                        Title             = Strings.ProductTitle,
                        MainInstruction   = Strings.CookiecutterComponentRequired,
                        Content           = Strings.CookiecutterComponentInstallInstructions,
                        AllowCancellation = true
                    };
                    dlg.Buttons.Add(TaskDialogButton.Cancel);
                    var download = new TaskDialogButton(Strings.DownloadAndInstall);
                    dlg.Buttons.Insert(0, download);

                    if (dlg.ShowModal() == download)
                    {
                        InstallTools(serviceProvider);
                        throw new WizardCancelledException();
                    }
                }

                var uiShell = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell));

                string projName  = replacementsDictionary["$projectname$"];
                string directory = Path.GetDirectoryName(replacementsDictionary["$destinationdirectory$"]);

                var wizardData  = replacementsDictionary["$wizarddata$"];
                var templateUri = Resolve(new Uri(wizardData));

                object inObj = projName + "|" + directory + "|" + templateUri.ToString();
                var    guid  = GuidList.guidCookiecutterCmdSet;
                uiShell.PostExecCommand(ref guid, cmdidNewProjectFromTemplate, 0, ref inObj);
            }
            throw new WizardCancelledException();
        }
Пример #9
0
        private Tuple <bool?, bool> ConfirmMoveFileUsingTaskDialog(string fileName, string targetFolder,
                                                                   int numberOfItemsLeft, string mainInstruction)
        {
            var content = string.Format(
                CultureInfo.CurrentCulture,
                Resources.MoveContentFileToFolderExplanation,
                targetFolder);

            var dialog = new TaskDialog
            {
                MainInstruction = mainInstruction,
                Content         = content,
                WindowTitle     = Resources.Dialog_Title,
                ButtonStyle     = TaskDialogButtonStyle.CommandLinks
            };

            if (numberOfItemsLeft > 0)
            {
                dialog.VerificationText = "Do this for the next " + numberOfItemsLeft + " file(s).";
            }

            var moveButton = new TaskDialogButton
            {
                Text            = "Yes",
                CommandLinkNote =
                    "'" + fileName + "' will be added to '" + targetFolder +
                    "' folder."
            };

            var noMoveButton = new TaskDialogButton
            {
                Text            = "No",
                CommandLinkNote =
                    "'" + fileName + "' will be added to the package root."
            };

            dialog.Buttons.Add(moveButton);
            dialog.Buttons.Add(noMoveButton);
            dialog.Buttons.Add(new TaskDialogButton(ButtonType.Cancel));

            var result = dialog.ShowDialog(Window.Value);

            bool?movingFile;

            if (result == moveButton)
            {
                movingFile = true;
            }
            else if (result == noMoveButton)
            {
                movingFile = false;
            }
            else
            {
                // Cancel button clicked
                movingFile = null;
            }

            var remember = dialog.IsVerificationChecked;

            return(Tuple.Create(movingFile, remember));
        }
Пример #10
0
 /// <summary>Displays a task dialog that has a message, a title, an instruction, one or more buttons and an icon.</summary>
 /// <param name="instruction">The text to display.</param>
 /// <param name="title">The title bar caption of the dialog.</param>
 /// <param name="instruction">The instruction shown below the main text.</param>
 /// <param name="buttons">Value that specifies which button or buttons to display.</param>
 /// <param name="icon">The icon to display.</param>
 public static Result Show(string instruction, string title, string content, TaskDialogButton buttons, TaskDialogIcon icon)
 {
     return(InternalShow(IntPtr.Zero, title, instruction, content, buttons, icon));
 }
Пример #11
0
        private void OfferUpgrade(IServiceProvider provider) {
            if (!_recommendUpgrade) {
                return;
            }

            var sm = SettingsManagerCreator.GetSettingsManager(provider);
            var store = sm.GetReadOnlySettingsStore(SettingsScope.UserSettings);

            if (!store.CollectionExists(PythonConstants.DontShowUpgradeDialogAgainCollection) ||
                !store.GetBoolean(PythonConstants.DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, false)) {
                var dlg = new TaskDialog(provider) {
                    Title = Strings.ProductTitle,
                    MainInstruction = Strings.AzureToolsUpgradeRecommended,
                    Content = Strings.AzureToolsUpgradeInstructions,
                    AllowCancellation = true,
                    VerificationText = Strings.DontShowAgain
                };
                var download = new TaskDialogButton(Strings.DownloadAndInstall);
                dlg.Buttons.Add(download);
                var cont = new TaskDialogButton(Strings.ContinueWithoutAzureToolsUpgrade);
                dlg.Buttons.Add(cont);
                dlg.Buttons.Add(TaskDialogButton.Cancel);

                var response = dlg.ShowModal();

                if (dlg.SelectedVerified) {
                    var rwStore = sm.GetWritableSettingsStore(SettingsScope.UserSettings);
                    rwStore.CreateCollection(PythonConstants.DontShowUpgradeDialogAgainCollection);
                    rwStore.SetBoolean(PythonConstants.DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, true);
                }

                if (response == download) {
                    Process.Start(new ProcessStartInfo(AzureToolsDownload));
                    throw new WizardCancelledException();
                } else if (response == TaskDialogButton.Cancel) {
                    // User cancelled, so go back to the New Project dialog
                    throw new WizardBackoutException();
                }
            }
        }
Пример #12
0
        public async Task CheckForLongPaths(string npmArguments = null) {
            if (_isCheckingForLongPaths || !NodejsPackage.Instance.GeneralOptionsPage.CheckForLongPaths) {
                return;
            }

            if (npmArguments != null && _uninstallRegex.IsMatch(npmArguments)) {
                return;
            }

            try {
                _isCheckingForLongPaths = true;
                TaskDialogButton dedupeButton, ignoreButton, disableButton;
                var taskDialog = new TaskDialog(NodejsPackage.Instance) {
                    AllowCancellation = true,
                    EnableHyperlinks = true,
                    Title = Resources.LongPathWarningTitle,
                    MainIcon = TaskDialogIcon.Warning,
                    Content = Resources.LongPathWarningText,
                    CollapsedControlText = Resources.LongPathShowPathsExceedingTheLimit,
                    ExpandedControlText = Resources.LongPathHidePathsExceedingTheLimit,
                    Buttons = {
                        (dedupeButton = new TaskDialogButton(Resources.LongPathNpmDedupe, Resources.LongPathNpmDedupeDetail)),
                        (ignoreButton = new TaskDialogButton(Resources.LongPathDoNothingButWarnNextTime)),
                        (disableButton = new TaskDialogButton(Resources.LongPathDoNothingAndDoNotWarnAgain, Resources.LongPathDoNothingAndDoNotWarnAgainDetail))
                    },
                    FooterIcon = TaskDialogIcon.Information,
                    Footer = Resources.LongPathFooter
                };

                taskDialog.HyperlinkClicked += (sender, e) => {
                    switch (e.Url) {
                        case "#msdn":
                            Process.Start("https://go.microsoft.com/fwlink/?LinkId=454508");
                            break;
                        case "#uservoice":
                            Process.Start("https://go.microsoft.com/fwlink/?LinkID=456509");
                            break;
                        case "#help":
                            Process.Start("https://go.microsoft.com/fwlink/?LinkId=456511");
                            break;
                        default:
                            System.Windows.Clipboard.SetText(e.Url);
                            break;
                    }
                };

                recheck:

                var longPaths = await Task.Factory.StartNew(() =>
                    GetLongSubPaths(ProjectHome)
                    .Concat(GetLongSubPaths(_intermediateOutputPath))
                    .Select(lpi => string.Format(CultureInfo.InvariantCulture, "• {1}\u00A0<a href=\"{0}\">{2}</a>", lpi.FullPath, lpi.RelativePath, Resources.LongPathClickToCopy))
                    .ToArray());
                if (longPaths.Length == 0) {
                    return;
                }
                taskDialog.ExpandedInformation = string.Join("\r\n", longPaths);

                var button = taskDialog.ShowModal();
                if (button == dedupeButton) {
                    var repl = NodejsPackage.Instance.OpenReplWindow(focus: false);
                    await repl.ExecuteCommand(".npm dedupe").HandleAllExceptions(SR.ProductName);

                    taskDialog.Content += "\r\n\r\n" + Resources.LongPathNpmDedupeDidNotHelp;
                    taskDialog.Buttons.Remove(dedupeButton);
                    goto recheck;
                } else if (button == disableButton) {
                    var page = NodejsPackage.Instance.GeneralOptionsPage;
                    page.CheckForLongPaths = false;
                    page.SaveSettingsToStorage();
                }
            } finally {
                _isCheckingForLongPaths = false;
            }
        }
Пример #13
0
 private void ShowTaskDialogWithCommandLinks()
 {
     if( TaskDialog.OSSupportsTaskDialogs )
     {
         using( TaskDialog dialog = new TaskDialog() )
         {
             dialog.WindowTitle = "Task dialog sample";
             dialog.MainInstruction = "This is a sample task dialog with command links.";
             dialog.Content = "Besides regular buttons, task dialogs also support command links. Only custom buttons are shown as command links; standard buttons remain regular buttons.";
             dialog.ButtonStyle = TaskDialogButtonStyle.CommandLinks;
             TaskDialogButton elevatedButton = new TaskDialogButton("An action requiring elevation");
             elevatedButton.CommandLinkNote = "Both regular buttons and command links can show the shield icon to indicate that the action they perform requires elevation. It is up to the application to actually perform the elevation.";
             elevatedButton.ElevationRequired = true;
             TaskDialogButton otherButton = new TaskDialogButton("Some other action");
             TaskDialogButton cancelButton = new TaskDialogButton(ButtonType.Cancel);
             dialog.Buttons.Add(elevatedButton);
             dialog.Buttons.Add(otherButton);
             dialog.Buttons.Add(cancelButton);
             dialog.ShowDialog(this);
         }
     }
     else
     {
         MessageBox.Show(this, "This operating system does not support task dialogs.", "Task Dialog Sample");
     }
 }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskDialog"/> class.
 /// </summary>
 /// <param name="caption">The caption.</param>
 /// <param name="instructionHeading">The instruction heading.</param>
 /// <param name="instructionText">The instruction text.</param>
 /// <param name="additionalDetailsText">The additional details text.</param>
 /// <param name="footerText">The footer text.</param>
 /// <param name="buttons">The buttons.</param>
 /// <param name="defaultButton">The default button.</param>
 /// <param name="instructionIcon">The instruction icon.</param>
 /// <param name="footerIcon">The footer icon.</param>
 /// <param name="buttonsDisabledDelay">The buttons disabled delay.</param>
 public TaskDialog(String caption, String instructionHeading, String instructionText, String additionalDetailsText, String footerText, TaskDialogButton buttons, TaskDialogResult defaultButton, TaskDialogIcon instructionIcon, TaskDialogIcon footerIcon, Int32 buttonsDisabledDelay = 0)
 {
     _caption                  = caption;
     _instructionHeading       = instructionHeading;
     _instructionText          = instructionText;
     _additionalDetailsText    = additionalDetailsText;
     _footerText               = footerText;
     _buttons                  = buttons;
     _defaultButton            = defaultButton;
     _instructionIcon          = instructionIcon;
     _footerIcon               = footerIcon;
     this.ButtonsDisabledDelay = buttonsDisabledDelay;
 }
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskDialog"/> class.
 /// </summary>
 /// <param name="caption">The caption.</param>
 /// <param name="instructionHeading">The instruction heading.</param>
 /// <param name="instructionText">The instruction text.</param>
 /// <param name="buttons">The buttons.</param>
 /// <param name="defaultButton">The default button.</param>
 /// <param name="instructionIcon">The instruction icon.</param>
 /// <param name="buttonsDisabledDelay">The buttons disabled delay.</param>
 public TaskDialog(String caption, String instructionHeading, String instructionText, TaskDialogButton buttons, TaskDialogResult defaultButton, TaskDialogIcon instructionIcon, Int32 buttonsDisabledDelay = 0)
 {
     _caption                  = caption;
     _instructionHeading       = instructionHeading;
     _instructionText          = instructionText;
     _buttons                  = buttons;
     _defaultButton            = defaultButton;
     _instructionIcon          = instructionIcon;
     this.ButtonsDisabledDelay = buttonsDisabledDelay;
 }
        /// <summary>
        /// Select server
        /// </summary>
        /// <returns></returns>
        public static string SelectWebServer()
        {
            string serverName    = "";
            var    server1Button = new TaskDialogButton("Server1Button", "Server 1")
            {
                Default = true
            };
            var server2Button = new TaskDialogButton("Server2Button", "Server 2");
            var cancelButton  = new TaskDialogButton("CancelButton", "Cancel");

            var dialog = new TaskDialog
            {
                Caption           = "Question",
                InstructionText   = $"Close '{Application.ProductName}'",
                Icon              = TaskDialogStandardIcon.Warning,
                Cancelable        = true,
                OwnerWindowHandle = Form.ActiveForm.Handle,
                StartupLocation   = TaskDialogStartupLocation.CenterOwner
            };

            //
            // Place buttons in the order they should appear
            //
            dialog.Controls.Add(server2Button);
            dialog.Controls.Add(server1Button);
            dialog.Controls.Add(cancelButton);

            //
            // Issue that requires icon to be set here else
            // it will not show.
            //
            dialog.Opened += (sender, ea) =>
            {
                var taskDialog = sender as TaskDialog;
                taskDialog.Icon = taskDialog.Icon;
            };

            //
            // Set result for when dialog closes
            //
            server1Button.Click += (e, a) =>
            {
                serverName = "https://stackpath.bootstrapcdn.com";
                dialog.Close(TaskDialogResult.Close);
            };

            server2Button.Click += (e, a) =>
            {
                serverName = "https://cdn.jsdelivr.net";
                dialog.Close(TaskDialogResult.Close);
            };

            cancelButton.Click += (e, a) =>
            {
                serverName = "";
                dialog.Close(TaskDialogResult.Close);
            };

            dialog.Show();

            return(serverName);
        }
Пример #17
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
            AppDomain.CurrentDomain.UnhandledException   += CurrentDomain_UnhandledException;

            System.Windows.Forms.Application.EnableVisualStyles();
            SetBrowserEmulationMode();

            if (File.Exists(Path.Combine(CurrentDirectory, "Config.json"))) // Checks for configuration file
            {
                try
                {
                    // Loads configuration
                    Config = JsonConvert.DeserializeObject <Config>(
                        File.ReadAllText(Path.Combine(CurrentDirectory, "Config.json")));
                }
                catch
                {
                    // Creates new configuration
                    Config.Save();
                }
            }
            else
            {
                try
                {
                    // Creates new configuration
                    File.WriteAllText(Path.Combine(CurrentDirectory, "Config.json"),
                                      JsonConvert.SerializeObject(Config, Formatting.Indented));
                }
                catch
                {
                    // Relaunches app as administrator
                    // Helps if app is installed to Program Files and it can't access config.json
                    TaskDialog dialog = new TaskDialog();
                    dialog.WindowTitle             = "Unable to write config file";
                    dialog.MainInstruction         = "Unable to write configuration file!";
                    dialog.Content                 = "Sorry! I was unable to write my configuration file! I may be in a protected directory, do you want to try relaunch as an administrator and try again?";
                    dialog.MainIcon                = TaskDialogIcon.Error;
                    dialog.AllowDialogCancellation = true;
                    dialog.ButtonStyle             = TaskDialogButtonStyle.CommandLinks;
                    TaskDialogButton relaunchAsAdmin = new TaskDialogButton("Relaunch as administrator\nLets hope this works!\0");
                    relaunchAsAdmin.ElevationRequired = true;
                    dialog.Buttons.Add(relaunchAsAdmin);
                    dialog.Buttons.Add(new TaskDialogButton(ButtonType.Cancel));

                    if (dialog.Show() == relaunchAsAdmin)
                    {
                        ProcessStartInfo info = new ProcessStartInfo(Assembly.GetExecutingAssembly().Location);
                        info.UseShellExecute = true;
                        info.Verb            = "runas";
                        info.Arguments       = "firstrun";
                        Process.Start(info);
                        Environment.Exit(0);
                    }
                    else
                    {
                        Environment.Exit(0);
                    }
                }
            }

            SelectedTheme = Config.Personalisation.SelectedTheme;

            ChangeTheme();

            Config.Save();

            if (!String.IsNullOrEmpty(App.Config.Token))
            {
                DiscordWindow window = new DiscordWindow(App.Config.Token);
                MainWindow = window;
                window.Show();
            }
            else
            {
                LoginWindow window = new LoginWindow();
                MainWindow = window;
                window.Show();
            }
        }
        private void OnRenameTags(string newName)
        {
            ShowBusy(true);

            //check if new name provided is a new tag or existing
            var tagExistResponse = _tagService.GetTagByName(newName).Result;

            if (tagExistResponse.Exception != null)
            {
                StatusMessage = "Renaming tag...";
                var selectedTag = SelectedTags?.FirstOrDefault();
                if (selectedTag == null)
                {
                    return;
                }

                StatusMessage = $"Renaming tag...{selectedTag.Name}";

                var response = _tagService.RenameTag(selectedTag.Name, newName.Trim()).Result;
                if (response.Exception != null)
                {
                    _log.Error("Error renaming tag - Data: {@data}, Exception: {@exception}", response.Data, response.Exception);
                    ShowBusy(false);
                    _eventAggregator.GetEvent <NotifyErrorTagAdminPage>().Publish(response.Exception.Message);
                    return;
                }
                //trigger refresh
                StatusMessage = "Refreshing...";
                _eventAggregator.GetEvent <TriggerGetTags>().Publish(_teamFoundationContext);
            }
            else if (tagExistResponse.Data != null)
            {
                //tag already exist
                ShowBusy(false);
                if (TaskDialog.OSSupportsTaskDialogs)
                {
                    using (TaskDialog dialog = new TaskDialog())
                    {
                        dialog.WindowTitle     = @"Tag Admin";
                        dialog.MainInstruction = @"Tag name already exists!";
                        dialog.Content         = $@"Tag '{newName}' already exists, please choose another name.";
                        TaskDialogButton okButton = new TaskDialogButton("Try new name");
                        dialog.Buttons.Add(okButton);
                        var cancelButton = new TaskDialogButton("Cancel rename");
                        dialog.Buttons.Add(cancelButton);
                        var taskDialogButton = dialog.ShowDialog();
                        if (taskDialogButton == okButton)
                        {
                            OnRenameTagCommand(null);
                            return;
                        }
                        if (taskDialogButton == cancelButton)
                        {
                            return;
                        }
                    }
                }
                else
                {
                    var messageBoxResult = MessageBox.Show(
                        $"Tag '{newName}' already exists, please choose another name.", "Tag Admin", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                    if (messageBoxResult == MessageBoxResult.OK)
                    {
                        OnRenameTagCommand(null);
                        return;
                    }
                    if (messageBoxResult == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                }
            }


            ShowBusy(false);
        }
Пример #19
0
        private void PipExtensionProvider_QueryShouldElevate(object sender, QueryShouldElevateEventArgs e)
        {
            if (_pyService.GeneralOptions.ElevatePip) {
                e.Elevate = true;
                return;
            }

            try {
                // Create a test file and delete it immediately to ensure we can do it.
                // If this fails, prompt the user to see whether they want to elevate.
                var testFile = PathUtils.GetAvailableFilename(e.TargetDirectory, "access-test", ".txt");
                using (new FileStream(testFile, FileMode.CreateNew, FileAccess.Write, FileShare.Delete, 4096, FileOptions.DeleteOnClose)) { }
                e.Elevate = false;
                return;
            } catch (IOException) {
            } catch (UnauthorizedAccessException) {
            }

            var td = new TaskDialog(_site) {
                Title = Strings.ProductTitle,
                MainInstruction = Strings.ElevateForInstallPackage_MainInstruction,
                AllowCancellation = true,
            };
            var elevate = new TaskDialogButton(Strings.ElevateForInstallPackage_Elevate, Strings.ElevateForInstallPackage_Elevate_Note) {
                ElevationRequired = true
            };
            var noElevate = new TaskDialogButton(Strings.ElevateForInstallPackage_DoNotElevate, Strings.ElevateForInstallPackage_DoNotElevate_Note);
            var elevateAlways = new TaskDialogButton(Strings.ElevateForInstallPackage_ElevateAlways, Strings.ElevateForInstallPackage_ElevateAlways_Note) {
                ElevationRequired = true
            };
            td.Buttons.Add(elevate);
            td.Buttons.Add(noElevate);
            td.Buttons.Add(elevateAlways);
            td.Buttons.Add(TaskDialogButton.Cancel);
            var sel = td.ShowModal();
            if (sel == TaskDialogButton.Cancel) {
                e.Cancel = true;
            } else if (sel == noElevate) {
                e.Elevate = false;
            } else if (sel == elevateAlways) {
                _pyService.GeneralOptions.ElevatePip = true;
                _pyService.GeneralOptions.Save();
                e.Elevate = true;
            } else {
                e.Elevate = true;
            }
        }
Пример #20
0
        public static void Main(string [] args)
        {
            ChapterManager    chapterManager    = null;
            KanjiInputManager kanjiInputManager = null;
            TranslatorThread  translatorThread  = null;
            MiharuMainWindow  mainWindow        = null;

            try {
                App application = new App();


                /*MainWindow mw = new MainWindow();
                 * application.Run(mw);*/


                //Initialize stuff
                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory.ToString());
                if (CheckForTesseract())
                {
                    translatorThread = TranslatorThread.StartThread();

                    string startChapter = null;
                    startChapter = CheckCrash();
                    if (startChapter == null && args.Length > 0 && File.Exists(args [0]))
                    {
                        startChapter = args[0];
                    }

                    /*Logger.Log("Start Chapter: " + startChapter);
                     * Logger.Log("Args Length: " + args.Length);
                     * for (int i = 0; i < args.Length; i++)
                     *      Logger.Log("\t" + args[i]);*/

                    kanjiInputManager = new KanjiInputManager();

                    chapterManager = new ChapterManager(kanjiInputManager, translatorThread);

                    mainWindow = new MiharuMainWindow(chapterManager, startChapter);

                    PageControl pageControl = new PageControl(chapterManager.PageManager);
                    mainWindow.PageControlArea.Child = pageControl;

                    TextEntryView textEntryView = new TextEntryView(chapterManager.PageManager.TextEntryManager, kanjiInputManager);
                    mainWindow.TextEntryArea.Child = textEntryView;

                    application.Run(mainWindow);
                }
            }
            catch (Exception e) {
                CrashHandler.HandleCrash(chapterManager, e);
                FileInfo crashFileInfo = new FileInfo(Logger.CurrentCrashLog);

                TaskDialog dialog = new TaskDialog();
                dialog.WindowTitle     = "Fatal Error";
                dialog.MainIcon        = TaskDialogIcon.Error;
                dialog.MainInstruction = "There was a fatal error. Details can be found in the generated crash log:";
                dialog.Content         = crashFileInfo.FullName;

                TaskDialogButton okButton = new TaskDialogButton("Ok");
                okButton.ButtonType = ButtonType.Ok;
                dialog.Buttons.Add(okButton);
                TaskDialogButton button = dialog.ShowDialog();
            }
            finally {
                mainWindow?.Close();
                translatorThread?.FinalizeThread();
            }
        }
Пример #21
0
        public static bool ShouldElevate(IServiceProvider site, InterpreterConfiguration config, string operation) {
            var opts = site.GetPythonToolsService().GeneralOptions;
            if (opts.ElevatePip) {
                return true;
            }

            try {
                // Create a test file and delete it immediately to ensure we can do it.
                // If this fails, prompt the user to see whether they want to elevate.
                var testFile = PathUtils.GetAvailableFilename(config.PrefixPath, "access-test", ".txt");
                using (new FileStream(testFile, FileMode.CreateNew, FileAccess.Write, FileShare.Delete, 4096, FileOptions.DeleteOnClose)) { }
                return false;
            } catch (IOException) {
            } catch (UnauthorizedAccessException) {
            }

            var td = new TaskDialog(site) {
                Title = Strings.ProductTitle,
                MainInstruction = Strings.ElevateForInstallPackage_MainInstruction,
                AllowCancellation = true,
            };
            var elevate = new TaskDialogButton(Strings.ElevateForInstallPackage_Elevate, Strings.ElevateForInstallPackage_Elevate_Note) {
                ElevationRequired = true
            };
            var noElevate = new TaskDialogButton(Strings.ElevateForInstallPackage_DoNotElevate, Strings.ElevateForInstallPackage_DoNotElevate_Note);
            var elevateAlways = new TaskDialogButton(Strings.ElevateForInstallPackage_ElevateAlways, Strings.ElevateForInstallPackage_ElevateAlways_Note) {
                ElevationRequired = true
            };
            td.Buttons.Add(elevate);
            td.Buttons.Add(noElevate);
            td.Buttons.Add(elevateAlways);
            td.Buttons.Add(TaskDialogButton.Cancel);
            var sel = td.ShowModal();
            if (sel == TaskDialogButton.Cancel) {
                throw new OperationCanceledException();
            }

            if (sel == noElevate) {
                return false;
            }

            if (sel == elevateAlways) {
                opts.ElevatePip = true;
                opts.Save();
            }

            return true;
        }
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            var provider = WizardHelpers.GetProvider(automationObject);

            if (_wizard == null)
            {
                try {
                    Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
                    Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
                } catch {
                    // If it fails (doesn't exist/contains files/read-only), let the directory stay.
                }

                var dlg = new TaskDialog(provider)
                {
                    Title             = Resources.PythonToolsForVisualStudio,
                    MainInstruction   = Resources.AzureToolsRequired,
                    Content           = Resources.AzureToolsInstallInstructions,
                    AllowCancellation = true
                };
                var download = new TaskDialogButton(Resources.DownloadAndInstall);
                dlg.Buttons.Add(download);
                dlg.Buttons.Add(TaskDialogButton.Cancel);

                if (dlg.ShowModal() == download)
                {
                    Process.Start(new ProcessStartInfo(AzureToolsDownload));
                    throw new WizardCancelledException();
                }

                // User cancelled, so go back to the New Project dialog
                throw new WizardBackoutException();
            }

            if (_recommendUpgrade)
            {
                var sm    = SettingsManagerCreator.GetSettingsManager(provider);
                var store = sm.GetReadOnlySettingsStore(SettingsScope.UserSettings);

                if (!store.CollectionExists(PythonConstants.DontShowUpgradeDialogAgainCollection) ||
                    !store.GetBoolean(PythonConstants.DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, false))
                {
                    var dlg = new TaskDialog(provider)
                    {
                        Title             = Resources.PythonToolsForVisualStudio,
                        MainInstruction   = Resources.AzureToolsUpgradeRecommended,
                        Content           = Resources.AzureToolsUpgradeInstructions,
                        AllowCancellation = true,
                        VerificationText  = Resources.DontShowAgain
                    };
                    var download = new TaskDialogButton(Resources.DownloadAndInstall);
                    dlg.Buttons.Add(download);
                    var cont = new TaskDialogButton(Resources.ContinueWithoutAzureToolsUpgrade);
                    dlg.Buttons.Add(cont);
                    dlg.Buttons.Add(TaskDialogButton.Cancel);

                    var response = dlg.ShowModal();

                    if (response != cont)
                    {
                        try {
                            Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
                            Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
                        } catch {
                            // If it fails (doesn't exist/contains files/read-only), let the directory stay.
                        }
                    }

                    if (dlg.SelectedVerified)
                    {
                        var rwStore = sm.GetWritableSettingsStore(SettingsScope.UserSettings);
                        rwStore.CreateCollection(PythonConstants.DontShowUpgradeDialogAgainCollection);
                        rwStore.SetBoolean(PythonConstants.DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, true);
                    }

                    if (response == download)
                    {
                        Process.Start(new ProcessStartInfo(AzureToolsDownload));
                        throw new WizardCancelledException();
                    }
                    else if (response == TaskDialogButton.Cancel)
                    {
                        // User cancelled, so go back to the New Project dialog
                        throw new WizardBackoutException();
                    }
                }
            }

            // Run the original wizard to get the right replacements
            _wizard.RunStarted(automationObject, replacementsDictionary, runKind, customParams);
        }
Пример #23
0
        /// <summary>Initializes a new Task Dialog instance with an instruction, a title, some content text, a specific button and an icon.</summary>
        /// <param name="instruction">The main instruction to display.</param>
        /// <param name="title">The title of the Task Dialog.</param>
        /// <param name="content">The content text that will be displayes below the main instruction.</param>
        /// <param name="commonButtons">Specifies one or more buttons to be displayed on the bottom of the dialog, instead of the default OK button.</param>
        /// <param name="icon">The icon to display.</param>
        public TaskDialog(string instruction, string title, string content, TaskDialogButton commonButtons, TaskDialogIcon icon)
        {
            Init();

            Title = title;
            Instruction = instruction;
            Content = content;
            CommonButtons = commonButtons;
            CommonIcon = icon;
        }
Пример #24
0
        static TaskDialogPage CreatetDownloadPage()
        {
            var downloadCancellationSource = new CancellationTokenSource();

            var downloadProgressBar = new TaskDialogProgressBar()
            {
                Minimum = 0,
                Maximum = 100,
                State   = TaskDialogProgressBarState.Marquee,
            };
            var cancelDownloadButton = new TaskDialogButton()
            {
                Text = "Cancel Download",
            };

            cancelDownloadButton.Click += (s, e) => downloadCancellationSource.Cancel();

            var downloadPage = new TaskDialogPage()
            {
                AllowMinimize = true,
                Caption       = "FFmpeg missing",
                Heading       = "Downloading FFmpeg...",
                Text          = "We're shifting some bits around to get you ready.",
                ProgressBar   = downloadProgressBar,
                Buttons       = new TaskDialogButtonCollection()
                {
                    cancelDownloadButton,
                },
                // DefaultButton = None,
                Expander = new TaskDialogExpander()
                {
                    Text = "Initializing...",
                    CollapsedButtonText = "More status info",
                    Position            = TaskDialogExpanderPosition.AfterFootnote,
                },
            };

            downloadPage.Created += async(o, e) =>
            {
                downloadPage.Expander.Text = "Fetching info...";

                var url = await FFmpegFetcher.GetUrlOfLatestBinary();

                if (url == null)
                {
                    downloadPage.Navigate(CreateDownloadFailedPage("Unable to get link to FFmpeg download"));
                    return;
                }

                var progress = new DialogTransferProgress(downloadPage);

                downloadPage.Expander.Text = "Downloading...";
                try
                {
                    await FFmpegFetcher.LoadAndUnzipToDirectory(FFmpegManager.FFmpegAppDataPath, url, progress, downloadCancellationSource.Token);
                }
                catch (TaskCanceledException)
                {
                    // Well, it's actually not an error, but we're too lazy for a separate doaloge for this
                    downloadPage.Navigate(CreateDownloadFailedPage("You cancelled the download."));
                    return;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Failed to download FFmpeg.");
                    Debug.WriteLine(ex);
                    downloadPage.Navigate(CreateDownloadFailedPage(ex.Message));
                    return;
                }

                downloadPage.Expander.Text = "Done!";

                // Cross-check if downloading ffmpeg fixed the problem
                var path = FFmpegManager.GetAbsoluteFFmpegPath(true);
                if (path == null)
                {
                    downloadPage.Navigate(CreateDownloadFailedPage("The download was successful, but it did not fix the issue."));
                }
                else
                {
                    downloadPage.Navigate(CreateDownloadFinishedPage());
                }
            };

            return(downloadPage);
        }
Пример #25
0
        private bool? QuerySetEvaluator(string newEvaluator, string newEvaluatorId) {
            var opts = _serviceProvider.GetPythonToolsService().SuppressDialogOptions;
            var opt = opts.SwitchEvaluator;
            if (opt == "AlwaysSwitch") {
                return true;
            } else if (opt == "AlwaysOpenNew") {
                return false;
            }

            var td = new TaskDialog(_serviceProvider) {
                Title = Strings.ProductTitle,
                MainInstruction = Strings.ReplQuerySwitchEvaluator.FormatUI(newEvaluator),
                Content = Strings.ReplQuerySwitchEvaluatorHint,
                VerificationText = Strings.RememberMySelection,
                AllowCancellation = true
            };
            var sameWin = new TaskDialogButton(Strings.ReplQuerySwitchThisTab, Strings.ReplQuerySwitchThisTabHint);
            var newWin = new TaskDialogButton(Strings.ReplQuerySwitchNewTab, Strings.ReplQuerySwitchNewTabHint);
            td.Buttons.Add(sameWin);
            td.Buttons.Add(newWin);
            td.Buttons.Add(TaskDialogButton.Cancel);
            var result = td.ShowModal();
            if (result == sameWin) {
                if (td.SelectedVerified) {
                    opts.SwitchEvaluator = "AlwaysSwitch";
                    opts.Save();
                }
                return true;
            } else if (result == newWin) {
                if (td.SelectedVerified) {
                    opts.SwitchEvaluator = "AlwaysOpenNew";
                    opts.Save();
                }
                return false;
            }
            return null;
        }
Пример #26
0
        public async Task CheckForLongPaths(string npmArguments = null)
        {
            if (_isCheckingForLongPaths || !NodejsPackage.Instance.GeneralOptionsPage.CheckForLongPaths)
            {
                return;
            }

            if (npmArguments != null && _uninstallRegex.IsMatch(npmArguments))
            {
                return;
            }

            try {
                _isCheckingForLongPaths = true;
                TaskDialogButton dedupeButton, ignoreButton, disableButton;
                var taskDialog = new TaskDialog(NodejsPackage.Instance)
                {
                    AllowCancellation    = true,
                    EnableHyperlinks     = true,
                    Title                = Resources.LongPathWarningTitle,
                    MainIcon             = TaskDialogIcon.Warning,
                    Content              = Resources.LongPathWarningText,
                    CollapsedControlText = Resources.LongPathShowPathsExceedingTheLimit,
                    ExpandedControlText  = Resources.LongPathHidePathsExceedingTheLimit,
                    Buttons              =
                    {
                        (dedupeButton  = new TaskDialogButton(Resources.LongPathNpmDedupe,                  Resources.LongPathNpmDedupeDetail)),
                        (ignoreButton  = new TaskDialogButton(Resources.LongPathDoNothingButWarnNextTime)),
                        (disableButton = new TaskDialogButton(Resources.LongPathDoNothingAndDoNotWarnAgain, Resources.LongPathDoNothingAndDoNotWarnAgainDetail))
                    },
                    FooterIcon = TaskDialogIcon.Information,
                    Footer     = Resources.LongPathFooter
                };

                taskDialog.HyperlinkClicked += (sender, e) => {
                    switch (e.Url)
                    {
                    case "#msdn":
                        Process.Start("https://go.microsoft.com/fwlink/?LinkId=454508");
                        break;

                    case "#uservoice":
                        Process.Start("https://go.microsoft.com/fwlink/?LinkID=456509");
                        break;

                    case "#help":
                        Process.Start("https://go.microsoft.com/fwlink/?LinkId=456511");
                        break;

                    default:
                        System.Windows.Clipboard.SetText(e.Url);
                        break;
                    }
                };

recheck:

                var longPaths = await Task.Factory.StartNew(() =>
                                                            GetLongSubPaths(ProjectHome)
                                                            .Concat(GetLongSubPaths(_intermediateOutputPath))
                                                            .Select(lpi => string.Format(CultureInfo.InvariantCulture, "• {1}\u00A0<a href=\"{0}\">{2}</a>", lpi.FullPath, lpi.RelativePath, Resources.LongPathClickToCopy))
                                                            .ToArray());

                if (longPaths.Length == 0)
                {
                    return;
                }
                taskDialog.ExpandedInformation = string.Join("\r\n", longPaths);

                var button = taskDialog.ShowModal();
                if (button == dedupeButton)
                {
                    var repl = NodejsPackage.Instance.OpenReplWindow(focus: false);
                    await repl.ExecuteCommand(".npm dedupe").HandleAllExceptions(SR.ProductName);

                    taskDialog.Content += "\r\n\r\n" + Resources.LongPathNpmDedupeDidNotHelp;
                    taskDialog.Buttons.Remove(dedupeButton);
                    goto recheck;
                }
                else if (button == disableButton)
                {
                    var page = NodejsPackage.Instance.GeneralOptionsPage;
                    page.CheckForLongPaths = false;
                    page.SaveSettingsToStorage();
                }
            } finally {
                _isCheckingForLongPaths = false;
            }
        }
Пример #27
0
        private void ShowAutoClosingTaskDialog()
        {
            const string textFormat            = "Reconnecting in {0} seconds...";
            int          remainingTenthSeconds = 50;

            var reconnectButton = new TaskDialogButton("&Reconnect now");
            var cancelButton    = TaskDialogButton.Cancel;

            var page = new TaskDialogPage()
            {
                Heading = "Connection lost; reconnecting...",
                Text    = string.Format(textFormat, (remainingTenthSeconds + 9) / 10),
                // Display the form's icon in the task dialog.
                // Note however that the task dialog will not scale the icon.
                Icon        = new TaskDialogIcon(this.Icon),
                ProgressBar = new TaskDialogProgressBar()
                {
                    State = TaskDialogProgressBarState.Paused
                },
                Buttons =
                {
                    reconnectButton,
                    cancelButton
                }
            };

            // Create a WinForms timer that raises the Tick event every tenth second.
            using (var timer = new Timer()
            {
                Enabled = true,
                Interval = 100
            })
            {
                timer.Tick += (s, e) =>
                {
                    remainingTenthSeconds--;
                    if (remainingTenthSeconds > 0)
                    {
                        // Update the remaining time and progress bar.
                        page.Text = string.Format(textFormat, (remainingTenthSeconds + 9) / 10);
                        page.ProgressBar.Value = 100 - remainingTenthSeconds * 2;
                    }
                    else
                    {
                        // Stop the timer and click the "Reconnect" button - this will
                        // close the dialog.
                        timer.Enabled = false;
                        reconnectButton.PerformClick();
                    }
                };

                TaskDialogButton result = TaskDialog.ShowDialog(this, page);
                if (result == reconnectButton)
                {
                    Console.WriteLine("Reconnecting.");
                }
                else
                {
                    Console.WriteLine("Not reconnecting.");
                }
            }
        }
Пример #28
0
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) {
            var provider = WizardHelpers.GetProvider(automationObject);

            if (_wizard == null) {
                try {
                    Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
                    Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
                } catch {
                    // If it fails (doesn't exist/contains files/read-only), let the directory stay.
                }

                var dlg = new TaskDialog(provider) {
                    Title = Strings.ProductTitle,
                    MainInstruction = Strings.AzureToolsRequired,
                    Content = Strings.AzureToolsInstallInstructions,
                    AllowCancellation = true
                };
                dlg.Buttons.Add(TaskDialogButton.Cancel);
                var download = new TaskDialogButton(Strings.DownloadAndInstall);
                dlg.Buttons.Insert(0, download);

                if (dlg.ShowModal() == download) {
                    StartDownload(provider);
                    throw new WizardCancelledException();
                }

                // User cancelled, so go back to the New Project dialog
                throw new WizardBackoutException();
            }

            OfferUpgrade(provider);

            // Run the original wizard to get the right replacements
            _wizard.RunStarted(automationObject, replacementsDictionary, runKind, customParams);
        }
Пример #29
0
        private void ShowMultiPageTaskDialog()
        {
            // Disable the "Yes" button and only enable it when the check box is checked.
            // Also, don't close the dialog when this button is clicked.
            var initialButtonYes = TaskDialogButton.Yes;

            initialButtonYes.Enabled          = false;
            initialButtonYes.AllowCloseDialog = false;

            var initialPage = new TaskDialogPage()
            {
                Caption     = "My Application",
                Heading     = "Clean up database?",
                Text        = "Do you really want to do a clean-up?\nThis action is irreversible!",
                Icon        = TaskDialogIcon.ShieldWarningYellowBar,
                AllowCancel = true,
                // A modeless dialog can be minimizable.
                AllowMinimize = true,

                Verification = new TaskDialogVerificationCheckBox()
                {
                    Text = "I know what I'm doing"
                },

                Buttons =
                {
                    TaskDialogButton.No,
                    initialButtonYes
                },
                DefaultButton = TaskDialogButton.No
            };

            // For the "In Progress" page, don't allow the dialog to close, by adding
            // a disabled button (if no button was specified, the task dialog would
            // get an (enabled) 'OK' button).
            var inProgressCloseButton = TaskDialogButton.Close;

            inProgressCloseButton.Enabled = false;

            var inProgressPage = new TaskDialogPage()
            {
                Caption       = "My Application",
                Heading       = "Operation in progress...",
                Text          = "Please wait while the operation is in progress.",
                Icon          = TaskDialogIcon.Information,
                AllowMinimize = true,

                ProgressBar = new TaskDialogProgressBar()
                {
                    State = TaskDialogProgressBarState.Marquee
                },

                Expander = new TaskDialogExpander()
                {
                    Text     = "Initializing...",
                    Position = TaskDialogExpanderPosition.AfterFootnote
                },

                Buttons =
                {
                    inProgressCloseButton
                }
            };

            // Add an invisible Cancel button where we will intercept the Click event
            // to prevent the dialog from closing (when the User clicks the "X" button
            // in the title bar or presses ESC or Alt+F4).
            var invisibleCancelButton = TaskDialogButton.Cancel;

            invisibleCancelButton.Visible          = false;
            invisibleCancelButton.AllowCloseDialog = false;
            inProgressPage.Buttons.Add(invisibleCancelButton);

            var finishedPage = new TaskDialogPage()
            {
                Caption       = "My Application",
                Heading       = "Success!",
                Text          = "The operation finished.",
                Icon          = TaskDialogIcon.ShieldSuccessGreenBar,
                AllowMinimize = true,
                Buttons       =
                {
                    TaskDialogButton.Close
                }
            };

            TaskDialogButton showResultsButton = new TaskDialogCommandLinkButton("Show &Results");

            finishedPage.Buttons.Add(showResultsButton);

            // Enable the "Yes" button only when the checkbox is checked.
            TaskDialogVerificationCheckBox checkBox = initialPage.Verification;

            checkBox.CheckedChanged += (sender, e) =>
            {
                initialButtonYes.Enabled = checkBox.Checked;
            };

            // When the user clicks "Yes", navigate to the second page.
            initialButtonYes.Click += (sender, e) =>
            {
                // Navigate to the "In Progress" page that displays the
                // current progress of the background work.
                initialPage.Navigate(inProgressPage);

                // NOTE: When you implement a "In Progress" page that represents
                // background work that is done e.g. by a separate thread/task,
                // which eventually calls Control.Invoke()/BeginInvoke() when
                // its work is finished in order to navigate or update the dialog,
                // then DO NOT start that work here already (directly after
                // setting the Page property). Instead, start the work in the
                // TaskDialogPage.Created event of the new page.
                //
                // See comments in the code sample in https://github.com/dotnet/winforms/issues/146
                // for more information.
            };

            // Simulate work by starting an async operation from which we are updating the
            // progress bar and the expander with the current status.
            inProgressPage.Created += async(s, e) =>
            {
                // Run the background operation and iterate over the streamed values to update
                // the progress. Because we call the async method from the GUI thread,
                // it will use this thread's synchronization context to run the continuations,
                // so we don't need to use Control.[Begin]Invoke() to schedule the callbacks.
                var progressBar = inProgressPage.ProgressBar;

                await foreach (int progressValue in StreamBackgroundOperationProgressAsync())
                {
                    // When we display the first progress, switch the marquee progress bar
                    // to a regular one.
                    if (progressBar.State == TaskDialogProgressBarState.Marquee)
                    {
                        progressBar.State = TaskDialogProgressBarState.Normal;
                    }

                    progressBar.Value            = progressValue;
                    inProgressPage.Expander.Text = $"Progress: {progressValue} %";
                }

                // Work is finished, so navigate to the third page.
                inProgressPage.Navigate(finishedPage);
            };

            // Show the dialog (modeless).
            TaskDialogButton result = TaskDialog.ShowDialog(initialPage);

            if (result == showResultsButton)
            {
                Console.WriteLine("Showing Results!");
            }
Пример #30
0
        private static Result InternalShow(IntPtr parent, string title, string instruction, string content, TaskDialogButton commonButtons, TaskDialogIcon icon)
        {
            int dlgValue;

            try {
                //Get handle for parent window if none specified (behave like MessageBox)
                if (parent == IntPtr.Zero)
                {
                    parent = Native.Windows.GetActiveWindow();
                }

                if (NativeMethods.TaskDialog(parent, IntPtr.Zero, title, instruction, content, (int)commonButtons, new IntPtr((long)icon), out dlgValue) != 0)
                {
                    throw new Exception(String.Format(Resources.ExceptionMessages.NativeCallFailure, "TaskDialog"));
                }
            }
            catch (EntryPointNotFoundException ex) {
                throw new Exception(Resources.ExceptionMessages.CommonControlEntryPointNotFound, ex);
            }
            catch (Exception ex) {
                throw new Exception(Resources.ExceptionMessages.TaskDialogFailure, ex);
            }

            //Convert int value to common dialog result
            if (dlgValue > 0 && dlgValue <= 8)
            {
                return((Result)dlgValue);
            }
            else
            {
                return(Result.None);
            }
        }
Пример #31
0
        private void ShowSimpleTaskDialog()
        {
            // Show a message box.
            DialogResult messageBoxResult = MessageBox.Show(
                this,
                text: "Stopping the operation might leave your database in a corrupted state. Are you sure you want to stop?",
                caption: "Confirmation [Message Box]",
                buttons: MessageBoxButtons.YesNo,
                icon: MessageBoxIcon.Warning,
                defaultButton: MessageBoxDefaultButton.Button2);

            if (messageBoxResult == DialogResult.Yes)
            {
                Console.WriteLine("User confirmed to stop the operation.");
            }

            // Show a task dialog (simple).
            TaskDialogButton result = TaskDialog.ShowDialog(this, new TaskDialogPage()
            {
                Text    = "Stopping the operation might leave your database in a corrupted state.",
                Heading = "Are you sure you want to stop?",
                Caption = "Confirmation (Task Dialog)",
                Buttons =
                {
                    TaskDialogButton.Yes,
                    TaskDialogButton.No
                },
                Icon          = TaskDialogIcon.Warning,
                DefaultButton = TaskDialogButton.No
            });

            if (result == TaskDialogButton.Yes)
            {
                Console.WriteLine("User confirmed to stop the operation.");
            }

            // Show a task dialog (enhanced).
            var page = new TaskDialogPage()
            {
                Heading     = "Are you sure you want to stop?",
                Text        = "Stopping the operation might leave your database in a corrupted state.",
                Caption     = "Confirmation (Task Dialog)",
                Icon        = TaskDialogIcon.Warning,
                AllowCancel = true,

                Verification = new TaskDialogVerificationCheckBox()
                {
                    Text = "Do not show again"
                },

                Buttons =
                {
                    TaskDialogButton.Yes,
                    TaskDialogButton.No
                },

                DefaultButton = TaskDialogButton.No
            };

            var resultButton = TaskDialog.ShowDialog(this, page);

            if (resultButton == TaskDialogButton.Yes)
            {
                if (page.Verification.Checked)
                {
                    Console.WriteLine("Do not show this confirmation again.");
                }

                Console.WriteLine("User confirmed to stop the operation.");
            }
        }
Пример #32
0
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) {
            var provider = WizardHelpers.GetProvider(automationObject);

            if (_wizard == null) {
                try {
                    Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
                    Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
                } catch {
                    // If it fails (doesn't exist/contains files/read-only), let the directory stay.
                }

                var dlg = new TaskDialog(provider) {
                    Title = SR.ProductName,
                    MainInstruction = SR.GetString(SR.AzureToolsRequired),
                    Content = SR.GetString(SR.AzureToolsInstallInstructions),
                    AllowCancellation = true
                };
                var download = new TaskDialogButton(SR.GetString(SR.DownloadAndInstall));
                dlg.Buttons.Add(download);
                dlg.Buttons.Add(TaskDialogButton.Cancel);

                if (dlg.ShowModal() == download) {
                    Process.Start(new ProcessStartInfo(AzureToolsDownload));
                    throw new WizardCancelledException();
                }

                // User cancelled, so go back to the New Project dialog
                throw new WizardBackoutException();
            }

            if (_recommendUpgrade) {
                var sm = SettingsManagerCreator.GetSettingsManager(provider);
                var store = sm.GetReadOnlySettingsStore(SettingsScope.UserSettings);

                if (!store.CollectionExists(DontShowUpgradeDialogAgainCollection) ||
                    !store.GetBoolean(DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, false)) {
                    var dlg = new TaskDialog(provider) {
                        Title = SR.ProductName,
                        MainInstruction = SR.GetString(SR.AzureToolsUpgradeRecommended),
                        Content = SR.GetString(SR.AzureToolsUpgradeInstructions),
                        AllowCancellation = true,
                        VerificationText = SR.GetString(SR.DontShowAgain)
                    };
                    var download = new TaskDialogButton(SR.GetString(SR.DownloadAndInstall));
                    dlg.Buttons.Add(download);
                    var cont = new TaskDialogButton(SR.GetString(SR.ContinueWithoutAzureToolsUpgrade));
                    dlg.Buttons.Add(cont);
                    dlg.Buttons.Add(TaskDialogButton.Cancel);

                    var response = dlg.ShowModal();

                    if (response != cont) {
                        try {
                            Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
                            Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
                        } catch {
                            // If it fails (doesn't exist/contains files/read-only), let the directory stay.
                        }
                    }

                    if (dlg.SelectedVerified) {
                        var rwStore = sm.GetWritableSettingsStore(SettingsScope.UserSettings);
                        rwStore.CreateCollection(DontShowUpgradeDialogAgainCollection);
                        rwStore.SetBoolean(DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, true);
                    }

                    if (response == download) {
                        Process.Start(new ProcessStartInfo(AzureToolsDownload));
                        throw new WizardCancelledException();
                    } else if (response == TaskDialogButton.Cancel) {
                        // User cancelled, so go back to the New Project dialog
                        throw new WizardBackoutException();
                    }
                }
            }

            // Run the original wizard to get the right replacements
            _wizard.RunStarted(automationObject, replacementsDictionary, runKind, customParams);
        }
Пример #33
0
        private void DeleteItem(Dataset datasetToDelete)
        {
            if (datasetToDelete.Kind == Dataset.DatasetKind.Archive)
            {
                var taskDialog = new TaskDialog
                {
                    WindowTitle     = "Delete item",
                    MainInstruction = "Are you sure you want to remove this archive?",
                    Content         = "This operation cannot be undone.",
                    MainIcon        = TaskDialogIcon.Warning
                };

                var deletePermanentlyButton = new TaskDialogButton()
                {
                    ButtonType      = ButtonType.Custom,
                    Text            = "Remove archive from list",
                    CommandLinkNote =
                        "This archive will be removed from the list and placed in the deleted folder."
                };
                taskDialog.Buttons.Add(deletePermanentlyButton);

                taskDialog.Buttons.Add(new TaskDialogButton(ButtonType.Cancel)
                {
                    Default = true
                });
                taskDialog.CenterParent = true;
                taskDialog.ButtonStyle  = TaskDialogButtonStyle.CommandLinks;
                var selectedButton = taskDialog.ShowDialog(this);

                if (selectedButton == deletePermanentlyButton)
                {
                    //Delete the item
                    Console.WriteLine("Delete");
                    ViewModel.DeleteItem(datasetToDelete);
                }
            }
            else
            {
                var taskDialog = new TaskDialog
                {
                    WindowTitle     = "Delete item",
                    MainInstruction = "Are you sure you want to remove this dataset?",
                    Content         = "This operation cannot be undone.",
                    MainIcon        = TaskDialogIcon.Warning
                };

                var removeFromListButton = new TaskDialogButton()
                {
                    ButtonType      = ButtonType.Custom,
                    Text            = "Remove dataset from list",
                    CommandLinkNote =
                        "This dataset will be removed from the list and its files, folders, results, and artifacts will be moved to the deleted folder."
                };
                taskDialog.Buttons.Add(removeFromListButton);

                taskDialog.Buttons.Add(new TaskDialogButton(ButtonType.Cancel)
                {
                    Default = true
                });
                taskDialog.CenterParent = true;
                taskDialog.ButtonStyle  = TaskDialogButtonStyle.CommandLinks;
                var selectedButton = taskDialog.ShowDialog(this);

                if (selectedButton == removeFromListButton)
                {
                    //Delete the item
                    Console.WriteLine("Remove");
                    try
                    {
                        ViewModel.DeleteItem(datasetToDelete);
                    }
                    catch (IOException e)
                    {
                        ShowErrorDialog("Error", "An error occurred while deleting this dataset.", e.Message, e.ToString());
                    }
                }
            }
        }
        public void ProjectFinishedGenerating(Project project)
        {
            if (project.DTE.SuppressUI)
            {
                return;
            }

            string description = null;

            try {
                var p = project.Properties.Item("InterpreterDescription");
                if (p != null)
                {
                    description = p.Value as string;
                }
            } catch (ArgumentException) {
            }

            if (string.IsNullOrEmpty(description))
            {
                bool isValid = false;
                try {
                    var p = project.Properties.Item("InterpreterId");
                    isValid = p != null && !string.IsNullOrEmpty(p.Value as string);
                } catch (ArgumentException) {
                }
                if (!isValid)
                {
                    // We don't have a usable interpreter, so there's no point
                    // going ahead.
                    // Fall out - the user will find what they need when they
                    // try and run or edit, but until then there's no reason to
                    // block them or duplicate all of our help messages into yet
                    // another assembly.
                    return;
                }
            }

            ProjectItem requirementsTxt = null;

            try {
                requirementsTxt = project.ProjectItems.Item("requirements.txt");
            } catch (ArgumentException) {
            }

            if (requirementsTxt == null)
            {
                return;
            }

            var txt = requirementsTxt.FileNames[0];

            if (!File.Exists(txt))
            {
                return;
            }

            var provider = WizardHelpers.GetProvider(project.DTE);

            if (provider == null)
            {
                return;
            }

            var td = new TaskDialog(provider)
            {
                Title             = string.Format("{0} - {1}", project.Name, Resources.PythonToolsForVisualStudio),
                MainInstruction   = Resources.InstallRequirementsHeading,
                Content           = Resources.InstallRequirementsMessage,
                EnableHyperlinks  = true,
                AllowCancellation = true,
            };

            var venv = new TaskDialogButton(
                Resources.InstallRequirementsIntoVirtualEnv,
                Resources.InstallRequirementsIntoVirtualEnvTip
                );

            description = description ?? Resources.DefaultInterpreterDescription;
            var install = new TaskDialogButton(
                string.Format(Resources.InstallRequirementsIntoGlobalEnv, description),
                Resources.InstallRequirementsIntoGlobalEnvTip
                );
            var goAway = new TaskDialogButton(Resources.InstallRequirementsNowhere);

            td.Buttons.Add(venv);
            td.Buttons.Add(install);
            td.Buttons.Add(goAway);

            try {
                td.ExpandedInformation  = File.ReadAllText(txt);
                td.CollapsedControlText = Resources.InstallRequirementsShowPackages;
                td.ExpandedControlText  = Resources.InstallRequirementsHidePackages;
            } catch (IOException) {
            } catch (NotSupportedException) {
            } catch (UnauthorizedAccessException) {
            }

            var btn   = td.ShowModal();
            int cmdId = 0;

            if (btn == venv)
            {
                cmdId = (int)PkgCmdIDList.cmdidAddVirtualEnv;
            }
            else if (btn == install)
            {
                cmdId = (int)PkgCmdIDList.cmdidInstallRequirementsTxt;
            }
            if (cmdId != 0)
            {
                object inObj = (object)true, outObj = null;
                try {
                    project.DTE.Commands.Raise(
                        GuidList.guidPythonToolsCmdSet.ToString("B"),
                        cmdId,
                        ref inObj,
                        ref outObj
                        );
                } catch (Exception ex) {
                    if (ex.IsCriticalException())
                    {
                        throw;
                    }
                    TaskDialog.ForException(
                        provider,
                        ex,
                        Resources.InstallRequirementsFailed,
                        PythonConstants.IssueTrackerUrl
                        ).ShowModal();
                }
            }
        }
Пример #35
0
        private string ResolveAppNameCollisionWithUser(EnvDTE.ProjectItems items, string name, out bool cancel) {
            while (true) {
                try {
                    if (items.Item(name) == null) {
                        break;
                    }
                } catch (ArgumentException) {
                    break;
                }

                var td = new TaskDialog(new ServiceProvider(GetSite())) {
                    Title = Resources.PythonToolsForVisualStudio,
                    MainInstruction = string.Format(Resources.DjangoAppAlreadyExistsTitle, name),
                    Content = string.Format(Resources.DjangoAppAlreadyExistsInstruction, name),
                    AllowCancellation = true
                };
                var cont = new TaskDialogButton(
                    Resources.DjangoAppAlreadyExistsCreateAnyway,
                    Resources.DjangoAppAlreadyExistsCreateAnywaySubtitle
                );
                var retry = new TaskDialogButton(Resources.SelectAnotherName);
                td.Buttons.Add(cont);
                td.Buttons.Add(retry);
                td.Buttons.Add(TaskDialogButton.Cancel);

                var clicked = td.ShowModal();
                if (clicked == cont) {
                    break;
                } else if (clicked == retry) {
                    name = GetNewAppNameFromUser(name);
                    if (string.IsNullOrEmpty(name)) {
                        cancel = true;
                        return null;
                    }
                } else {
                    cancel = true;
                    return null;
                }
            }

            cancel = false;
            return name;
        }
Пример #36
0
        private async Task ExecuteWorker(PythonProjectNode project)
        {
            _errorListProvider.Tasks.Clear();

            var interpFactory = project.GetInterpreterFactoryOrThrow();
            var startInfo     = GetStartInfo(project);

            var packagesToInstall = new List <string>();
            var pm = interpFactory.PackageManager;

            if (pm != null)
            {
                foreach (var pkg in startInfo.RequiredPackages)
                {
                    if (!(await pm.GetInstalledPackageAsync(new PackageSpec(pkg), CancellationToken.None)).IsValid)
                    {
                        packagesToInstall.Add(pkg);
                    }
                }
            }

            if (packagesToInstall.Any())
            {
                var installMissingButton = new TaskDialogButton(
                    Strings.CustomCommandPrerequisitesInstallMissing,
                    Strings.CustomCommandPrerequisitesInstallMissingSubtext + "\r\n\r\n" + string.Join("\r\n", packagesToInstall));
                var runAnywayButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesRunAnyway);
                var doNotRunButton  = new TaskDialogButton(Strings.CustomCommandPrerequisitesDoNotRun);

                var taskDialog = new TaskDialog(project.Site)
                {
                    Title             = Strings.ProductTitle,
                    MainInstruction   = Strings.CustomCommandPrerequisitesInstruction,
                    Content           = Strings.CustomCommandPrerequisitesContent.FormatUI(DisplayLabelWithoutAccessKeys),
                    AllowCancellation = true,
                    Buttons           = { installMissingButton, runAnywayButton, doNotRunButton, TaskDialogButton.Cancel }
                };

                var selectedButton = taskDialog.ShowModal();
                if (selectedButton == installMissingButton)
                {
                    var ui = new VsPackageManagerUI(project.Site);
                    if (!pm.IsReady)
                    {
                        await pm.PrepareAsync(ui, CancellationToken.None);
                    }
                    await pm.InstallAsync(PackageSpec.FromArguments(string.Join(" ", packagesToInstall)), ui, CancellationToken.None);
                }
                else if (selectedButton == runAnywayButton)
                {
                }
                else
                {
                    throw new TaskCanceledException();
                }
            }

            if (startInfo.TargetType == PythonCommandTask.TargetTypePip)
            {
                if (startInfo.ExecuteInOutput && pm != null)
                {
                    var ui = new VsPackageManagerUI(project.Site);
                    if (!pm.IsReady)
                    {
                        await pm.PrepareAsync(ui, CancellationToken.None);
                    }
                    await pm.InstallAsync(
                        PackageSpec.FromArguments(string.IsNullOrEmpty(startInfo.Arguments) ? startInfo.Filename : "{0} {1}".FormatUI(startInfo.Filename, startInfo.Arguments)),
                        ui,
                        CancellationToken.None
                        );

                    return;
                }

                // Rewrite start info to execute
                startInfo.TargetType = PythonCommandTask.TargetTypeModule;
                startInfo.AddArgumentAtStart(startInfo.Filename);
                startInfo.Filename = "pip";
            }

            if (startInfo.ExecuteInRepl)
            {
                if (await RunInRepl(project, startInfo))
                {
                    return;
                }
            }

            startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false));

            if (startInfo.ExecuteInOutput)
            {
                RunInOutput(project, startInfo);
            }
            else
            {
                RunInConsole(project, startInfo);
            }
        }
        private DialogMessageResult DoOokiiMsgBox()
        {
            using (TaskDialog td = new TaskDialog())
            {
                if ((Buttons & DialogMessageButtons.Ok) != 0)
                {
                    td.Buttons.Add(new TaskDialogButton(ButtonType.Ok));
                }
                if ((Buttons & DialogMessageButtons.Cancel) != 0)
                {
                    td.Buttons.Add(new TaskDialogButton(ButtonType.Cancel));
                }
                if ((Buttons & DialogMessageButtons.Yes) != 0)
                {
                    td.Buttons.Add(new TaskDialogButton(ButtonType.Yes));
                }
                if ((Buttons & DialogMessageButtons.No) != 0)
                {
                    td.Buttons.Add(new TaskDialogButton(ButtonType.No));
                }
                if ((Buttons & DialogMessageButtons.Close) != 0)
                {
                    td.Buttons.Add(new TaskDialogButton(ButtonType.Close));
                }
                if ((Buttons & DialogMessageButtons.Retry) != 0)
                {
                    td.Buttons.Add(new TaskDialogButton(ButtonType.Retry));
                }
                switch (Icon)
                {
                case DialogMessageIcon.Error:
                    td.MainIcon = TaskDialogIcon.Error;
                    break;

                case DialogMessageIcon.Question:
                    td.MainIcon = TaskDialogIcon.Shield;
                    break;

                case DialogMessageIcon.Warning:
                    td.MainIcon = TaskDialogIcon.Warning;
                    break;

                case DialogMessageIcon.Information:
                    td.MainIcon = TaskDialogIcon.Information;
                    break;

                case DialogMessageIcon.Shield:
                    td.MainIcon = TaskDialogIcon.Shield;
                    break;
                }
                td.WindowTitle     = Title;
                td.MainInstruction = Text;
                td.Content         = Extra;
                TaskDialogButton result = null;
                if (owner == null)
                {
                    result = td.ShowDialog();
                }
                else
                {
                    var dispatcher = owner.Dispatcher;
                    result = (TaskDialogButton)dispatcher.Invoke(new Func <TaskDialogButton>(() => td.ShowDialog(owner)), System.Windows.Threading.DispatcherPriority.Normal);
                }
                switch (result.ButtonType)
                {
                case ButtonType.Cancel:
                    return(DialogMessageResult.Cancel);

                case ButtonType.Close:
                    return(DialogMessageResult.Close);

                case ButtonType.Custom:
                    return(DialogMessageResult.CustomButtonClicked);

                case ButtonType.No:
                    return(DialogMessageResult.No);

                case ButtonType.Ok:
                    return(DialogMessageResult.OK);

                case ButtonType.Retry:
                    return(DialogMessageResult.Retry);

                case ButtonType.Yes:
                    return(DialogMessageResult.Yes);
                }
            }

            return(DialogMessageResult.None);
        }
        private DialogMessageResult DoOokiiMsgBox()
        {
            TaskDialog td = new TaskDialog();

            if ((Buttons & DialogMessageButtons.Ok) != 0)
            {
                td.Buttons.Add(new TaskDialogButton(ButtonType.Ok));
            }
            if ((Buttons & DialogMessageButtons.Cancel) != 0)
            {
                td.Buttons.Add(new TaskDialogButton(ButtonType.Cancel));
            }

            if ((Buttons & DialogMessageButtons.Yes) != 0)
            {
                td.Buttons.Add(new TaskDialogButton(ButtonType.Yes));
            }
            if ((Buttons & DialogMessageButtons.No) != 0)
            {
                td.Buttons.Add(new TaskDialogButton(ButtonType.No));
            }

            if ((Buttons & DialogMessageButtons.Close) != 0)
            {
                td.Buttons.Add(new TaskDialogButton(ButtonType.Close));
            }
            if ((Buttons & DialogMessageButtons.Retry) != 0)
            {
                td.Buttons.Add(new TaskDialogButton(ButtonType.Retry));
            }

            switch (Icon)
            {
            case DialogMessageIcon.Error:
                td.MainIcon = TaskDialogIcon.Error;
                break;

            case DialogMessageIcon.Question:
                td.MainIcon = TaskDialogIcon.Warning;
                break;

            case DialogMessageIcon.Warning:
                td.MainIcon = TaskDialogIcon.Warning;
                break;

            case DialogMessageIcon.Information:
                td.MainIcon = TaskDialogIcon.Information;
                break;

            case DialogMessageIcon.Shield:
                td.MainIcon = TaskDialogIcon.Shield;
                break;
            }

            td.WindowTitle     = Title;
            td.MainInstruction = Text;
            td.Content         = Extra;

            var translation = new Dictionary <TaskDialogButton, ButtonType>();

            if (ButtonExtras != null && ButtonExtras.Any())
            {
                td.ButtonStyle = TaskDialogButtonStyle.CommandLinks;

                var buttonSet = td.Buttons.ToArray();
                td.Buttons.Clear();

                foreach (var extra in ButtonExtras)
                {
                    foreach (var button in buttonSet.Where(b => b.ButtonType == extra.ButtonType))
                    {
                        button.ButtonType      = ButtonType.Custom;
                        button.Text            = extra.Text;
                        button.CommandLinkNote = extra.Note;

                        translation.Add(button, extra.ButtonType);
                        td.Buttons.Add(button);
                    }
                }

                foreach (var button in buttonSet.Where(b => b.ButtonType != ButtonType.Custom))
                {
                    td.Buttons.Add(button);
                }
            }

            TaskDialogButton result = null;

            if (owner == null)
            {
                result = td.ShowDialog();
            }
            else
            {
                var dispatcher = owner.Dispatcher;

                result = (TaskDialogButton)dispatcher.Invoke(
                    new Func <TaskDialogButton>(() => td.ShowDialog(owner)),
                    System.Windows.Threading.DispatcherPriority.Normal);
            }

            var resultButtonType = result.ButtonType;

            if (resultButtonType == ButtonType.Custom)
            {
                resultButtonType = translation[result];
            }

            switch (resultButtonType)
            {
            case ButtonType.Cancel:
                return(DialogMessageResult.Cancel);

            case ButtonType.Close:
                return(DialogMessageResult.Close);

            case ButtonType.No:
                return(DialogMessageResult.No);

            case ButtonType.Ok:
                return(DialogMessageResult.OK);

            case ButtonType.Retry:
                return(DialogMessageResult.Retry);

            case ButtonType.Yes:
                return(DialogMessageResult.Yes);
            }

            return(DialogMessageResult.None);
        }
Пример #39
0
        public int ShowMessage(string body, IReadOnlyCollection <string> buttons, string title = null, string extendedInfo = null, InteractionResult systemButtons = InteractionResult.None)
        {
            var taskDialog = new TaskDialog
            {
                MainIcon    = TaskDialogIcon.Information,
                ButtonStyle = TaskDialogButtonStyle.CommandLinks
            };

            foreach (var item in buttons)
            {
                var btn = new TaskDialogButton(ButtonType.Custom)
                {
                    Text = item
                };

                taskDialog.Buttons.Add(btn);
            }

            if (systemButtons != InteractionResult.None)
            {
                var bts = new[] { InteractionResult.Yes, InteractionResult.No, InteractionResult.OK, InteractionResult.Cancel, InteractionResult.Close };
                foreach (var bt in bts)
                {
                    if ((systemButtons & bt) == bt)
                    {
                        taskDialog.Buttons.Add(new TaskDialogButton((ButtonType)(int)bt));
                    }
                }
            }

            taskDialog.CenterParent = true;
            taskDialog.Content      = body;

            if (!string.IsNullOrEmpty(extendedInfo))
            {
                taskDialog.ExpandedInformation = extendedInfo;
            }

            taskDialog.WindowTitle = title ?? "MSIX Hero";

            int clickedIndex = -1;
            // ReSharper disable once ConvertToLocalFunction
            EventHandler <TaskDialogItemClickedEventArgs> handler = (_, args) =>
            {
                var taskDialogButton = args.Item as TaskDialogButton;
                if (taskDialogButton == null)
                {
                    return;
                }

                clickedIndex = taskDialog.Buttons.IndexOf(taskDialogButton);
            };

            try
            {
                taskDialog.ButtonClicked += handler;

                if (this.context == null)
                {
                    taskDialog.ShowDialog(GetActiveWindow());
                }

                var dispatcher = Application.Current.Dispatcher;
                if (dispatcher != null)
                {
                    dispatcher.Invoke(() =>
                    {
                        this.context.Send(
                            _ => taskDialog.ShowDialog(GetActiveWindow()),
                            null);
                    },
                                      DispatcherPriority.SystemIdle);
                }
            }
            finally
            {
                taskDialog.ButtonClicked -= handler;
            }

            return(clickedIndex);
        }
Пример #40
0
 /// <summary>Displays a task dialog that has a message, a title, an instruction, one or more buttons and an icon.</summary>
 /// <param name="title">The title bar caption of the dialog.</param>
 /// <param name="instruction">The instruction shown below the main text.</param>
 /// <param name="buttons">Value that specifies which button or buttons to display.</param>
 /// <param name="icon">The icon to display.</param>
 public static Result Show(string instruction, string title, string content, TaskDialogButton buttons, TaskDialogIcon icon)
 {
     return InternalShow(IntPtr.Zero, title, instruction, content, buttons, icon);
 }
Пример #41
0
        private async Task ExecuteWorker(PythonProjectNode project) {
            _errorListProvider.Tasks.Clear();

            var interpFactory = project.GetInterpreterFactoryOrThrow();
            var startInfo = GetStartInfo(project);

            var packagesToInstall = new List<string>();
            foreach (var pkg in startInfo.RequiredPackages) {
                if (!await Pip.IsInstalled(interpFactory, pkg)) {
                    packagesToInstall.Add(pkg);
                }
            }

            if (packagesToInstall.Any()) {
                var installMissingButton = new TaskDialogButton(
                    Strings.CustomCommandPrerequisitesInstallMissing,
                    Strings.CustomCommandPrerequisitesInstallMissingSubtext + "\r\n\r\n" + string.Join("\r\n", packagesToInstall));
                var runAnywayButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesRunAnyway);
                var doNotRunButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesDoNotRun);

                var taskDialog = new TaskDialog(project.Site) {
                    Title = Strings.ProductTitle,
                    MainInstruction = Strings.CustomCommandPrerequisitesInstruction,
                    Content = Strings.CustomCommandPrerequisitesContent.FormatUI(DisplayLabelWithoutAccessKeys),
                    AllowCancellation = true,
                    Buttons = { installMissingButton, runAnywayButton, doNotRunButton, TaskDialogButton.Cancel }
                };

                var selectedButton = taskDialog.ShowModal();
                if (selectedButton == installMissingButton) {
                    await Pip.Install(
                        project.Site,
                        interpFactory,
                        string.Join(" ", packagesToInstall),
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site));
                } else if (selectedButton == runAnywayButton) {
                } else {
                    throw new TaskCanceledException();
                }
            }

            if (startInfo.TargetType == CreatePythonCommandItem.TargetTypePip) {
                if (startInfo.ExecuteInOutput) {
                    await Pip.Install(
                        _project.Site,
                        interpFactory,
                        string.IsNullOrEmpty(startInfo.Arguments) ?
                            startInfo.Filename :
                            string.Format("{0} {1}", startInfo.Filename, startInfo.Arguments),
                        project.Site,
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site)
                    );
                    return;
                }

                // Rewrite start info to execute 
                startInfo.TargetType = CreatePythonCommandItem.TargetTypeModule;
                startInfo.AddArgumentAtStart(startInfo.Filename);
                startInfo.Filename = "pip";
            }

            if (startInfo.ExecuteInRepl) {
                if (await RunInRepl(project, startInfo)) {
                    return;
                }
            }

            startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false));

            if (startInfo.ExecuteInOutput) {
                RunInOutput(project, startInfo);
            } else {
                RunInConsole(project, startInfo);
            }
        }
Пример #42
0
 static TaskDialogPage CreateManualSetupPage(TaskDialogButton quitButton) => new()
Пример #43
0
        private async Task ExecuteWorker(PythonProjectNode project)
        {
            _errorListProvider.Tasks.Clear();

            var interpFactory = project.GetInterpreterFactoryOrThrow();
            var startInfo     = GetStartInfo(project);

            var packagesToInstall = new List <string>();

            foreach (var pkg in startInfo.RequiredPackages)
            {
                if (!await Pip.IsInstalled(interpFactory, pkg))
                {
                    packagesToInstall.Add(pkg);
                }
            }

            if (packagesToInstall.Any())
            {
                var installMissingButton = new TaskDialogButton(
                    Strings.CustomCommandPrerequisitesInstallMissing,
                    Strings.CustomCommandPrerequisitesInstallMissingSubtext + "\r\n\r\n" + string.Join("\r\n", packagesToInstall));
                var runAnywayButton = new TaskDialogButton(Strings.CustomCommandPrerequisitesRunAnyway);
                var doNotRunButton  = new TaskDialogButton(Strings.CustomCommandPrerequisitesDoNotRun);

                var taskDialog = new TaskDialog(project.Site)
                {
                    Title             = Strings.ProductTitle,
                    MainInstruction   = Strings.CustomCommandPrerequisitesInstruction,
                    Content           = Strings.CustomCommandPrerequisitesContent.FormatUI(DisplayLabelWithoutAccessKeys),
                    AllowCancellation = true,
                    Buttons           = { installMissingButton, runAnywayButton, doNotRunButton, TaskDialogButton.Cancel }
                };

                var selectedButton = taskDialog.ShowModal();
                if (selectedButton == installMissingButton)
                {
                    await Pip.Install(
                        project.Site,
                        interpFactory,
                        string.Join(" ", packagesToInstall),
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site));
                }
                else if (selectedButton == runAnywayButton)
                {
                }
                else
                {
                    throw new TaskCanceledException();
                }
            }

            if (startInfo.TargetType == CreatePythonCommandItem.TargetTypePip)
            {
                if (startInfo.ExecuteInOutput)
                {
                    await Pip.Install(
                        _project.Site,
                        interpFactory,
                        string.IsNullOrEmpty(startInfo.Arguments)?
                        startInfo.Filename :
                        string.Format("{0} {1}", startInfo.Filename, startInfo.Arguments),
                        project.Site,
                        false,
                        OutputWindowRedirector.GetGeneral(project.Site)
                        );

                    return;
                }

                // Rewrite start info to execute
                startInfo.TargetType = CreatePythonCommandItem.TargetTypeModule;
                startInfo.AddArgumentAtStart(startInfo.Filename);
                startInfo.Filename = "pip";
            }

            if (startInfo.ExecuteInRepl)
            {
                if (await RunInRepl(project, startInfo))
                {
                    return;
                }
            }

            startInfo.AdjustArgumentsForProcessStartInfo(GetInterpreterPath(project, false));

            if (startInfo.ExecuteInOutput)
            {
                RunInOutput(project, startInfo);
            }
            else
            {
                RunInConsole(project, startInfo);
            }
        }
Пример #44
0
 static TaskDialogPage CreateInitialPage(TaskDialogButton downloadButton, TaskDialogButton manualDownload) => new()
Пример #45
0
        private static Result InternalShow(IntPtr parent, string title, string instruction, string content, TaskDialogButton commonButtons, TaskDialogIcon icon)
        {
            int dlgValue;

            try {
                //Get handle for parent window if none specified (behave like MessageBox)
                if (parent == IntPtr.Zero)
                {
                    parent = GetActiveWindow();
                }

                if (NativeMethods.TaskDialog(parent, IntPtr.Zero, title, instruction, content, (int)commonButtons, new IntPtr((long)icon), out dlgValue) != 0)
                {
                    throw new Exception(String.Format("Native call to {0} failed.", "TaskDialog"));
                }
            }
            catch (EntryPointNotFoundException ex) {
                throw new Exception("Common Controls library version 6.0 not loaded. Must run on Vista and must provide a manifest.", ex);
            }
            catch (Exception ex) {
                throw new Exception("Failed to create TaskDialog.", ex);
            }

            //Convert int value to common dialog result
            if (dlgValue > 0 && dlgValue <= 8)
            {
                return((Result)dlgValue);
            }
            else
            {
                return(Result.None);
            }
        }
Пример #46
0
        private static void ShowTaskDialog()
        {
            var dialogPage = new TaskDialogPage()
            {
                Heading = "USB Function Mode Switcher",
                Caption = "Select a USB function mode to switch to",
                Text    = "Below are the available modes your phone supports switching to.",

                Footnote =
                {
                    Text = "Switching modes will require a reboot of the device.",
                    Icon = TaskDialogIcon.Warning,
                },

                AllowCancel   = true,
                SizeToContent = true
            };

            try
            {
                var handler = new USBRoleHandler();

                foreach (var role in handler.USBRoles)
                {
                    var rolebutton = new TaskDialogCommandLinkButton(role.DisplayName, role.Description);
                    if (role.IsHost && role.HostRole.EnableVbus)
                    {
                        rolebutton.AllowCloseDialog = false;
                    }
                    dialogPage.Buttons.Add(rolebutton);

                    if (role == handler.CurrentUSBRole)
                    {
                        rolebutton.Enabled = false;
                    }

                    rolebutton.Click += (object sender, EventArgs args) =>
                    {
                        if (role.IsHost && role.HostRole.EnableVbus)
                        {
                            ShowDisclaimerDialog(dialogPage, () =>
                            {
                                handler.CurrentUSBRole = role;
                                RebootDevice();
                            });
                        }
                        else
                        {
                            handler.CurrentUSBRole = role;
                            RebootDevice();
                        }
                    };
                }

                if (USBRoleHandler.IsUSBCv2())
                {
                    var polaritybutton = new TaskDialogCommandLinkButton("Polarity", "Change the polarity of the USB C port");
                    polaritybutton.AllowCloseDialog = false;
                    dialogPage.Buttons.Add(polaritybutton);
                    polaritybutton.Click += (object sender, EventArgs args) =>
                    {
                        ShowPolarityDialog(dialogPage);
                    };
                }

                var aboutbutton = new TaskDialogCommandLinkButton("About", "About USB Function Mode Switcher", allowCloseDialog: false);
                dialogPage.Buttons.Add(aboutbutton);
                aboutbutton.Click += (object sender, EventArgs args) =>
                {
                    ShowAboutDialog(dialogPage);
                };

                TaskDialogButton result = TaskDialog.ShowDialog(dialogPage);
            }
            catch (Exception ex)
            {
                dialogPage = new TaskDialogPage()
                {
                    Heading       = "USB Function Mode Switcher",
                    Caption       = "Something happened",
                    Text          = ex.ToString(),
                    AllowCancel   = true,
                    SizeToContent = true,
                    Icon          = TaskDialogIcon.Error
                };

                var closemainbutton = new TaskDialogCommandLinkButton("Close");
                var aboutbutton     = new TaskDialogCommandLinkButton("About", "About USB Function Mode Switcher", allowCloseDialog: false);
                dialogPage.Buttons.Add(closemainbutton);
                dialogPage.Buttons.Add(aboutbutton);

                aboutbutton.Click += (object sender, EventArgs args) =>
                {
                    ShowAboutDialog(dialogPage);
                };

                TaskDialogButton result = TaskDialog.ShowDialog(dialogPage);
            }
        }
Пример #47
0
        public static void Main()
        {
            try
            {
                CultureInfo cInf = new CultureInfo(RegistrySettings.Default.UiCulture);
                Loksim3D.WetterEdit.Resources.Strings.Culture = cInf;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show("Invalid Language Settings " + RegistrySettings.Default.UiCulture + "\n" + ex.Message);
            }


            if (Environment.OSVersion.Version.Major >= 6 && RegistrySettings.Default.DefaultAdminStartMode != RegistrySettings.AdminStartMode.DoNotStartAsAdmin)
            {
                // Unter Vista oder höher prüfen ob wir in das Datenverzeichnis lt. paths.ini schreiben dürfen
                // Wenn nicht schauen wir ob wir als Admin ausgeführt werden
                // Wenn nicht als Admin ausgeführt => User fragen ob als Admin ausführen bzw in Optionen nachschauen was user möchte

                string datadir = L3dFilePath.LoksimDirectory.AbsolutePath;

                try
                {
                    string file = TempFileUtility.GetTempFileName("l3d", 0, datadir /*Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)*/);
                    File.Delete(file);
                }
                catch (Win32Exception ex)
                {
                    if (ex.ErrorCode == TempFileUtility.ERROR_ACCESS_DENIED)
                    {
                        IntPtr tkHandle;
                        IntPtr procHandle = Process.GetCurrentProcess().Handle;
                        Win32Utility.OpenProcessToken(procHandle,
                                                      (uint)System.Security.Principal.TokenAccessLevels.Read, out tkHandle);

                        uint TokenInfLength = 0;
                        bool Result;

                        // first call gets lenght of TokenInformation
                        Result = Win32Utility.GetTokenInformation(tkHandle, Win32Utility.TOKEN_INFORMATION_CLASS.TokenElevation, IntPtr.Zero, TokenInfLength, out TokenInfLength);
                        IntPtr TokenInformation = Marshal.AllocHGlobal((int)TokenInfLength);

                        Result = Win32Utility.GetTokenInformation(tkHandle, Win32Utility.TOKEN_INFORMATION_CLASS.TokenElevation, TokenInformation, TokenInfLength, out TokenInfLength);
                        if (Result)
                        {
                            Win32Utility.TOKEN_ELEVATION TokenElevation = (Win32Utility.TOKEN_ELEVATION)Marshal.PtrToStructure(TokenInformation, typeof(Win32Utility.TOKEN_ELEVATION));
                            TaskDialog dlg = new TaskDialog
                            {
                                Caption               = Strings.UacDlgCaption,
                                InstructionText       = Strings.UacDlgInstructionText,
                                Text                  = Strings.UacDlgText,
                                FooterCheckBoxChecked = false,
                                FooterCheckBoxText    = Strings.UacDlgCheckBoxText,
                                Cancelable            = false,
                            };
                            TaskDialogButton btn = new TaskDialogButton {
                                Text = Strings.UacDlgBtnAdmin, UseElevationIcon = true, Default = true
                            };
                            btn.Click += (sender, e) => dlg.Close(TaskDialogResult.Yes);
                            dlg.Controls.Add(btn);
                            btn = new TaskDialogButton {
                                Text = Strings.UacDlgBtnNoAdmin
                            };
                            btn.Click += (sender, e) => dlg.Close(TaskDialogResult.No);
                            dlg.Controls.Add(btn);
                            if (RegistrySettings.Default.DefaultAdminStartMode == RegistrySettings.AdminStartMode.StartAsAdmin || dlg.Show() == TaskDialogResult.Yes)
                            {
                                if (dlg.FooterCheckBoxChecked.GetValueOrDefault(false))
                                {
                                    RegistrySettings.Default.DefaultAdminStartMode = RegistrySettings.AdminStartMode.StartAsAdmin;
                                }

                                ProcessStartInfo info = new ProcessStartInfo();
                                info.FileName        = System.Reflection.Assembly.GetCallingAssembly().Location;
                                info.UseShellExecute = true;
                                info.Verb            = "runas"; // Provides Run as Administrator
                                info.Arguments       = EscapeCommandLineArguments(Environment.GetCommandLineArgs());
                                Process.Start(info);
                                Marshal.FreeHGlobal(TokenInformation);
                                return;
                            }
                            else if (RegistrySettings.Default.DefaultAdminStartMode == RegistrySettings.AdminStartMode.Ask && dlg.FooterCheckBoxChecked.GetValueOrDefault(false))
                            {
                                RegistrySettings.Default.DefaultAdminStartMode = RegistrySettings.AdminStartMode.DoNotStartAsAdmin;
                            }
                        }
                        Marshal.FreeHGlobal(TokenInformation);
                    }
                }
            }

            // Der Editor soll pro Installation nur 1x gestartet werden können.
            // Hat der User mehrere Editoren in unterschiedlichen Verzeichnissen oder mit unterschiedlichen Namen, kann er diese jeweils 1x starten
            // Deshalb ist in der Unique-ID auch noch die Assembly Location kodiert
            if (SingleInstance <App> .InitializeAsFirstInstance(Unique + "-" + System.Reflection.Assembly.GetCallingAssembly().Location.GetHashCode()))
            {
                var application = new App();

                application.InitializeComponent();
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
        }