Ejemplo n.º 1
0
        private void WarnAboutPythonSymbols(string moduleName)
        {
            var dialog = new TaskDialog(_serviceProvider);

            var openSymbolSettings = new TaskDialogButton(Strings.MixedModeDebugSymbolsRequiredOpenSymbolSettings);
            var downloadSymbols    = new TaskDialogButton(Strings.MixedModeDebugSymbolsRequiredDownloadSymbols);

            dialog.Buttons.Add(openSymbolSettings);
            dialog.Buttons.Add(downloadSymbols);
            dialog.Buttons.Add(TaskDialogButton.Close);
            dialog.UseCommandLinks = true;
            dialog.Title           = Strings.MixedModeDebugSymbolsRequiredTitle;
            dialog.Content         = Strings.MixedModeDebugSymbolsRequiredMessage.FormatUI(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(
                    _serviceProvider,
                    string.Format("http://go.microsoft.com/fwlink/?LinkId=308954&clcid=0x{0:X}", CultureInfo.CurrentCulture.LCID)
                    );
            }
        }
Ejemplo n.º 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));
            }
        }
Ejemplo n.º 3
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));
            }
        }
Ejemplo n.º 4
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.Configuration.PrefixPath, "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;
            }
        }
Ejemplo n.º 5
0
        private bool ShouldIncludeNodeModulesFolderInProject()
        {
            var includeNodeModulesButton = new TaskDialogButton(SR.GetString(SR.IncludeNodeModulesIncludeTitle), SR.GetString(SR.IncludeNodeModulesIncludeDescription));
            var cancelOperationButton    = new TaskDialogButton(SR.GetString(SR.IncludeNodeModulesCancelTitle));
            var taskDialog = new TaskDialog(_project.ProjectMgr.Site)
            {
                AllowCancellation = true,
                EnableHyperlinks  = true,
                Title             = SR.ProductName,
                MainIcon          = TaskDialogIcon.Warning,
                Content           = SR.GetString(SR.IncludeNodeModulesContent),
                Buttons           =
                {
                    cancelOperationButton,
                    includeNodeModulesButton
                },
                FooterIcon     = TaskDialogIcon.Information,
                Footer         = SR.GetString(SR.IncludeNodeModulesInformation),
                SelectedButton = cancelOperationButton
            };

            var button = taskDialog.ShowModal();

            return(button == includeNodeModulesButton);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 7
0
        internal static bool LaunchFile(IServiceProvider provider, string filename, bool debug, bool saveDirtyFiles)
        {
            var project = (IPythonProject)provider.GetProjectFromOpenFile(filename) ?? new DefaultPythonProject(provider, filename);

            try {
                var starter = GetLauncher(provider, project);
                if (starter == null)
                {
                    Debug.Fail("Failed to get project launcher");
                    return(false);
                }

                if (saveDirtyFiles)
                {
                    var rdt = provider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
                    if (rdt != null)
                    {
                        // Consider using (uint)(__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty | __VSRDTSAVEOPTIONS.RDTSAVEOPT_PromptSave)
                        // when VS settings include prompt for save on build
                        var saveOpt = (uint)__VSRDTSAVEOPTIONS.RDTSAVEOPT_SaveIfDirty;
                        var hr      = rdt.SaveDocuments(saveOpt, null, VSConstants.VSITEMID_NIL, VSConstants.VSCOOKIE_NIL);
                        if (hr == VSConstants.E_ABORT)
                        {
                            return(false);
                        }
                    }
                }

                starter.LaunchFile(filename, debug);
            } catch (MissingInterpreterException ex) {
                var interpreterRegistry = provider.GetComponentModel().GetService <IInterpreterRegistryService>();
                if (project.GetInterpreterFactory() == interpreterRegistry.NoInterpretersValue)
                {
                    OpenNoInterpretersHelpPage(provider, ex.HelpPage);
                }
                else
                {
                    var td = new TaskDialog(provider)
                    {
                        Title           = Strings.ProductTitle,
                        MainInstruction = Strings.FailedToLaunchDebugger,
                        Content         = ex.Message
                    };
                    td.Buttons.Add(TaskDialogButton.Close);
                    td.ShowModal();
                }
                return(false);
            } catch (NoInterpretersException ex) {
                OpenNoInterpretersHelpPage(provider, ex.HelpPage);
                return(false);
            } catch (IOException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 8
0
        public override int DebugLaunch(uint flags)
        {
            if (_project.ShouldWarnOnLaunch)
            {
                var pyService = ProjectMgr.Site.GetPythonToolsService();
                if (pyService.DebuggerOptions.PromptBeforeRunningWithBuildError)
                {
                    var res = new StartWithErrorsDialog(pyService).ShowDialog();
                    if (res == DialogResult.No)
                    {
                        return(VSConstants.S_OK);
                    }
                }
            }

            string errorMessage = null;

            try {
                return(base.DebugLaunch(flags));
            } catch (MissingInterpreterException ex) {
                if (_project.ActiveInterpreter == _project.InterpreterRegistry.NoInterpretersValue)
                {
                    PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
                }
                else
                {
                    errorMessage = ex.Message;
                }
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
            } catch (IOException ex) {
                errorMessage = ex.Message;
            } catch (NoStartupFileException ex) {
                errorMessage = ex.Message;
            } catch (ArgumentException ex) {
                // Previously used to handle "No startup file" which now has its own exception.
                // Keeping it in case some launchers started relying on us catching this.
                errorMessage = ex.Message;
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                var td = new TaskDialog(ProjectMgr.Site)
                {
                    Title             = Strings.ProductTitle,
                    MainInstruction   = Strings.FailedToLaunchDebugger,
                    Content           = errorMessage,
                    AllowCancellation = true
                };
                td.Buttons.Add(TaskDialogButton.Close);
                td.ShowModal();
            }

            return(VSConstants.S_OK);
        }
Ejemplo n.º 9
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.ProductTitle,
                    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);
        }
Ejemplo n.º 10
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            var provider = WizardHelpers.GetProvider(automationObject);

            try {
                if (AreToolsInstalled(provider))
                {
                    // If we fail to find the wizard, we will redirect the user to
                    // install the required packages.
                    var asm  = Assembly.Load("Microsoft.VisualStudio.CloudService.Wizard,Version=1.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a");
                    var type = asm.GetType("Microsoft.VisualStudio.CloudService.Wizard.CloudServiceWizard");
                    _wizard = type.InvokeMember(null, BindingFlags.CreateInstance, null, null, new object[0], CultureInfo.CurrentCulture) as IWizard;
                }
            } catch (ArgumentException) {
            } catch (BadImageFormatException) {
            } catch (IOException) {
            } catch (MemberAccessException) {
            }

            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)
                {
                    InstallTools(provider);
                    throw new WizardCancelledException();
                }

                // 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);
        }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
