Пример #1
0
        private static void ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport)
        {
            var project = projectToProfile.AsPythonProject();

            var config = project?.GetLaunchConfigurationOrThrow();

            if (config == null)
            {
                MessageBox.Show(Strings.ProjectInterpreterNotFound.FormatUI(projectToProfile.Name), Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.ScriptName))
            {
                MessageBox.Show(Strings.NoProjectStartupFile, Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".")
            {
                config.WorkingDirectory = project.ProjectHome;
                if (string.IsNullOrEmpty(config.WorkingDirectory))
                {
                    config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName);
                }
            }

            RunProfiler(session, config, openReport);
        }
Пример #2
0
        private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport)
        {
            LaunchConfiguration config;

            if (runTarget.PythonInterpreter != null)
            {
                var registry    = session._serviceProvider.GetComponentModel().GetService <IInterpreterRegistryService>();
                var interpreter = registry.FindConfiguration(runTarget.PythonInterpreter.Id);
                if (interpreter == null)
                {
                    return;
                }
                config = new LaunchConfiguration(interpreter);
            }
            else
            {
                config = new LaunchConfiguration(null);
            }

            config.InterpreterPath  = runTarget.InterpreterPath;
            config.ScriptName       = runTarget.Script;
            config.ScriptArguments  = runTarget.Arguments;
            config.WorkingDirectory = runTarget.WorkingDirectory;

            RunProfiler(session, config, openReport);
        }
Пример #3
0
        private static void RunProfiler(SessionNode session, string interpreter, string script, string arguments, string workingDir, bool openReport, ProcessorArchitecture arch)
        {
            var process = new ProfiledProcess(interpreter, String.Format("\"{0}\" {1}", script, arguments), workingDir, arch);

            string baseName = Path.GetFileNameWithoutExtension(session.Filename);
            string date     = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
            string outPath  = Path.Combine(Path.GetTempPath(), baseName + date + ".vsp");

            int count = 1;

            while (File.Exists(outPath))
            {
                outPath = Path.Combine(Path.GetTempPath(), baseName + date + "(" + count + ").vsp");
                count++;
            }

            process.ProcessExited += (sender, args) => {
                var dte = (EnvDTE.DTE)PythonProfilingPackage.GetGlobalService(typeof(EnvDTE.DTE));
                _profilingProcess     = null;
                _stopCommand.Enabled  = false;
                _startCommand.Enabled = true;
                if (openReport)
                {
                    dte.ItemOperations.OpenFile(outPath);
                }
            };

            session.AddProfile(outPath);

            process.StartProfiling(outPath);
            _profilingProcess     = process;
            _stopCommand.Enabled  = true;
            _startCommand.Enabled = false;
        }
Пример #4
0
        internal SessionNode OpenTarget(ProfilingTarget target, string filename)
        {
            for (int i = 0; i < _sessions.Count; i++)
            {
                if (_sessions[i].Filename == filename)
                {
                    throw new InvalidOperationException(Strings.PerformanceSessionAlreadyOpen.FormatUI(filename));
                }
            }

            uint prevSibl;

            if (_sessions.Count > 0)
            {
                prevSibl = _sessions[_sessions.Count - 1].ItemId;
            }
            else
            {
                prevSibl = VSConstants.VSITEMID_NIL;
            }

            var node = new SessionNode(_serviceProvider, this, target, filename);

            _sessions.Add(node);

            OnItemAdded(VSConstants.VSITEMID_ROOT, prevSibl, node.ItemId);

            if (_activeSession == VSConstants.VSITEMID_NIL)
            {
                SetActiveSession(node);
            }

            return(node);
        }
Пример #5
0
        internal SessionNode OpenTarget(ProfilingTarget target, string filename)
        {
            for (int i = 0; i < _sessions.Count; i++)
            {
                if (_sessions[i].Filename == filename)
                {
                    throw new InvalidOperationException(String.Format("Performance '{0}' session is already open", filename));
                }
            }

            uint itemid = (uint)_sessions.Count;
            var  node   = new SessionNode(this, target, filename);

            _sessions.Add(node);

            uint prevSibl;

            if (itemid != 0)
            {
                prevSibl = itemid - 1;
            }
            else
            {
                prevSibl = VSConstants.VSITEMID_NIL;
            }

            OnItemAdded(VSConstants.VSITEMID_ROOT, prevSibl, itemid);

            if (_activeSession == -1)
            {
                SetActiveSession(node);
            }

            return(node);
        }
