示例#1
0
        private async void CreateProjectAndHandleErrors(
            IVsStatusbar statusBar,
            Microsoft.PythonTools.Project.ImportWizard.ImportWizard dlg,
            bool addToExistingSolution
            )
        {
            try {
                var path = await dlg.ImportSettings.CreateRequestedProjectAsync();

                if (File.Exists(path))
                {
                    object outRef = null, pathRef = ProcessOutput.QuoteSingleArgument(path);
                    _serviceProvider.GetDTE().Commands.Raise(
                        VSConstants.GUID_VSStandardCommandSet97.ToString("B"),
                        addToExistingSolution
                            ? (int)VSConstants.VSStd97CmdID.AddExistingProject
                            : (int)VSConstants.VSStd97CmdID.OpenProject,
                        ref pathRef,
                        ref outRef
                        );
                    statusBar.SetText("");
                    return;
                }
            } catch (UnauthorizedAccessException) {
                MessageBox.Show(Strings.ErrorImportWizardUnauthorizedAccess, Strings.ProductTitle);
            } catch (Exception ex) {
                CommonUtils.ActivityLogError(Strings.ProductTitle, ex.ToString());
                MessageBox.Show(Strings.ErrorImportWizardException.FormatUI(ex.GetType().Name), Strings.ProductTitle);
            }
            statusBar.SetText(Strings.StatusImportWizardError);
        }
示例#2
0
        public Task ExecuteAsync(object parameter)
        {
            var task = ExecuteWorker((parameter as PythonProjectNode) ?? _project);

            // Ensure the exception is observed.
            // The caller can check task.Exception to do their own reporting.
            task.ContinueWith(t => {
                try {
                    t.Wait();
                } catch (AggregateException ex) {
                    var exception = ex.InnerException;
                    if (exception is NoInterpretersException ||
                        exception is MissingInterpreterException ||
                        exception is TaskCanceledException)
                    {
                        // No need to log this exception or disable the command.
                        return;
                    }

                    // Prevent the command from executing again until the project is
                    // reloaded.
                    _canExecute = false;
                    var evt     = CanExecuteChanged;
                    if (evt != null)
                    {
                        evt(this, EventArgs.Empty);
                    }

                    // Log error to the ActivityLog.
                    CommonUtils.ActivityLogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_target, ex));
                }
            });

            return(task);
        }
        private async Task RequestFeeds(string feedSource)
        {
            try {
                await Task.Run(() => GetFeeds(feedSource));
            } catch (Exception ex) {
                if (ex.IsCriticalException())
                {
                    throw;
                }

                MessageBox.Show(SR.GetString(SR.WebPiFeedError, feedSource, ex.Message));

                var fullMessage = SR.GetString(SR.WebPiFeedError, feedSource, ex);
                Trace.WriteLine(fullMessage);
                CommonUtils.ActivityLogError("WebPiComponentPickerControl", fullMessage);
            }
        }
示例#4
0
        private static string LoadResourceFromAssembly(string assembly, string ns, string key)
        {
            try {
                var asmName = new System.Reflection.AssemblyName(assembly);
                System.Reflection.Assembly asm = null;
                if (asmName.FullName == asmName.Name)
                {
                    // A partial name was provided. If there is an assembly with
                    // matching name in the current AppDomain, assume that is
                    // the intended one.
                    asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => assembly == a.GetName().Name);
                }

                asm = asm ?? System.Reflection.Assembly.Load(asmName);
                var rm = new System.Resources.ResourceManager(ns, asm);
                return(rm.GetString(key, CultureInfo.CurrentUICulture) ?? key);
            } catch (Exception ex) {
                CommonUtils.ActivityLogError(Strings.ProductTitle, Strings.FailedToReadResource.FormatUI(assembly, ns, key, ex));
                return(key);
            }
        }