0
        public static void CallWithRetry(
            Action <int> action,
            IServiceProvider provider,
            string title,
            string failedText,
            string expandControlText,
            string retryButtonText,
            string cancelButtonText,
            Func <Exception, bool> canRetry = null
            )
        {
            for (int retryCount = 1; ; ++retryCount)
            {
                try
                {
                    action(retryCount);
                    return;
                }
                catch (Exception ex)
                {
                    if (ex.IsCriticalException())
                    {
                        throw;
                    }
                    if (canRetry != null && !canRetry(ex))
                    {
                        throw;
                    }

                    var td = new TaskDialog(provider)
                    {
                        Title                = title,
                        MainInstruction      = failedText,
                        Content              = ex.Message,
                        CollapsedControlText = expandControlText,
                        ExpandedControlText  = expandControlText,
                        ExpandedInformation  = ex.ToString()
                    };
                    var retry = new TaskDialogButton(retryButtonText);
                    td.Buttons.Add(retry);
                    td.Buttons.Add(new TaskDialogButton(cancelButtonText));
                    var button = td.ShowModal();
                    if (button != retry)
                    {
                        throw new OperationCanceledException();
                    }
                }
            }
        }
Ejemplo n.º 13
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();
                }
            }
        }
Ejemplo n.º 14
0
        public override int DebugLaunch(uint flags)
        {
            if (_project.ShouldWarnOnLaunch)
            {
                var pyService = ProjectMgr.Site.GetPythonToolsService();
                if (pyService.DebuggerOptions.PromptBeforeRunningWithBuildError)
                {
                    var res = new StartWithErrorsDialog(pyService).ShowDialog();
                    if (res == DialogResult.No)
                    {
                        return(VSConstants.S_OK);
                    }
                }
            }

            string errorMessage = null;

            try {
                return(base.DebugLaunch(flags));
            } catch (MissingInterpreterException ex) {
                if (_project.ActiveInterpreter == _project.InterpreterRegistry.NoInterpretersValue)
                {
                    PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
                }
                else
                {
                    errorMessage = ex.Message;
                }
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(ProjectMgr.Site, ex.HelpPage);
            } catch (ArgumentException ex) {
                errorMessage = ex.Message;
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                var td = new TaskDialog(ProjectMgr.Site)
                {
                    Title           = Strings.ProductTitle,
                    MainInstruction = Strings.FailedToLaunchDebugger,
                    Content         = errorMessage
                };
                td.Buttons.Add(TaskDialogButton.Close);
                td.ShowModal();
            }

            return(VSConstants.S_OK);
        }