Пример #6
0
        internal void StartProfiling(ProfilingTarget target, SessionNode session, bool openReport = true)
        {
            ThreadHelper.JoinableTaskFactory.Run(async() => {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (!Utilities.SaveDirtyFiles())
                {
                    // Abort
                    return;
                }

                if (target.ProjectTarget != null)
                {
                    ProfileProjectTarget(session, target.ProjectTarget, openReport);
                }
                else if (target.StandaloneTarget != null)
                {
                    ProfileStandaloneTarget(session, target.StandaloneTarget, openReport);
                }
                else
                {
                    if (MessageBox.Show(Strings.ProfilingSessionNotConfigured, Strings.NoProfilingTargetTitle, MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        var newTarget = session.OpenTargetProperties();
                        if (newTarget != null && (newTarget.ProjectTarget != null || newTarget.StandaloneTarget != null))
                        {
                            StartProfiling(newTarget, session, openReport);
                        }
                    }
                }
            });
        }
Пример #7
0
        internal void StartProfiling(ProfilingTarget target, SessionNode session, bool openReport = true)
        {
            ThreadHelper.Generic.Invoke(() => {
                if (!Utilities.SaveDirtyFiles())
                {
                    // Abort
                    return;
                }

                if (target.ProjectTarget != null)
                {
                    ProfileProjectTarget(session, target.ProjectTarget, openReport);
                }
                else if (target.StandaloneTarget != null)
                {
                    ProfileStandaloneTarget(session, target.StandaloneTarget, openReport);
                }
                else
                {
                    if (MessageBox.Show("Profiling session is not configured - would you like to configure now and then launch?", "No Profiling Target", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        var newTarget = session.OpenTargetProperties();
                        if (newTarget != null && (newTarget.ProjectTarget != null || newTarget.StandaloneTarget != null))
                        {
                            StartProfiling(newTarget, session, openReport);
                        }
                    }
                }
            });
        }
Пример #8
0
        private void ProfileProjectTarget(SessionNode session, ProjectTarget projectTarget, bool openReport)
        {
            var targetGuid = projectTarget.TargetProject;

            var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));

            EnvDTE.Project projectToProfile = null;
            foreach (EnvDTE.Project project in dte.Solution.Projects)
            {
                var kind = project.Kind;

                if (String.Equals(kind, PythonProfilingPackage.PythonProjectGuid, StringComparison.OrdinalIgnoreCase))
                {
                    var guid = project.Properties.Item("Guid").Value as string;

                    Guid guidVal;
                    if (Guid.TryParse(guid, out guidVal) && guidVal == projectTarget.TargetProject)
                    {
                        projectToProfile = project;
                        break;
                    }
                }
            }

            if (projectToProfile != null)
            {
                ProfileProject(session, projectToProfile, openReport);
            }
            else
            {
                MessageBox.Show("Project could not be found in current solution.", "Python Tools for Visual Studio");
            }
        }
Пример #9
0
        private static void ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport)
        {
            var project = projectToProfile.AsPythonProject();

            var config = project?.GetLaunchConfigurationOrThrow();

            if (config == null)
            {
                MessageBox.Show("Could not find interpreter for project {0}".FormatUI(projectToProfile.Name), "Python Tools for Visual Studio");
                return;
            }

            if (string.IsNullOrEmpty(config.ScriptName))
            {
                MessageBox.Show("Project has no configured startup file, cannot start profiling.", "Python Tools for Visual Studio");
                return;
            }

            if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".")
            {
                config.WorkingDirectory = project.ProjectHome;
                if (string.IsNullOrEmpty(config.WorkingDirectory))
                {
                    config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName);
                }
            }

            RunProfiler(session, config, openReport);
        }