示例#5
0
        private async Task <bool> RunInRepl(IPythonProject project, CommandStartInfo startInfo)
        {
            var  executeIn = string.IsNullOrEmpty(startInfo.ExecuteIn) ? CreatePythonCommandItem.ExecuteInRepl : startInfo.ExecuteIn;
            bool resetRepl = executeIn.StartsWithOrdinal("R");

            var replTitle = executeIn.Substring(4).TrimStart(' ', ':');

            if (string.IsNullOrEmpty(replTitle))
            {
                replTitle = Strings.CustomCommandReplTitle.FormatUI(DisplayLabelWithoutAccessKeys);
            }
            else
            {
                var match = _customCommandLabelRegex.Match(replTitle);
                if (match.Success)
                {
                    replTitle = LoadResourceFromAssembly(
                        match.Groups["assembly"].Value,
                        match.Groups["namespace"].Value,
                        match.Groups["key"].Value
                        );
                }
            }

            replTitle = PerformSubstitutions(project, replTitle);

            var replWindowId = PythonReplEvaluatorProvider.GetTemporaryId(
                ReplId + executeIn.Substring(4),
                _project.GetInterpreterFactory().Configuration
                );

            var model        = _project.Site.GetComponentModel();
            var replProvider = model.GetService <InteractiveWindowProvider>();

            if (replProvider == null)
            {
                return(false);
            }

            bool created;
            var  replWindow = replProvider.OpenOrCreateTemporary(replWindowId, replTitle, out created);

            // TODO: Find alternative way of closing repl window on Dev15
            var replFrame = (replWindow as ToolWindowPane)?.Frame as IVsWindowFrame;

            var interactive = replWindow.InteractiveWindow;
            var pyEvaluator = replWindow.InteractiveWindow.Evaluator as PythonInteractiveEvaluator;

            if (pyEvaluator == null)
            {
                if (created && replFrame != null)
                {
                    // We created the window, but it isn't valid, so we'll close
                    // it again immediately.
                    replFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                return(false);
            }

            if (pyEvaluator.IsExecuting)
            {
                throw new InvalidOperationException(Strings.ErrorCommandAlreadyRunning);
            }

            pyEvaluator.ProjectMoniker = _project.GetMkDocument();
            pyEvaluator.Configuration  = new LaunchConfiguration(startInfo.Interpreter)
            {
                WorkingDirectory = startInfo.WorkingDirectory,
                Environment      = startInfo.EnvironmentVariables.ToDictionary(kv => kv.Key, kv => kv.Value)
            };
            pyEvaluator.Configuration.LaunchOptions[PythonInteractiveEvaluator.DoNotResetConfigurationLaunchOption] = "true";

            project.AddActionOnClose((object)replWindow, InteractiveWindowProvider.Close);

            replWindow.Show(true);

            var result = await pyEvaluator.ResetAsync(false, quiet : true);

            if (result.IsSuccessful)
            {
                try {
                    var filename  = startInfo.Filename;
                    var arguments = startInfo.Arguments ?? string.Empty;

                    if (startInfo.IsScript)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingScript.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteFileAsync(filename, arguments);
                    }
                    else if (startInfo.IsModule)
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingModule.FormatUI(filename, arguments));
                        Debug.WriteLine("Executing -m {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteModuleAsync(filename, arguments);
                    }
                    else if (startInfo.IsCode)
                    {
                        Debug.WriteLine("Executing -c \"{0}\"", filename, arguments);
                        await pyEvaluator.ExecuteCodeAsync(filename);
                    }
                    else
                    {
                        interactive.WriteLine(Strings.CustomCommandExecutingOther.FormatUI(Path.GetFileName(filename), arguments));
                        Debug.WriteLine("Executing {0} {1}", filename, arguments);
                        await pyEvaluator.ExecuteProcessAsync(filename, arguments);
                    }

                    if (resetRepl)
                    {
                        // We really close the backend, rather than resetting.
                        pyEvaluator.Dispose();
                    }
                } catch (OperationCanceledException) {
                    // Swallow OperationCanceledException, it is normal for async operation to be cancelled
                    ActivityLog.LogInformation(Strings.ProductTitle, Strings.CustomCommandCanceled.FormatUI(_label));
                } catch (Exception ex) {
                    CommonUtils.ActivityLogError(Strings.ProductTitle, Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                    var outWindow = OutputWindowRedirector.GetGeneral(project.Site);
                    if (outWindow != null)
                    {
                        outWindow.WriteErrorLine(Strings.ErrorRunningCustomCommand.FormatUI(_label, ex));
                        outWindow.Show();
                    }
                }
                return(true);
            }

            return(false);
        }