Ejemplo n.º 15
0
        private static void ShowDebuggingErrorMessage(string main, string content, bool allowDisable, bool isError)
        {
            var serviceProvider = VisualStudio.Shell.ServiceProvider.GlobalProvider;

            try {
                serviceProvider.GetUIThread().Invoke(() => {
                    var dlg = new TaskDialog(serviceProvider)
                    {
                        Title             = Strings.ProductTitle,
                        MainInstruction   = main,
                        Content           = content,
                        AllowCancellation = true,
                        MainIcon          = isError ? TaskDialogIcon.Error : TaskDialogIcon.Warning,
                        EnableHyperlinks  = true,
                    };

                    var disable   = new TaskDialogButton(Strings.PtvsdDisableCaption, Strings.PtvsdDisableSubtext);
                    var learnMore = new TaskDialogButton(Strings.PtvsdLearnMoreCaption, Strings.PtvsdLearnMoreSubtext);

                    dlg.Buttons.Add(TaskDialogButton.OK);
                    dlg.Buttons.Insert(0, learnMore);
                    if (allowDisable)
                    {
                        dlg.Buttons.Insert(0, disable);
                    }

                    var selection = dlg.ShowModal();
                    if (selection == learnMore)
                    {
                        Process.Start("https://aka.ms/upgradeptvsd")?.Dispose();
                    }
                    else if (selection == disable)
                    {
                        var debuggerOptions = ((PythonToolsService)Package.GetGlobalService(typeof(PythonToolsService))).DebuggerOptions;
                        debuggerOptions.UseLegacyDebugger = true;
                        debuggerOptions.Save();
                    }
                });
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                ex.ReportUnhandledException(serviceProvider, typeof(DebugPyVersionHelper));
            }
        }
Ejemplo n.º 16
0
        public static async Task ShowModalDelayed(
            this TaskDialog dialog, CancellationToken cancellationToken, TimeSpan?delay = null)
        {
            var dispatcher = Dispatcher.FromThread(Thread.CurrentThread);

            if (dispatcher == null)
            {
                throw new InvalidOperationException("Current thread has no dispatcher");
            }

            try {
                await Delay(dispatcher, delay ?? TimeSpan.FromMilliseconds(250), cancellationToken);

                if (!cancellationToken.IsCancellationRequested)
                {
                    dialog.ShowModal();
                }
            } catch (OperationCanceledException) {
            }
        }
Ejemplo n.º 17
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);
        }
Ejemplo n.º 18
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;
        }