Пример #10
0
        internal static void ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport)
        {
            var    interpreterId      = (string)projectToProfile.Properties.Item("InterpreterId").Value;
            var    interpreterVersion = (string)projectToProfile.Properties.Item("InterpreterVersion").Value;
            string interpreter;

            Guid    intGuid;
            Version intVersion;
            ProcessorArchitecture arch;

            if (!Guid.TryParse(interpreterId, out intGuid) ||
                !Version.TryParse(interpreterVersion, out intVersion) ||
                !TryGetInterpreter(intVersion, intGuid, out interpreter, out arch))
            {
                MessageBox.Show(String.Format("Could not find interpreter for project {0}", projectToProfile.Name));
                return;
            }

            string startupFile = (string)projectToProfile.Properties.Item("StartupFile").Value;

            if (String.IsNullOrEmpty(startupFile))
            {
                MessageBox.Show("Project has no configured startup file, cannot start profiling.");
                return;
            }

            string workingDir = projectToProfile.Properties.Item("WorkingDirectory").Value as string;

            if (String.IsNullOrEmpty(workingDir) || workingDir == ".")
            {
                workingDir = Path.GetDirectoryName(projectToProfile.FullName);
            }

            RunProfiler(session, interpreter, startupFile, null, workingDir, openReport, arch);
        }
Пример #11
0
        private static void RunVTune(SessionNode session, LaunchConfiguration config, bool openReport)
        {
            var interpreter = config.GetInterpreterPath();

            if (!File.Exists(interpreter))
            {
                MessageBox.Show(Strings.CannotFindPythonInterpreter, Strings.ProductTitle);
                return;
            }

            string outPathDir = Path.GetTempPath();
            var    subpath    = Path.Combine(outPathDir, Path.GetRandomFileName());

            while (Directory.Exists(subpath) || File.Exists(subpath))
            {
                subpath = Path.Combine(outPathDir, Path.GetRandomFileName());
            }
            outPathDir = subpath;

            string outPath = Path.Combine(outPathDir, "pythontrace.diagsession");

            var driver = PythonToolsInstallPath.GetFile(ExternalProfilerDriverExe, typeof(PythonProfilingPackage).Assembly);

            var procInfo = new ProcessStartInfo(driver)
            {
                CreateNoWindow = false,
                Arguments      = string.Join(" ", new[] {
                    "-d",
                    ProcessOutput.QuoteSingleArgument(outPathDir),
                    "--",
                    ProcessOutput.QuoteSingleArgument(interpreter),
                    config.InterpreterArguments,
                    string.IsNullOrEmpty(config.ScriptName) ? "" : ProcessOutput.QuoteSingleArgument(config.ScriptName),
                    config.ScriptArguments
                }),
                WorkingDirectory = config.WorkingDirectory,
            };

            var proc = new Process {
                StartInfo = procInfo
            };
            var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));

            proc.EnableRaisingEvents = true;
            proc.Exited += (_, args) => {
                if (!File.Exists(Path.Combine(outPathDir, "Sample.dwjson")))
                {
                    MessageBox.Show(Strings.CannotFindGeneratedFile, Strings.ProductTitle);
                }
                else
                {
                    PackageTrace(outPathDir);
                    dte.ItemOperations.OpenFile(Path.Combine(outPathDir, "trace.diagsession"));
                }
            };
            proc.Start();
        }
Пример #12
0
        internal void SetActiveSession(SessionNode node)
        {
            uint oldItem = _activeSession;

            if (oldItem != VSConstants.VSITEMID_NIL)
            {
                _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_UnBoldItem);
            }

            _activeSession = node.ItemId;

            _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_BoldItem);
        }
Пример #13
0
        private static void ProfileProject(SessionNode session, PythonProjectNode project, bool openReport, bool useVTune)
        {
            LaunchConfiguration config = null;

            try {
                config = project?.GetLaunchConfigurationOrThrow();
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(session._serviceProvider, ex.HelpPage);
                return;
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            } catch (IOException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }
            if (config == null)
            {
                MessageBox.Show(Strings.ProjectInterpreterNotFound.FormatUI(project.GetNameProperty()), Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.ScriptName))
            {
                MessageBox.Show(Strings.NoProjectStartupFile, Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".")
            {
                config.WorkingDirectory = project.ProjectHome;
                if (string.IsNullOrEmpty(config.WorkingDirectory))
                {
                    config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName);
                }
            }

#if EXTERNAL_PROFILER_DRIVER
            if (useVTune)
            {
                RunVTune(session, config, openReport);
            }
            else
            {
#endif
            RunProfiler(session, config, openReport);
#if EXTERNAL_PROFILER_DRIVER
        }
#endif
        }