示例#6
0
        void IVsProjectUpgradeViaFactory4.UpgradeProject_CheckOnly(
            string bstrFileName,
            IVsUpgradeLogger pLogger,
            out uint pUpgradeRequired,
            out Guid pguidNewProjectFactory,
            out uint pUpgradeProjectCapabilityFlags
            )
        {
            pguidNewProjectFactory = Guid.Empty;

            if (!File.Exists(bstrFileName))
            {
                pUpgradeRequired = 0;
                pUpgradeProjectCapabilityFlags = 0;
                return;
            }

            var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED |
                                __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP |
                                __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP;
            var logger = new UpgradeLogger(bstrFileName, pLogger);

            try {
                var projectXml      = ProjectRootElement.Open(bstrFileName);
                var userProjectName = bstrFileName + ".user";
                var userProjectXml  = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null;

                var upgradeRequired = UpgradeProjectCheck(
                    projectXml,
                    userProjectXml,
                    logger.Log,
                    ref pguidNewProjectFactory,
                    ref backupSupport
                    );

                switch (upgradeRequired)
                {
                case ProjectUpgradeState.SafeRepair:
                    pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_SAFEREPAIR;
                    break;

                case ProjectUpgradeState.UnsafeRepair:
                    pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_UNSAFEREPAIR;
                    break;

                case ProjectUpgradeState.OneWayUpgrade:
                    pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_ONEWAYUPGRADE;
                    break;

                case ProjectUpgradeState.Incompatible:
                    pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_INCOMPATIBLE;
                    break;

                case ProjectUpgradeState.Deprecated:
                    pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_DEPRECATED;
                    break;

                default:
                case ProjectUpgradeState.NotNeeded:
                    pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR;
                    break;
                }
            } catch (Exception ex) {
                if (ex.IsCriticalException())
                {
                    throw;
                }
                // Log the error and don't attempt to upgrade the project.
                logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message));
                CommonUtils.ActivityLogError(GetType().FullName, ex.ToString());
                pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR;
            }
            pUpgradeProjectCapabilityFlags = (uint)backupSupport;

            // If the upgrade checker set the factory GUID to ourselves, we need
            // to clear it
            if (pguidNewProjectFactory == GetType().GUID)
            {
                pguidNewProjectFactory = Guid.Empty;
            }
        }
示例#7
0
        int IVsProjectUpgradeViaFactory.UpgradeProject_CheckOnly(
            string bstrFileName,
            IVsUpgradeLogger pLogger,
            out int pUpgradeRequired,
            out Guid pguidNewProjectFactory,
            out uint pUpgradeProjectCapabilityFlags
            )
        {
            pUpgradeRequired       = 0;
            pguidNewProjectFactory = Guid.Empty;

            if (!File.Exists(bstrFileName))
            {
                pUpgradeProjectCapabilityFlags = 0;
                return(VSConstants.E_INVALIDARG);
            }


            var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED |
                                __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP |
                                __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP;
            var logger = new UpgradeLogger(bstrFileName, pLogger);

            try {
                var projectXml      = ProjectRootElement.Open(bstrFileName);
                var userProjectName = bstrFileName + ".user";
                var userProjectXml  = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null;

                var upgradeRequired = UpgradeProjectCheck(
                    projectXml,
                    userProjectXml,
                    logger.Log,
                    ref pguidNewProjectFactory,
                    ref backupSupport
                    );

                if (upgradeRequired != ProjectUpgradeState.NotNeeded)
                {
                    pUpgradeRequired = 1;
                }
            } catch (Exception ex) {
                if (ex.IsCriticalException())
                {
                    throw;
                }
                // Log the error and don't attempt to upgrade the project.
                logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message));
                CommonUtils.ActivityLogError(GetType().FullName, ex.ToString());
                pUpgradeRequired = 0;
            }
            pUpgradeProjectCapabilityFlags = (uint)backupSupport;

            // If the upgrade checker set the factory GUID to ourselves, we need
            // to clear it
            if (pguidNewProjectFactory == GetType().GUID)
            {
                pguidNewProjectFactory = Guid.Empty;
            }

            return(VSConstants.S_OK);
        }