Ejemplo n.º 19
0
        private static void ShowDebuggingErrorMessage(string main, string content, bool isError)
        {
            var serviceProvider = VisualStudio.Shell.ServiceProvider.GlobalProvider;

            try {
                serviceProvider.GetUIThread().Invoke(() => {
                    var dlg = new TaskDialog(serviceProvider)
                    {
                        Title             = Strings.ProductTitle,
                        MainInstruction   = main,
                        Content           = content,
                        AllowCancellation = true,
                        MainIcon          = isError ? TaskDialogIcon.Error : TaskDialogIcon.Warning,
                        EnableHyperlinks  = true,
                    };

                    dlg.Buttons.Add(TaskDialogButton.OK);
                    dlg.ShowModal();
                });
            } catch (Exception ex) when(!ex.IsCriticalException())
            {
                ex.ReportUnhandledException(serviceProvider, typeof(DebugPyVersionHelper));
            }
        }
Ejemplo n.º 20
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;
        }
Ejemplo n.º 21
0
        int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
        {
            if (pguidCmdGroup == GuidList.guidWebPackgeCmdId)
            {
                if (nCmdID == 0x101 /*  EnablePublishToWindowsAzureMenuItem*/)
                {
                    var        shell = (IVsShell)((IServiceProvider)this).GetService(typeof(SVsShell));
                    var        webPublishPackageGuid = GuidList.guidWebPackageGuid;
                    IVsPackage package;

                    int res = shell.LoadPackage(ref webPublishPackageGuid, out package);
                    if (!ErrorHandler.Succeeded(res))
                    {
                        return(res);
                    }

                    var cmdTarget = package as IOleCommandTarget;
                    if (cmdTarget != null)
                    {
                        res = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                        if (ErrorHandler.Succeeded(res))
                        {
                            // TODO: Check flag to see if we were notified
                            // about being added as a web role.
                            if (!AddWebRoleSupportFiles())
                            {
                                VsShellUtilities.ShowMessageBox(
                                    this,
                                    Strings.AddWebRoleSupportFiles,
                                    null,
                                    OLEMSGICON.OLEMSGICON_INFO,
                                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
                                    );
                            }
                        }
                        return(res);
                    }
                }
            }
            else if (pguidCmdGroup == PublishCmdGuid)
            {
                if (nCmdID == PublishCmdid)
                {
                    // Approximately duplicated in DjangoProject
                    var opts = _site.GetPythonToolsService().SuppressDialogOptions;
                    if (string.IsNullOrEmpty(opts.PublishToAzure30))
                    {
                        var td = new TaskDialog(_site)
                        {
                            Title             = Strings.ProductTitle,
                            MainInstruction   = Strings.PublishToAzure30,
                            Content           = Strings.PublishToAzure30Message,
                            VerificationText  = Strings.DontShowAgain,
                            SelectedVerified  = false,
                            AllowCancellation = true,
                            EnableHyperlinks  = true
                        };
                        td.Buttons.Add(TaskDialogButton.OK);
                        td.Buttons.Add(TaskDialogButton.Cancel);
                        if (td.ShowModal() == TaskDialogButton.Cancel)
                        {
                            return(VSConstants.S_OK);
                        }

                        if (td.SelectedVerified)
                        {
                            opts.PublishToAzure30 = "true";
                            opts.Save();
                        }
                    }
                }
            }

            return(_menuService.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut));
        }
Ejemplo n.º 22
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;
        }