Пример #14
0
        private void ProfileProjectTarget(SessionNode session, ProjectTarget projectTarget, bool openReport)
        {
            var project = Solution.EnumerateLoadedPythonProjects()
                          .SingleOrDefault(p => p.GetProjectIDGuidProperty() == projectTarget.TargetProject);

            if (project != null)
            {
                ProfileProject(session, project, openReport);
            }
            else
            {
                MessageBox.Show(Strings.ProjectNotFoundInSolution, Strings.ProductTitle);
            }
        }
Пример #15
0
        internal void SetActiveSession(SessionNode node)
        {
            int oldItem = _activeSession;

            if (oldItem != -1)
            {
                _window.ExpandItem(this, (uint)_activeSession, EXPANDFLAGS.EXPF_UnBoldItem);
            }

            _activeSession = _sessions.IndexOf(node);
            Debug.Assert(_activeSession != -1);

            _window.ExpandItem(this, (uint)_activeSession, EXPANDFLAGS.EXPF_BoldItem);
        }
Пример #16
0
        private static void RunProfiler(SessionNode session, LaunchConfiguration config, bool openReport)
        {
            var process = new ProfiledProcess(
                (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService)),
                config.GetInterpreterPath(),
                string.Join(" ", ProcessOutput.QuoteSingleArgument(config.ScriptName), config.ScriptArguments),
                config.WorkingDirectory,
                session._serviceProvider.GetPythonToolsService().GetFullEnvironment(config)
                );

            string baseName = Path.GetFileNameWithoutExtension(session.Filename);
            string date     = DateTime.Now.ToString("yyyyMMdd");
            string outPath  = Path.Combine(Path.GetTempPath(), baseName + "_" + date + ".vsp");

            int count = 1;

            while (File.Exists(outPath))
            {
                outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vsp");
                count++;
            }

            process.ProcessExited += (sender, args) => {
                var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));
                _profilingProcess     = null;
                _stopCommand.Enabled  = false;
                _startCommand.Enabled = true;
                if (openReport && File.Exists(outPath))
                {
                    for (int retries = 10; retries > 0; --retries)
                    {
                        try {
                            using (new FileStream(outPath, FileMode.Open, FileAccess.Read, FileShare.None)) { }
                            break;
                        } catch (IOException) {
                            Thread.Sleep(100);
                        }
                    }
                    dte.ItemOperations.OpenFile(outPath);
                }
            };

            session.AddProfile(outPath);

            process.StartProfiling(outPath);
            _profilingProcess     = process;
            _stopCommand.Enabled  = true;
            _startCommand.Enabled = false;
        }
Пример #17
0
        private static void RunProfiler(SessionNode session, string interpreter, string script, string arguments, string workingDir, Dictionary <string, string> env, bool openReport, ProcessorArchitecture arch)
        {
            var process = new ProfiledProcess(
                (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService)),
                interpreter,
                String.Format("\"{0}\" {1}", script, arguments ?? string.Empty),
                workingDir,
                env,
                arch
                );

            string baseName = Path.GetFileNameWithoutExtension(session.Filename);
            string date     = DateTime.Now.ToString("yyyyMMdd");
            string outPath  = Path.Combine(Path.GetTempPath(), baseName + "_" + date + ".vsp");

            int count = 1;

            while (File.Exists(outPath))
            {
                outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vsp");
                count++;
            }

            process.ProcessExited += (sender, args) => {
                var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));
                _profilingProcess     = null;
                _stopCommand.Enabled  = false;
                _startCommand.Enabled = true;
                if (openReport && File.Exists(outPath))
                {
                    dte.ItemOperations.OpenFile(outPath);
                }
            };

            session.AddProfile(outPath);

            process.StartProfiling(outPath);
            _profilingProcess     = process;
            _stopCommand.Enabled  = true;
            _startCommand.Enabled = false;
        }
Пример #18
0
        private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport)
        {
            var model    = (IComponentModel)(session._serviceProvider.GetService(typeof(SComponentModel)));
            var registry = model.DefaultExportProvider.GetExportedValue <IInterpreterRegistryService>();

            var interpreterPath = runTarget.InterpreterPath;
            var arch            = ProcessorArchitecture.X86;

            if (runTarget.PythonInterpreter != null)
            {
                var interpreter = registry.FindInterpreter(runTarget.PythonInterpreter.Id);
                if (interpreter == null)
                {
                    return;
                }
                interpreterPath = interpreter.Configuration.InterpreterPath;
                arch            = interpreter.Configuration.Architecture;
            }

            RunProfiler(session, interpreterPath, runTarget.Script, runTarget.Arguments, runTarget.WorkingDirectory, null, openReport, arch);
        }