示例#8
0
        int IVsProjectUpgradeViaFactory.UpgradeProject(
            string bstrFileName,
            uint fUpgradeFlag,
            string bstrCopyLocation,
            out string pbstrUpgradedFullyQualifiedFileName,
            IVsUpgradeLogger pLogger,
            out int pUpgradeRequired,
            out Guid pguidNewProjectFactory
            )
        {
            pbstrUpgradedFullyQualifiedFileName = null;

            // We first run (or re-run) the upgrade check and bail out early if
            // there is actually no need to upgrade.
            uint dummy;
            var  hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly(
                bstrFileName,
                pLogger,
                out pUpgradeRequired,
                out pguidNewProjectFactory,
                out dummy
                );

            if (!CommonUtils.Succeeded(hr))
            {
                return(hr);
            }

            var logger = new UpgradeLogger(bstrFileName, pLogger);

            var  backup = (__VSPPROJECTUPGRADEVIAFACTORYFLAGS)fUpgradeFlag;
            bool anyBackup, sxsBackup, copyBackup;

            anyBackup = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED);
            if (anyBackup)
            {
                sxsBackup  = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP);
                copyBackup = !sxsBackup && backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP);
            }
            else
            {
                sxsBackup = copyBackup = false;
            }

            if (copyBackup)
            {
                throw new NotSupportedException("PUVFF_COPYBACKUP is not supported");
            }

            pbstrUpgradedFullyQualifiedFileName = bstrFileName;

            if (pUpgradeRequired == 0 && !copyBackup)
            {
                // No upgrade required, and no backup required.
                logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired));
                return(VSConstants.S_OK);
            }

            try {
                UpgradeLogger logger2      = null;
                var           userFileName = bstrFileName + ".user";
                if (File.Exists(userFileName))
                {
                    logger2 = new UpgradeLogger(userFileName, pLogger);
                }
                else
                {
                    userFileName = null;
                }

                if (sxsBackup)
                {
                    // For SxS backups we want to put the old project file alongside
                    // the current one.
                    bstrCopyLocation = Path.GetDirectoryName(bstrFileName);
                }

                if (anyBackup)
                {
                    var namePart          = Path.GetFileNameWithoutExtension(bstrFileName);
                    var extPart           = Path.GetExtension(bstrFileName) + (sxsBackup ? ".old" : "");
                    var projectFileBackup = Path.Combine(bstrCopyLocation, namePart + extPart);
                    for (int i = 1; File.Exists(projectFileBackup); ++i)
                    {
                        projectFileBackup = Path.Combine(
                            bstrCopyLocation,
                            string.Format("{0}{1}{2}", namePart, i, extPart)
                            );
                    }

                    File.Copy(bstrFileName, projectFileBackup);

                    // Back up the .user file if there is one
                    if (userFileName != null)
                    {
                        if (sxsBackup)
                        {
                            File.Copy(
                                userFileName,
                                Path.ChangeExtension(projectFileBackup, ".user.old")
                                );
                        }
                        else
                        {
                            File.Copy(userFileName, projectFileBackup + ".old");
                        }
                    }

                    // TODO: Implement support for backing up all files
                    //if (copyBackup) {
                    //  - Open the project
                    //  - Inspect all Items
                    //  - Copy those items that are referenced relative to the
                    //    project file into bstrCopyLocation
                    //}
                }


                var queryEdit = _site.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2;
                if (queryEdit != null)
                {
                    uint editVerdict;
                    uint queryEditMoreInfo;
                    var  tagVSQueryEditFlags_QEF_AllowUnopenedProjects = (tagVSQueryEditFlags)0x80;

                    CommonUtils.ThrowOnFailure(queryEdit.QueryEditFiles(
                                                   (uint)(tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting |
                                                          tagVSQueryEditFlags.QEF_DisallowInMemoryEdits |
                                                          tagVSQueryEditFlags_QEF_AllowUnopenedProjects),
                                                   1,
                                                   new[] { bstrFileName },
                                                   null,
                                                   null,
                                                   out editVerdict,
                                                   out queryEditMoreInfo
                                                   ));

                    if (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK)
                    {
                        logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UpgradeCannotCheckOutProject));
                        return(VSConstants.E_FAIL);
                    }

                    // File may have been updated during checkout, so check
                    // again whether we need to upgrade.
                    if ((queryEditMoreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0)
                    {
                        hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly(
                            bstrFileName,
                            pLogger,
                            out pUpgradeRequired,
                            out pguidNewProjectFactory,
                            out dummy
                            );

                        if (!CommonUtils.Succeeded(hr))
                        {
                            return(hr);
                        }
                        if (pUpgradeRequired == 0)
                        {
                            logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired));
                            return(VSConstants.S_OK);
                        }
                    }
                }

                // Load the project file and user file into MSBuild as plain
                // XML to make it easier for subclasses.
                var projectXml = ProjectRootElement.Open(bstrFileName);
                if (projectXml == null)
                {
                    throw new Exception(SR.GetString(SR.UpgradeCannotLoadProject));
                }

                var userXml = userFileName != null?ProjectRootElement.Open(userFileName) : null;

                // Invoke our virtual UpgradeProject function. If it fails, it
                // will throw and we will log the exception.
                UpgradeProject(ref projectXml, ref userXml, logger.Log);

                // Get the SCC info from the project file.
                if (projectXml != null)
                {
                    _cachedSccProject     = bstrFileName;
                    _cachedSccProjectName = string.Empty;
                    _cachedSccAuxPath     = string.Empty;
                    _cachedSccLocalPath   = string.Empty;
                    _cachedSccProvider    = string.Empty;
                    foreach (var property in projectXml.Properties)
                    {
                        switch (property.Name)
                        {
                        case ProjectFileConstants.SccProjectName:
                            _cachedSccProjectName = property.Value;
                            break;

                        case ProjectFileConstants.SccAuxPath:
                            _cachedSccAuxPath = property.Value;
                            break;

                        case ProjectFileConstants.SccLocalPath:
                            _cachedSccLocalPath = property.Value;
                            break;

                        case ProjectFileConstants.SccProvider:
                            _cachedSccProvider = property.Value;
                            break;

                        default:
                            break;
                        }
                    }
                }

                // Save the updated files.
                if (projectXml != null)
                {
                    projectXml.Save();
                }
                if (userXml != null)
                {
                    userXml.Save();
                }

                // Need to add "Converted" (unlocalized) to the report because
                // the XSLT refers to it.
                logger.Log(__VSUL_ERRORLEVEL.VSUL_STATUSMSG, "Converted");
                return(VSConstants.S_OK);
            } catch (Exception ex) {
                if (ex.IsCriticalException())
                {
                    throw;
                }

                logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message));
                CommonUtils.ActivityLogError(GetType().FullName, ex.ToString());
                return(VSConstants.E_FAIL);
            }
        }