Ejemplo n.º 23
0
        int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
            if (pguidCmdGroup == GuidList.guidWebPackgeCmdId) {
                if (nCmdID == 0x101 /*  EnablePublishToWindowsAzureMenuItem*/) {
                    var shell = (IVsShell)((IServiceProvider)this).GetService(typeof(SVsShell));
                    var webPublishPackageGuid = GuidList.guidWebPackageGuid;
                    IVsPackage package;

                    int res = shell.LoadPackage(ref webPublishPackageGuid, out package);
                    if (!ErrorHandler.Succeeded(res)) {
                        return res;
                    }

                    var cmdTarget = package as IOleCommandTarget;
                    if (cmdTarget != null) {
                        res = cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
                        if (ErrorHandler.Succeeded(res)) {
                            // TODO: Check flag to see if we were notified
                            // about being added as a web role.
                            if (!AddWebRoleSupportFiles()) {
                                VsShellUtilities.ShowMessageBox(
                                    this,
                                    Strings.AddWebRoleSupportFiles,
                                    null,
                                    OLEMSGICON.OLEMSGICON_INFO,
                                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
                                );
                            }
                        }
                        return res;
                    }
                }
            } else if (pguidCmdGroup == PublishCmdGuid) {
                if (nCmdID == PublishCmdid) {
                    // Approximately duplicated in DjangoProject
                    var opts = _site.GetPythonToolsService().SuppressDialogOptions;
                    if (string.IsNullOrEmpty(opts.PublishToAzure30)) {
                        var td = new TaskDialog(_site) {
                            Title = Strings.ProductTitle,
                            MainInstruction = Strings.PublishToAzure30,
                            Content = Strings.PublishToAzure30Message,
                            VerificationText = Strings.DontShowAgain,
                            SelectedVerified = false,
                            AllowCancellation = true,
                            EnableHyperlinks = true
                        };
                        td.Buttons.Add(TaskDialogButton.OK);
                        td.Buttons.Add(TaskDialogButton.Cancel);
                        if (td.ShowModal() == TaskDialogButton.Cancel) {
                            return VSConstants.S_OK;
                        }

                        if (td.SelectedVerified) {
                            opts.PublishToAzure30 = "true";
                            opts.Save();
                        }
                    }
                }
            }

            return _menuService.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
        }
Ejemplo n.º 24
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();
        }
Ejemplo n.º 25
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;
            }
        }
Ejemplo n.º 26
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);
            }
        }
Ejemplo n.º 27
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);
            }
        }
Ejemplo n.º 28
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();
                }
            }
        }
Ejemplo n.º 29
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();
                }
            }
        }
Ejemplo n.º 30
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);
        }
Ejemplo n.º 31
0
        internal static bool LaunchFile(IServiceProvider provider, string filename, bool debug, bool saveDirtyFiles)
        {
            bool isLaunchFileOpen = true;
            var  project          = (IPythonProject)provider.GetProjectFromOpenFile(filename);

            if (project == null)
            {
                project = (IPythonProject)provider.GetProjectContainingFile(filename);

                if (project == null)
                {
                    project = new DefaultPythonProject(provider, filename);
                }
                else
                {
                    isLaunchFileOpen = false;
                }
            }

            try {
                var starter = GetLauncher(provider, project);
                if (starter == null)
                {
                    Debug.Fail("Failed to get project launcher");
                    return(false);
                }

                if (saveDirtyFiles)
                {
                    if (!SaveDirtyFiles(provider, isLaunchFileOpen, ref filename))
                    {
                        return(false);
                    }
                }

                starter.LaunchFile(filename, debug);
            } catch (MissingInterpreterException ex) {
                var interpreterRegistry = provider.GetComponentModel().GetService <IInterpreterRegistryService>();
                if (project.GetInterpreterFactory() == interpreterRegistry.NoInterpretersValue)
                {
                    OpenNoInterpretersHelpPage(provider, ex.HelpPage);
                }
                else
                {
                    var td = new TaskDialog(provider)
                    {
                        Title           = Strings.ProductTitle,
                        MainInstruction = Strings.FailedToLaunchDebugger,
                        Content         = ex.Message
                    };
                    td.Buttons.Add(TaskDialogButton.Close);
                    td.ShowModal();
                }
                return(false);
            } catch (NoInterpretersException ex) {
                OpenNoInterpretersHelpPage(provider, ex.HelpPage);
                return(false);
            } catch (NoStartupFileException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            } catch (IOException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 32
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;
            }
        }
        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);
        }
Ejemplo n.º 34
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);
            }
        }
Ejemplo n.º 35
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;
            }
        }
Ejemplo n.º 36
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 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();
                }
            }
        }
Ejemplo n.º 38
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);
        }