Пример #19
0
 internal void StartProfiling(ProfilingTarget target, SessionNode session, bool openReport = true)
 {
     if (target.ProjectTarget != null)
     {
         ProfileProjectTarget(session, target.ProjectTarget, openReport);
     }
     else if (target.StandaloneTarget != null)
     {
         ProfileStandaloneTarget(session, target.StandaloneTarget, openReport);
     }
     else
     {
         if (MessageBox.Show("Profiling session is not configured - would you like to configure now and then launch?", "No Profiling Target", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
         {
             var newTarget = session.OpenTargetProperties();
             if (newTarget != null && (newTarget.ProjectTarget != null || newTarget.StandaloneTarget != null))
             {
                 StartProfiling(newTarget, session, openReport);
             }
         }
     }
 }
Пример #20
0
        private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport)
        {
            string interpreter;
            ProcessorArchitecture arch;

            if (runTarget.PythonInterpreter != null)
            {
                Version selectedVersion = new Version(runTarget.PythonInterpreter.Version);
                Guid    interpreterId   = runTarget.PythonInterpreter.Id;
                if (!TryGetInterpreter(selectedVersion, interpreterId, out interpreter, out arch))
                {
                    return;
                }
            }
            else
            {
                interpreter = runTarget.InterpreterPath;
                arch        = ProcessorArchitecture.X86;
            }

            RunProfiler(session, interpreter, runTarget.Script, runTarget.Arguments, runTarget.WorkingDirectory, openReport, arch);
        }
Пример #21
0
        private static void ProfileProject(SessionNode session, PythonProjectNode project, bool openReport)
        {
            LaunchConfiguration config = null;

            try {
                config = project?.GetLaunchConfigurationOrThrow();
            } catch (NoInterpretersException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            } catch (IOException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }
            if (config == null)
            {
                MessageBox.Show(Strings.ProjectInterpreterNotFound.FormatUI(project.GetNameProperty()), Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.ScriptName))
            {
                MessageBox.Show(Strings.NoProjectStartupFile, Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".")
            {
                config.WorkingDirectory = project.ProjectHome;
                if (string.IsNullOrEmpty(config.WorkingDirectory))
                {
                    config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName);
                }
            }

            RunProfiler(session, config, openReport);
        }
Пример #22
0
        internal static void ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport) {
            var model = (IComponentModel)(session._serviceProvider.GetService(typeof(SComponentModel)));
            var interpreterService = model.GetService<IInterpreterOptionsService>();

            var projectHome = CommonUtils.GetAbsoluteDirectoryPath(
                Path.GetDirectoryName(projectToProfile.FullName),
                (string)projectToProfile.Properties.Item("ProjectHome").Value
            );
            var interpreterProvider = (MSBuildProjectInterpreterFactoryProvider)projectToProfile.Properties.Item("InterpreterFactoryProvider").Value;
            var args = (string)projectToProfile.Properties.Item("CommandLineArguments").Value;
            var interpreterPath = (string)projectToProfile.Properties.Item("InterpreterPath").Value;
            var searchPath = (string)projectToProfile.Properties.Item("SearchPath").Value;

            var interpreter = interpreterProvider != null ? interpreterProvider.ActiveInterpreter : null;
            if (interpreter == null || interpreter == interpreterService.NoInterpretersValue) {
                MessageBox.Show(String.Format("Could not find interpreter for project {0}", projectToProfile.Name), "Python Tools for Visual Studio");
                return;
            }

            var arch = interpreter.Configuration.Architecture;
            var pathEnvVarName = interpreter.Configuration.PathEnvironmentVariable;

            if (String.IsNullOrWhiteSpace(interpreterPath)) {
                interpreterPath = interpreter.Configuration.InterpreterPath;
            }

            string startupFile = (string)projectToProfile.Properties.Item("StartupFile").Value;
            if (String.IsNullOrEmpty(startupFile)) {
                MessageBox.Show("Project has no configured startup file, cannot start profiling.", "Python Tools for Visual Studio");
                return;
            }

            string workingDir = projectToProfile.Properties.Item("WorkingDirectory").Value as string;
            if (String.IsNullOrEmpty(workingDir) || workingDir == ".") {
                workingDir = projectToProfile.Properties.Item("ProjectHome").Value as string;
                if (String.IsNullOrEmpty(workingDir)) {
                    workingDir = Path.GetDirectoryName(projectToProfile.FullName);
                }
            }

            var env = new Dictionary<string, string>();
            if (!String.IsNullOrWhiteSpace(pathEnvVarName) && !String.IsNullOrEmpty(searchPath)) {
                var searchPaths = searchPath.Split(';').ToList();
                var pyService = (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService));
                if (!pyService.GeneralOptions.ClearGlobalPythonPath) {
                    searchPaths.AddRange(Environment.GetEnvironmentVariable(pathEnvVarName).Split(';'));
                }

                env[pathEnvVarName] = string.Join(";", searchPaths
                    .Where(CommonUtils.IsValidPath)
                    .Select(p => CommonUtils.GetAbsoluteDirectoryPath(projectHome, p))
                    .Where(Directory.Exists)
                    .Distinct(StringComparer.OrdinalIgnoreCase)
                );
            }

            var userEnv = projectToProfile.Properties.Item("Environment").Value as string;
            if (userEnv != null) {
                foreach (var envVar in userEnv.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) {
                    var nameValue = envVar.Split(new[] { '=' }, 2);
                    if (nameValue.Length == 2) {
                        env[nameValue[0]] = nameValue[1];
                    }
                }
            }

            RunProfiler(session, interpreterPath, startupFile, args, workingDir, env, openReport, arch);
        }
Пример #23
0
        private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport) {
            var model = (IComponentModel)(session._serviceProvider.GetService(typeof(SComponentModel)));
            var interpreterService = model.GetService<IInterpreterOptionsService>();

            var interpreterPath = runTarget.InterpreterPath;
            var arch = ProcessorArchitecture.X86;
            if (runTarget.PythonInterpreter != null) {
                var interpreter = interpreterService.FindInterpreter(
                    runTarget.PythonInterpreter.Id,
                    runTarget.PythonInterpreter.Version
                );
                if (interpreter == null) {
                    return;
                }
                interpreterPath = interpreter.Configuration.InterpreterPath;
                arch = interpreter.Configuration.Architecture;
            }

            RunProfiler(session, interpreterPath, runTarget.Script, runTarget.Arguments, runTarget.WorkingDirectory, null, openReport, arch);
        }
Пример #24
0
        private static void RunProfiler(SessionNode session, string interpreter, string script, string arguments, string workingDir, Dictionary<string, string> env, bool openReport, ProcessorArchitecture arch) {
            var process = new ProfiledProcess(
                (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService)),
                interpreter,
                String.Format("\"{0}\" {1}", script, arguments ?? string.Empty),
                workingDir,
                env,
                arch
            );

            string baseName = Path.GetFileNameWithoutExtension(session.Filename);
            string date = DateTime.Now.ToString("yyyyMMdd");
            string outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + ".vsp");

            int count = 1;
            while (File.Exists(outPath)) {
                outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vsp");
                count++;
            }

            process.ProcessExited += (sender, args) => {
                var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));
                _profilingProcess = null;
                _stopCommand.Enabled = false;
                _startCommand.Enabled = true;
                if (openReport && File.Exists(outPath)) {
                    dte.ItemOperations.OpenFile(outPath);
                }
            };

            session.AddProfile(outPath);

            process.StartProfiling(outPath);
            _profilingProcess = process;
            _stopCommand.Enabled = true;
            _startCommand.Enabled = false;
        }
Пример #25
0
        internal void StartProfiling(ProfilingTarget target, SessionNode session, bool openReport = true) {
            ThreadHelper.Generic.Invoke(() => {
                if (!Utilities.SaveDirtyFiles()) {
                    // Abort
                    return;
                }

                if (target.ProjectTarget != null) {
                    ProfileProjectTarget(session, target.ProjectTarget, openReport);
                } else if (target.StandaloneTarget != null) {
                    ProfileStandaloneTarget(session, target.StandaloneTarget, openReport);
                } else {
                    if (MessageBox.Show("Profiling session is not configured - would you like to configure now and then launch?", "No Profiling Target", MessageBoxButton.YesNo) == MessageBoxResult.Yes) {
                        var newTarget = session.OpenTargetProperties();
                        if (newTarget != null && (newTarget.ProjectTarget != null || newTarget.StandaloneTarget != null)) {
                            StartProfiling(newTarget, session, openReport);
                        }
                    }
                }
            });
        }
Пример #26
0
        internal static void ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport)
        {
            var model = (IComponentModel)(session._serviceProvider.GetService(typeof(SComponentModel)));

            var projectHome = PathUtils.GetAbsoluteDirectoryPath(
                Path.GetDirectoryName(projectToProfile.FullName),
                (string)projectToProfile.Properties.Item("ProjectHome").Value
                );

            var args            = (string)projectToProfile.Properties.Item("CommandLineArguments").Value;
            var interpreterPath = (string)projectToProfile.Properties.Item("InterpreterPath").Value;
            var searchPath      = (string)projectToProfile.Properties.Item("SearchPath").Value;
            var project         = projectToProfile.AsPythonProject();

            var interpreter = project != null?project.GetInterpreterFactory() : null;

            if (interpreter == null /*|| interpreter == interpreterService.NoInterpretersValue*/)
            {
                MessageBox.Show(String.Format("Could not find interpreter for project {0}", projectToProfile.Name), "Python Tools for Visual Studio");
                return;
            }

            var arch           = interpreter.Configuration.Architecture;
            var pathEnvVarName = interpreter.Configuration.PathEnvironmentVariable;

            if (String.IsNullOrWhiteSpace(interpreterPath))
            {
                interpreterPath = interpreter.Configuration.InterpreterPath;
            }

            string startupFile = (string)projectToProfile.Properties.Item("StartupFile").Value;

            if (String.IsNullOrEmpty(startupFile))
            {
                MessageBox.Show("Project has no configured startup file, cannot start profiling.", "Python Tools for Visual Studio");
                return;
            }

            string workingDir = projectToProfile.Properties.Item("WorkingDirectory").Value as string;

            if (String.IsNullOrEmpty(workingDir) || workingDir == ".")
            {
                workingDir = projectToProfile.Properties.Item("ProjectHome").Value as string;
                if (String.IsNullOrEmpty(workingDir))
                {
                    workingDir = Path.GetDirectoryName(projectToProfile.FullName);
                }
            }

            var env = new Dictionary <string, string>();

            if (!String.IsNullOrWhiteSpace(pathEnvVarName) && !String.IsNullOrEmpty(searchPath))
            {
                var searchPaths = searchPath.Split(';').ToList();
                var pyService   = (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService));
                if (!pyService.GeneralOptions.ClearGlobalPythonPath)
                {
                    searchPaths.AddRange(Environment.GetEnvironmentVariable(pathEnvVarName).Split(';'));
                }

                env[pathEnvVarName] = string.Join(";", searchPaths
                                                  .Where(PathUtils.IsValidPath)
                                                  .Select(p => PathUtils.GetAbsoluteDirectoryPath(projectHome, p))
                                                  .Where(Directory.Exists)
                                                  .Distinct(StringComparer.OrdinalIgnoreCase)
                                                  );
            }

            var userEnv = projectToProfile.Properties.Item("Environment").Value as string;

            if (userEnv != null)
            {
                foreach (var envVar in userEnv.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var nameValue = envVar.Split(new[] { '=' }, 2);
                    if (nameValue.Length == 2)
                    {
                        env[nameValue[0]] = nameValue[1];
                    }
                }
            }

            RunProfiler(session, interpreterPath, startupFile, args, workingDir, env, openReport, arch);
        }
Пример #27
0
 public ContextCommandTarget(SessionNode node, uint itemid) {
     _node = node;
     _itemid = itemid;
 }
Пример #28
0
        internal SessionNode OpenTarget(ProfilingTarget target, string filename) {
            for (int i = 0; i < _sessions.Count; i++) {
                if (_sessions[i].Filename == filename) {
                    throw new InvalidOperationException(String.Format("Performance '{0}' session is already open", filename));
                }
            }

            uint prevSibl;
            if (_sessions.Count > 0) {
                prevSibl = _sessions[_sessions.Count - 1].ItemId;
            } else {
                prevSibl = VSConstants.VSITEMID_NIL;
            }

            var node = new SessionNode(_serviceProvider, this, target, filename);
            _sessions.Add(node);

            OnItemAdded(VSConstants.VSITEMID_ROOT, prevSibl, node.ItemId);

            if (_activeSession == VSConstants.VSITEMID_NIL) {
                SetActiveSession(node);
            }

            return node;
        }
Пример #29
0
 public ContextCommandTarget(SessionNode node, uint itemid)
 {
     _node   = node;
     _itemid = itemid;
 }
Пример #30
0
        private static void ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport) {
            var project = projectToProfile.AsPythonProject();

            var config = project?.GetLaunchConfigurationOrThrow();
            if (config == null) {
                MessageBox.Show("Could not find interpreter for project {0}".FormatUI(projectToProfile.Name), Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.ScriptName)) {
                MessageBox.Show("Project has no configured startup file, cannot start profiling.", Strings.ProductTitle);
                return;
            }

            if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".") {
                config.WorkingDirectory = project.ProjectHome;
                if (string.IsNullOrEmpty(config.WorkingDirectory)) {
                    config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName);
                }
            }

            RunProfiler(session, config, openReport);
        }
Пример #31
0
        private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport) {
            LaunchConfiguration config;
            if (runTarget.PythonInterpreter != null) {
                var registry = session._serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>();
                var interpreter = registry.FindConfiguration(runTarget.PythonInterpreter.Id);
                if (interpreter == null) {
                    return;
                }
                config = new LaunchConfiguration(interpreter);
            } else {
                config = new LaunchConfiguration(null);
            }

            config.InterpreterPath = runTarget.InterpreterPath;
            config.ScriptName = runTarget.Script;
            config.ScriptArguments = runTarget.Arguments;
            config.WorkingDirectory = runTarget.WorkingDirectory;

            RunProfiler(session, config, openReport);
        }
Пример #32
0
        private static void RunProfiler(SessionNode session, LaunchConfiguration config, bool openReport) {
            var process = new ProfiledProcess(
                (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService)),
                config.GetInterpreterPath(),
                string.Join(" ", ProcessOutput.QuoteSingleArgument(config.ScriptName), config.ScriptArguments),
                config.WorkingDirectory,
                session._serviceProvider.GetPythonToolsService().GetFullEnvironment(config)
            );

            string baseName = Path.GetFileNameWithoutExtension(session.Filename);
            string date = DateTime.Now.ToString("yyyyMMdd");
            string outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + ".vsp");

            int count = 1;
            while (File.Exists(outPath)) {
                outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vsp");
                count++;
            }

            process.ProcessExited += (sender, args) => {
                var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE));
                _profilingProcess = null;
                _stopCommand.Enabled = false;
                _startCommand.Enabled = true;
                if (openReport && File.Exists(outPath)) {
                    dte.ItemOperations.OpenFile(outPath);
                }
            };

            session.AddProfile(outPath);

            process.StartProfiling(outPath);
            _profilingProcess = process;
            _stopCommand.Enabled = true;
            _startCommand.Enabled = false;
        }
Пример #33
0
        internal void SetActiveSession(SessionNode node) {
            uint oldItem = _activeSession;
            if (oldItem != VSConstants.VSITEMID_NIL) {
                _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_UnBoldItem);
            }

            _activeSession = node.ItemId;

            _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_BoldItem);
        }
Пример #34
0
 internal AutomationSession(SessionNode session) {
     _node = session;
 }
Пример #35
0
        private void ProfileProjectTarget(SessionNode session, ProjectTarget projectTarget, bool openReport) {
            var targetGuid = projectTarget.TargetProject;

            var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
            EnvDTE.Project projectToProfile = null;
            foreach (EnvDTE.Project project in dte.Solution.Projects) {
                var kind = project.Kind;

                if (String.Equals(kind, PythonProfilingPackage.PythonProjectGuid, StringComparison.OrdinalIgnoreCase)) {
                    var guid = project.Properties.Item("Guid").Value as string;

                    Guid guidVal;
                    if (Guid.TryParse(guid, out guidVal) && guidVal == projectTarget.TargetProject) {
                        projectToProfile = project;
                        break;
                    }
                }
            }

            if (projectToProfile != null) {
                ProfileProject(session, projectToProfile, openReport);
            } else {
                MessageBox.Show("Project could not be found in current solution.", Strings.ProductTitle);
            }
        }
Пример #36
0
 internal AutomationSession(SessionNode session)
 {
     _node = session;
 }