internal static void WriteMessage(string message)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (GeneralOutputWindowPane == null)
            {
                GeneralOutputWindowPane = ProjectPackage?.GetOutputPane(VSConstants.OutputWindowPaneGuid.GeneralPane_guid, "Add referenced projects to solution");
            }

            GeneralOutputWindowPane?.Activate();
            GeneralOutputWindowPane?.OutputStringThreadSafe(message + System.Environment.NewLine);
        }
        /// <summary>
        /// Log the error to the Output Window asyncronously.
        /// </summary>
        /// <remarks>
        /// It creates a new Output Window pane called "Extensions" where it logs to. This is to no polute
        /// the existing "Build" pane with errors coming from extensions.
        /// </remarks>
        /// <example>
        /// <code>
        /// try
        /// {
        ///     // Do work;
        /// }
        /// catch (Exception ex)
        /// {
        ///     await ex.LogAsync();
        /// }
        /// </code>
        /// </example>
        public static async Task LogAsync(this Exception exception)
        {
            try
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (await EnsurePaneAsync())
                {
                    _pane?.OutputStringThreadSafe(exception + Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                Diagnostics.Debug.WriteLine(ex);
            }
        }
        private void Build(uint options, IVsOutputWindowPane output, string target)
        {
            if (!this.NotifyBuildBegin())
            {
                return;
            }

            try {
                config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
            } catch (Exception e) {
                Trace.WriteLine("Exception : " + e.Message);
                ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
                this.NotifyBuildEnd(MSBuildResult.Failed, target);
                throw;
            } finally {
                ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
            }
        }
Beispiel #4
0
        public async Task PrintMessageAsync(string title, string contents = null)
        {
            if (_pane == null)
            {
                await VSPackage.TaskFactory.SwitchToMainThreadAsync();

                var outputWindow = _serviceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
                Assumes.Present(outputWindow);
                outputWindow.CreatePane(_paneGuid, _paneTitle, fInitVisible: 1, fClearWithSolution: 1);
                outputWindow.GetPane(_paneGuid, out _pane);
            }

            var message = contents == null
                ? "=== " + title + Environment.NewLine + Environment.NewLine
                : "=== " + title + Environment.NewLine + contents + Environment.NewLine + Environment.NewLine;

            _pane.OutputStringThreadSafe(message);
        }
Beispiel #5
0
        protected async void OnExecute(object send, EventArgs e)
        {
            try
            {
                string result = await RunExecuteAsync(send, e);

                if (false == string.IsNullOrEmpty(result))
                {
                    VSOutput(result);
                }
            }
            catch (Exception ex)
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                outputWindowPane.Activate();
                outputWindowPane.OutputStringThreadSafe(ex.ToString());
            }
        }
        public void MenuItemCallback(object sender, EventArgs e)
        {
            if (ShowErrorMessageAndReturnTrueIfNoSolutionOpen())
            {
                return;
            }

            var componentModel = Package.GetGlobalService(typeof(SComponentModel)) as IComponentModel;
            var dte            = Package.GetGlobalService(typeof(DTE)) as DTE;
            var slnPath        = dte.Solution.FileName;

            IVsOutputWindowPane customPane = DteUtil.GetThisExtensionOutputPane();

            customPane.OutputStringThreadSafe($"Starting full compilation of {slnPath}\r\n");

            IRoslynSolutionAnalysis roslyn = new RoslynSolutionAnalysis();

            roslyn.CompileFullSolutionInBackgroundAndReportErrors(slnPath, (message) => customPane.OutputStringThreadSafe(message));
        }
Beispiel #7
0
        public static void Log(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            try
            {
                if (EnsurePane())
                {
                    _pane.OutputStringThreadSafe($"{DateTime.Now}: {message} {Environment.NewLine}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }
Beispiel #8
0
    ///// <summary>
    ///// Initializes the logger and Application Insights telemetry client.
    ///// </summary>
    ///// <param name="provider">The service provider or Package instance.</param>
    ///// <param name="name">The name to use for the custom Output Window pane.</param>
    ///// <param name="version">The version of the Visual Studio extension.</param>
    ///// <param name="telemetryKey">The Applicatoin Insights instrumentation key (usually a GUID).</param>
    //public static void Initialize(IServiceProvider provider, string name, string version, string telemetryKey)
    //{
    //    Initialize(provider, name);
    //    Telemetry.Initialize(provider, version, telemetryKey);
    //}

    /// <summary>
    /// Logs a message to the Output Window.
    /// </summary>
    /// <param name="message">The message to output.</param>
    public static void Log(string message)
    {
        if (string.IsNullOrWhiteSpace(message))
        {
            return;
        }

        try
        {
            if (EnsurePane())
            {
                pane?.OutputStringThreadSafe(DateTime.Now + ": " + message + Environment.NewLine);
            }
        }
        catch (Exception ex)
        {
            Debug.Write(ex);
        }
    }
 public static void WriteExtensionOutput(string message, int retyrCount = 20)
 {
     try
     {
         IVsOutputWindowPane customPane = GetThisExtensionOutputPane();
         customPane.OutputStringThreadSafe(message);
     }
     catch (InvalidOperationException ex)
     {
         if (retyrCount > 0 && ex.Message.Contains("has not been loaded yet"))
         {
             System.Threading.Tasks.Task.Factory.StartNew(async() =>
             {
                 await System.Threading.Tasks.Task.Delay(5000);
                 WriteExtensionOutput(message, retyrCount - 1);
             });
         }
     }
 }
Beispiel #10
0
        public bool RemovePackage(string packageId)
        {
            if (!m_packageServices.IsPackageInstalled(m_project, packageId))
            {
                return(false);
            }


            var meta = m_packageServices.GetInstalledPackages(m_project).FirstOrDefault(p => p.Id == packageId);

            if (string.IsNullOrEmpty(meta?.InstallPath))
            {
                //
                // UinstallPackage() fails, with the following exception when the respective package is still
                // referenced by the project, but no longer present in the "packages"-folder.
                //
                // So in this case a rebuild of the project _and_ a restore of the (existing/old) NuGet
                // packages is required.
                //
                //  System.ArgumentException: Empty path name is not legal.
                //    at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
                //    at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
                //    at NuGet.ProjectManagement.MSBuildNuGetProject.<UninstallPackageAsync>d__36.MoveNext()
                //   ...
                //    at NuGet.VisualStudio.VsPackageUninstaller.UninstallPackage(Project project, String packageId, Boolean removeDependencies)
                //    at NUnitToMSTestPackage.Utilities.PackageHandler.RemovePackage(String packageId) in C:\Sources\Stuff\mine\NUnitToMSTest\NUnitToMSTestPackage\Utilities\PackageHandler.cs:line 87
                //    at NUnitToMSTestPackage.Commands.TransformProjectFilesCommand.RemoveNUnitPackages(Project selectedProject, StatusbarContext statusbar, Int32& complete, Int32 total) in C:\Sources\Stuff\mine\NUnitToMSTest\NUnitToMSTestPackage\Commands\TransformProjectFilesCommand.cs:line 186
                //    at NUnitToMSTestPackage.Commands.TransformProjectFilesCommand.<InvokeRefactoring>d__16.MoveNext() in C:\Sources\Stuff\mine\NUnitToMSTest\NUnitToMSTestPackage\Commands\TransformProjectFilesCommand.cs:line 147
                //
                string str = $"Could not remove package {packageId}, because it's InstallPath is not set. " +
                             "Possibly the package is no longer present in your \"packages\" folder. Packages can " +
                             "only be removed, if they are present there. You could revert what has changed, restore " +
                             "all existing/old packages and retry the conversion. Or you can manually remove the package " +
                             $"{packageId} from the project {m_project.Name}.";
                m_outputWindowPane?.OutputStringThreadSafe("Warning: " + str);
                ReportWarning?.Invoke(str);
                return(false);
            }

            m_uninstaller.UninstallPackage(m_project, packageId, true);
            return(true);
        }
Beispiel #11
0
        /// <inheritdoc />
        protected override void LogImpl(LogSeverity severity, string message, ExceptionData exceptionData)
        {
            if (severity < LogSeverity.Info)
            {
                return;
            }

            StringBuilder output = new StringBuilder();

            output.AppendLine(message);
            if (exceptionData != null)
            {
                output.Append("  ");
                output.AppendLine(exceptionData.ToString());
            }

            IVsOutputWindowPane outputWindowPane = GetOutputWindowPane();

            outputWindowPane.OutputStringThreadSafe(output.ToString());
        }
Beispiel #12
0
        internal static void DisplayOutPutMessage(string message)
        {
            IVsOutputWindowPane outputPane = null;
            var outputWindow = ServiceProvider.GlobalProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;

            if (outputWindow != null && ErrorHandler.Failed(outputWindow.GetPane(XSharpOutputWindowPane, out outputPane)))
            {
                IVsWindowFrame windowFrame;
                var            vsUiShell = ServiceProvider.GlobalProvider.GetService(typeof(SVsUIShell)) as IVsUIShell;
                uint           flags     = (uint)__VSFINDTOOLWIN.FTW_fForceCreate;
                vsUiShell.FindToolWindow(flags, VSConstants.StandardToolWindows.Output, out windowFrame);
                windowFrame.Show();

                outputWindow.CreatePane(XSharpOutputWindowPane, "XSharp - Debug Window", 1, 1);
                outputWindow.GetPane(XSharpOutputWindowPane, out outputPane);
                outputPane.Activate();
            }
            message = DateTime.Now.ToString("hh:mm:ss.fff") + " " + message + "\r\n";
            outputPane?.OutputStringThreadSafe(message);
        }
Beispiel #13
0
 internal override void BuildAsync(uint vsopts, string config, IVsOutputWindowPane output, string target, Action<MSBuildResult, string> uiThreadCallback) {
   var xSolutionBuildManager = (IVsSolutionBuildManager)this.GetService(typeof(IVsSolutionBuildManager));
   var xSolution = (IVsSolution)this.GetService(typeof(IVsSolution));
   if (xSolutionBuildManager != null && xSolution != null) {
     IVsHierarchy xStartupProj;
     xSolutionBuildManager.get_StartupProject(out xStartupProj);
     if (xStartupProj != null) {
       var xProj = xStartupProj as IVsProject3;
       Guid xGuid;
       xSolution.GetGuidOfProject(xStartupProj, out xGuid);
       if (xGuid != Guid.Empty) {
         if (xGuid != this.ProjectIDGuid) {
           uiThreadCallback(MSBuildResult.Successful, "Skipped");
           output.OutputStringThreadSafe("Project skipped, as it's not necessary for running\r\n\r\n");
           return;
         }
       }
     }
   }
   base.BuildAsync(vsopts, config, output, target, uiThreadCallback);
 }
Beispiel #14
0
    public static async Task LogAsync(string message)
    {
        await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

        if (string.IsNullOrEmpty(message))
        {
            return;
        }

        try
        {
            if (EnsurePane())
            {
                pane.OutputStringThreadSafe(DateTime.Now + ": " + message + Environment.NewLine);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.Write(ex);
        }
    }
#pragma warning disable VSTHRD010
        /// <inheritdoc/>
        public void Emit(LogEvent logEvent)
        {
            var sw = new StringWriter();

            _formatter.Format(logEvent, sw);
            var message = sw.ToString();

            if (_pane is IVsOutputWindowPaneNoPump noPump)
            {
                noPump.OutputStringNoPump(message);
            }
            else
            {
                ErrorHandler.ThrowOnFailure(_pane.OutputStringThreadSafe(message));
            }

            if (logEvent.Level == LogEventLevel.Error)
            {
                _pane.Activate();
            }
        }
        public static void Log(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            try
            {
                if (!EnsurePane())
                {
                    return;
                }
                ThreadHelper.ThrowIfNotOnUIThread();

                _pane.OutputStringThreadSafe(DateTime.Now + ": " + message + Environment.NewLine);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
        public static void Log(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            try
            {
                if (EnsurePane())
                {
                    ThreadHelper.Generic.BeginInvoke(() =>
                    {
                        pane.OutputStringThreadSafe(DateTime.Now + ": " + message + Environment.NewLine);
                    });
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
            }
        }
Beispiel #18
0
        protected override void WriteLine(string format, params object[] args)
        {
            if (outputPane == null)
            {
                var output          = (IVsOutputWindow)Package.GetGlobalService(typeof(SVsOutputWindow));
                var generalPaneGuid = VSConstants.GUID_OutWindowGeneralPane;

                if (ErrorHandler.Failed(output.GetPane(ref generalPaneGuid, out outputPane)) || outputPane == null)
                {
                    if (ErrorHandler.Failed(output.CreatePane(ref generalPaneGuid, "Global Command Capture Output", 1, 1)))
                    {
                        statusBar.SetText("Attempt to create output pane failed");

                        Stop();

                        return;
                    }

                    if (ErrorHandler.Failed(output.GetPane(ref generalPaneGuid, out outputPane)) || outputPane == null)
                    {
                        statusBar.SetText("Attempt to get output pane failed");

                        Stop();

                        return;
                    }
                }

                outputPane.SetName("Global Command Capture Output");

                WriteLine(format, args);
            }
            else
            {
                outputPane.OutputStringThreadSafe(string.Format(format + "\r\n", args));
            }
        }
        //--//

        private void Message(IVsOutputWindowPane pane, String msg)
        {
            if (pane == null)
            {
                return;
            }

            if (msg == null)
            {
                msg = "[no message string provided to MessageCentre.Message()" + new StackTrace().ToString();
            }

            try
            {
                lock (pane)
                {
                    pane.Activate();
                    pane.OutputStringThreadSafe(msg + "\r\n");
                }
            }
            catch (InvalidOperationException)
            {
            }
        }
Beispiel #20
0
 private void LogMessageToOutputWindow([CanBeNull] string value)
 {
     _pane.OutputStringThreadSafe(value);
 }
 private static void WriteLineToPane(IVsOutputWindowPane pane, string messageFormat, params object[] args)
 {
     int hr = pane.OutputStringThreadSafe(string.Format(CultureInfo.CurrentCulture, messageFormat, args: args) + Environment.NewLine);
     Debug.Assert(ErrorHandler.Succeeded(hr), "Failed in OutputStringThreadSafe: " + hr.ToString());
 }
Beispiel #22
0
        private void Build(uint options, IVsOutputWindowPane output, string target) {
            if (!this.NotifyBuildBegin()) {
                return;
            }

            try {
                config.ProjectMgr.BuildAsync(options, this.config.ConfigName, output, target, (result, buildTarget) => this.NotifyBuildEnd(result, buildTarget));
            } catch (Exception e) {
                if (e.IsCriticalException()) {
                    throw;
                }
                Trace.WriteLine("Exception : " + e.Message);
                ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
                this.NotifyBuildEnd(MSBuildResult.Failed, target);
                throw;
            } finally {
                ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
            }
        }
Beispiel #23
0
 public void Write(MessageCategory category, string message)
 {
     EnsurePaneVisible();
     _pane?.OutputStringThreadSafe(message);
 }
Beispiel #24
0
        private void Build(uint options, IVsOutputWindowPane output, string target)
        {
            if (!this.config.ProjectMgr.HasPassedSecurityChecks)
            {
                // From a security perspective, if there was something truly malicious about the project,
                // the user is about to toast himself by requesting a build.  Any further attempts at
                // preventing damage by avoiding MSBuild targets/tasks are futile.  So, from this point
                // forward, we might as well pretend that this project has passed all security checks,
                // and we're free to run any targets we like.
                this.config.ProjectMgr.HasPassedSecurityChecks = true;
            }

            // We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
            bool shouldRepaintReferences = (target == null || target == MsBuildTarget.Build || target == MsBuildTarget.Rebuild ||
                                            !this.config.ProjectMgr.HasPassedSecurityChecks);

            int shouldContinue = 1;

            foreach (IVsBuildStatusCallback cb in callbacks)
            {
                try
                {
                    ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
                    if (shouldContinue == 0)
                    {
                        return;
                    }
                }
                catch (Exception e)
                {
                    // If those who ask for status have bugs in their code it should not prevent the build/notification from happening
                    Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
                }
            }

            MSBuildResult result = MSBuildResult.Failed;

            try
            {
                result = config.ProjectMgr.Build(options, this.config.ConfigName, this.config.PlatformName, output, target);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception : " + e.Message);
                ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
                throw e;
            }
            finally
            {
                int success = ((result == MSBuildResult.Successful) ? 1 : 0);

                foreach (IVsBuildStatusCallback cb in callbacks)
                {
                    try
                    {
                        ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
                    }
                    catch (Exception e)
                    {
                        // If those who ask for status have bugs in their code it should not prevent the build/notification from happening
                        Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
                    }
                }

                ErrorHandler.ThrowOnFailure(output.FlushToTaskList());

                // Now repaint references if that is needed.
                // We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
                // One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
                // but msbuild can actually resolve it.
                // Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
                if (shouldRepaintReferences && (result == MSBuildResult.Successful))
                {
                    this.RefreshReferences();
                }
            }
        }
Beispiel #25
0
 private static void StreamOutput(Process/*!*/ process, StreamReader/*!*/ from, IVsOutputWindowPane/*!*/ output, BackgroundWorker worker)
 {
     while (!process.HasExited) {
         string line;
         while ((line = from.ReadLine()) != null) {
             output.OutputStringThreadSafe(line);
             output.OutputStringThreadSafe("\n");
             worker.ReportProgress(5);
         }
     }
 }
Beispiel #26
0
 public Task WriteAsync(MessageCategory category, string message)
 {
     EnsurePaneVisible();
     _pane?.OutputStringThreadSafe(message);
     return(Task.CompletedTask);
 }
Beispiel #27
0
        public virtual bool ObsoleteBuild(uint vsopts, string config, IVsOutputWindowPane output, bool fCleanBuild)
        {
            if (fCleanBuild)
            {
                // we are done
                return true;
            }

            lock (Project.BuildLock)
            {
                ProjectOptions options = this.GetProjectOptions(config);
                CompilerResults results;
                ArrayList files = new ArrayList();
/*UNDONE: need to get this to use MSBuild
                foreach (XmlElement e in doc.SelectNodes("//Files/Include/File"))
                {
                    //TODO: Support other "BuildActions" like "EmbeddedResource"...
                    if (e.GetAttribute("BuildAction") == "Compile")
                    {
                        string rel = e.GetAttribute("RelPath");
                        Url url = new Url(new Url(doc.BaseURI), rel);
                        files.Add(url.AbsoluteUrl);
                    }
                }
*/
                try
                {
                    ICodeCompiler compiler = this.GetCompiler();
                    if (files.Count == 1)
                    {
                        string filename = (string)files[0];
                        results = compiler.CompileAssemblyFromFile(options, filename);
                    }
                    else
                    {
                        string[] fileNames = (string[])files.ToArray(typeof(string));
                        results = compiler.CompileAssemblyFromFileBatch(options, fileNames);
                    }
                }
                catch (Exception e)
                {
                    results = new CompilerResults(options.TempFiles);
                    results.Errors.Add(new CompilerError(options.OutputAssembly, 1, 1, "", "Internal Compiler Error: " + e.ToString() + "\n"));
                    results.NativeCompilerReturnValue = 1;
                }
                taskProvider.Tasks.Clear();

                int errorCount = 0;
                int warningCount = 0;

                foreach (CompilerError e in results.Errors)
                {
                    if (e.IsWarning) warningCount++;
                    else
                        errorCount++;

                    NativeMethods.ThrowOnFailure(output.OutputTaskItemString(GetFormattedErrorMessage(e, false) + "\n", VSTASKPRIORITY.TP_HIGH, VSTASKCATEGORY.CAT_BUILDCOMPILE, "", -1, e.FileName, (uint)e.Line - 1, e.ErrorText));
                }

                NativeMethods.ThrowOnFailure(output.OutputStringThreadSafe("Build complete -- " + errorCount + " errors, " + warningCount + " warnings")); //TODO: globalize
                NativeMethods.ThrowOnFailure(output.FlushToTaskList()); 
                return results.NativeCompilerReturnValue == 0;
            }
        }
        /// <summary>
        /// Creates a logger instance
        /// </summary>
        /// <param name="shouldLog">Predicate that will be called when logging. Should return true if logging is to be performed, false otherwise.</param>
        /// <param name="pane">The output pane where logging should be targeted</param>
        public OutputWindowLogger(Func<bool> shouldLog, IVsOutputWindowPane pane)
        {
            this.predicate = shouldLog;

            if (pane is IVsOutputWindowPaneNoPump)
            {
                var asNoPump = pane as IVsOutputWindowPaneNoPump;
                this.print = (s) => asNoPump.OutputStringNoPump(s);
            }
            else
            {
                this.print = (s) => pane.OutputStringThreadSafe(s);
            }
        }
        private static void WriteLineToPane(IVsOutputWindowPane pane, string messageFormat, params object[] args)
        {
            int hr = pane.OutputStringThreadSafe(string.Format(CultureInfo.CurrentCulture, messageFormat, args: args) + Environment.NewLine);

            Debug.Assert(ErrorHandler.Succeeded(hr), "Failed in OutputStringThreadSafe: " + hr.ToString());
        }
Beispiel #30
0
 public override void WriteLine(string line)
 {
     _pane.OutputStringThreadSafe(line + Environment.NewLine);
     Debug.WriteLine(line, "Output Window");
 }
Beispiel #31
0
 public void WriteLine(string text)
 {
     output.Activate();
     output.OutputStringThreadSafe(text + Environment.NewLine);
 }
Beispiel #32
0
        private void PrintDebugMessage(string message, params object[] args)
        {
            var hResult = m_packageOutputPane.OutputStringThreadSafe(string.Format(CultureInfo.CurrentCulture, message, args) + Environment.NewLine);

            Marshal.ThrowExceptionForHR(hResult);
        }
        private static void WriteLineToPane(IVsOutputWindowPane pane, string message)
        {
            int hr = pane.OutputStringThreadSafe(message + Environment.NewLine);

            Debug.Assert(ErrorHandler.Succeeded(hr), "Failed in OutputStringThreadSafe: " + hr.ToString());
        }
Beispiel #34
0
 private void OnEventsOnPackageUninstalled(IVsPackageMetadata m)
 {
     m_outputWindowPane.OutputStringThreadSafe($"Uninstalled package {m.Id}, version {m.VersionString}.");
 }
Beispiel #35
0
 public void Log(string message)
 {
     ErrorHandler.ThrowOnFailure(pane.OutputStringThreadSafe(DateTime.Now + ": Ref12: " + message + "\n"));
 }
Beispiel #36
0
 public static void WriteToOutputPane(string message)
 {
     _pane.OutputStringThreadSafe($"{DateTime.Now}: {message} \n");
 }
 public VsGitFlowWrapper(string repoPath,IVsOutputWindowPane outputWindow)
     : base(repoPath)
 {
     CommandOutputDataReceived += (o, args) => outputWindow.OutputStringThreadSafe(args.Output);
     CommandErrorDataReceived += (o, args) => outputWindow.OutputStringThreadSafe(args.Output);
 }
Beispiel #38
0
    //////////////////////////////////////////////////////////////////////////////////////////////////    
    // This is called from the compiler background thread.
    //    fCleanBuild is not part of the vsopts, but passed down as the callpath is differently
    //
    //////////////////////////////////////////////////////////////////////////////////////////////////    
    /// <include file='doc\Project.uex' path='docs/doc[@for="Project.Build"]/*' />
    public virtual bool Build(uint vsopts, XmlElement config, IVsOutputWindowPane output, bool fCleanBuild){
      if (fCleanBuild){
        // we are done
        return true;
      }
      lock (Project.BuildLock){
#if LookForMemoryLeaks
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        long usedMemoryBeforeBuild = System.GC.GetTotalMemory(true);
#endif        
        int errorCount = 0;
        int warningCount = 0;
        CompilerResults results = this.CompileProject(config);

#if WHIDBEY
        if (this.taskManager != null && this.taskManagerBuild != null) {
          taskManager.ClearTasksOnProject(this.Caption);
          taskManagerBuild.ClearTasksOnProject(this.Caption);
          bool runVerifierBuildOnly = this.GetBoolAttr(config, "RunProgramVerifier") && !this.GetBoolAttr(config, "RunProgramVerifierWhileEditing");
          string verifierCode = ((int)System.Compiler.Error.GenericWarning).ToString("0000");
          
          foreach (CompilerError e in results.Errors) {
            if (e.IsWarning)
              warningCount++;
            else
              errorCount++;

            // output.OutputTaskItemString(GetFormattedErrorMessage(e, false) + "\n", VSTASKPRIORITY.TP_HIGH, VSTASKCATEGORY.CAT_BUILDCOMPILE, "", -1, e.FileName, (uint)e.Line - 1, e.ErrorText);
            int endLine;
            int endColumn;
            if (e is System.Compiler.CompilerErrorEx) {
              System.Compiler.CompilerErrorEx errorEx = (System.Compiler.CompilerErrorEx)e;
              endLine = errorEx.EndLine;
              endColumn = errorEx.EndColumn;
            }
            else {
              endLine = e.Line;
              endColumn = e.Column + 1;
            }

            bool isBuildOnly = runVerifierBuildOnly && e.ErrorNumber == verifierCode;
            
            (isBuildOnly ? taskManagerBuild : taskManager).AddTask(e.ErrorText, null, e.ErrorNumber, "CS" + e.ErrorNumber,
              TaskPriority.Normal, (e.IsWarning ? TaskCategory.Warning : TaskCategory.Error),
              (isBuildOnly ? TaskMarker.Error : (e.IsWarning ? TaskMarker.Warning : TaskMarker.CodeSense)),
              TaskOutputPane.Build, this.Caption, e.FileName,
              e.Line, e.Column, endLine, endColumn, null);
          }
          taskManager.OutputString("Build complete -- " + errorCount + " errors, " + warningCount + " warnings\n", TaskOutputPane.Build);
          taskManager.Refresh();
          taskManagerBuild.Refresh();
        }
        else {
#endif        
          this.taskProvider.ClearErrors();
          foreach (CompilerError e in results.Errors) {
            if (e.IsWarning) warningCount++;
            else
              errorCount++;
            output.OutputTaskItemString(GetFormattedErrorMessage(e, false) + "\n", VSTASKPRIORITY.TP_HIGH, VSTASKCATEGORY.CAT_BUILDCOMPILE, "", -1, e.FileName, (uint)e.Line - 1, e.ErrorText);
          }
          output.OutputStringThreadSafe("Build complete -- " + errorCount + " errors, " + warningCount + " warnings\n"); //TODO: globalize
          output.FlushToTaskList();
#if WHIDBEY
        }
#endif
        bool success = results.NativeCompilerReturnValue == 0;
#if LookForMemoryLeaks
        results = null;
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        System.GC.Collect();
        System.GC.WaitForPendingFinalizers();
        long usedMemoryAfterBuild = System.GC.GetTotalMemory(true);
        output.OutputStringThreadSafe("Build leaked "+(usedMemoryAfterBuild-usedMemoryBeforeBuild)+" bytes");
#endif
        return success;
      }
    }
Beispiel #39
0
        private void Build(uint options, IVsOutputWindowPane output, string target)
        {
            if (!this.config.ProjectMgr.HasPassedSecurityChecks)
            {
                // From a security perspective, if there was something truly malicious about the project,
                // the user is about to toast himself by requesting a build.  Any further attempts at
                // preventing damage by avoiding MSBuild targets/tasks are futile.  So, from this point
                // forward, we might as well pretend that this project has passed all security checks,
                // and we're free to run any targets we like.
                this.config.ProjectMgr.HasPassedSecurityChecks = true;
            }

            // We want to refresh the references if we are building with the Build or Rebuild target or if the project was opened for browsing only.
            bool shouldRepaintReferences = (target == null || target == MsBuildTarget.Build || target == MsBuildTarget.Rebuild
                || !this.config.ProjectMgr.HasPassedSecurityChecks);

            int shouldContinue = 1;
            foreach (IVsBuildStatusCallback cb in callbacks)
            {
                try
                {
                    ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
                    if (shouldContinue == 0)
                        return;
                }
                catch (Exception e)
                {
                    // If those who ask for status have bugs in their code it should not prevent the build/notification from happening
                    Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
                }
            }

            MSBuildResult result = MSBuildResult.Failed;
            try
            {
                result = config.ProjectMgr.Build(options, this.config.ConfigName, output, target);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception : " + e.Message);
                ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
                throw e;
            }
            finally
            {

                int success = ((result == MSBuildResult.Successful) ? 1 : 0);

                foreach (IVsBuildStatusCallback cb in callbacks)
                {
                    try
                    {
                        ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
                    }
                    catch (Exception e)
                    {
                        // If those who ask for status have bugs in their code it should not prevent the build/notification from happening
                        Debug.Fail(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.BuildEventError, CultureInfo.CurrentUICulture), e.Message));
                    }
                }

                ErrorHandler.ThrowOnFailure(output.FlushToTaskList());

                // Now repaint references if that is needed.
                // We hardly rely here on the fact the ResolveAssemblyReferences target has been run as part of the build.
                // One scenario to think at is when an assembly reference is renamed on disk thus becomming unresolvable,
                // but msbuild can actually resolve it.
                // Another one if the project was opened only for browsing and now the user chooses to build or rebuild.
                if (shouldRepaintReferences && (result == MSBuildResult.Successful))
                {
                    this.RefreshReferences();
                }
            }
        }
Beispiel #40
0
        private void Build(uint options, IVsOutputWindowPane output, string target)
        {
            int shouldContinue = 1;
            foreach (IVsBuildStatusCallback cb in callbacks)
            {
                try
                {
                    ErrorHandler.ThrowOnFailure(cb.BuildBegin(ref shouldContinue));
                    if (shouldContinue == 0)
                        return;
                }
                catch (Exception e)
                {
                    // If those who ask for status have bugs in their code it should not prevent the build/notification from happening
                    Debug.Fail(String.Format("Exception was thrown during BuildBegin event\n{0}", e.Message));
                }
            }

            MSBuildResult result = MSBuildResult.Failed;
            try
            {
                result = config.ProjectMgr.Build(options, this.config.ConfigName, output, target);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception : " + e.Message);
                ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
                throw e;
            }
            finally
            {

                int success = ((result == MSBuildResult.Sucessful) ? 1 : 0);

                foreach (IVsBuildStatusCallback cb in callbacks)
                {
                    try
                    {
                        ErrorHandler.ThrowOnFailure(cb.BuildEnd(success));
                    }
                    catch (Exception e)
                    {
                        // If those who ask for status have bugs in their code it should not prevent the build/notification from happening
                        Debug.Fail(String.Format("Exception was thrown during BuildEnd event\n{0}", e.Message));
                    }
                }
                ErrorHandler.ThrowOnFailure(output.FlushToTaskList());
            }
        }
Beispiel #41
0
        public void Build(uint options, IVsOutputWindowPane output, string target)
        {
            // We want to refresh the references if we are building with the Build or Rebuild target.
            bool shouldRepaintReferences = (target == null || target == MsBuildTarget.Build || target == MsBuildTarget.Rebuild);

            if (!NotifyBuildBegin()) return;
            try
            {
                config.ProjectMgr.BuildAsync(options, this.config.ConfigCanonicalName, output, target, (result, projectInstance) =>
                    {
                        this.BuildCoda(new BuildResult(result, projectInstance), output, shouldRepaintReferences);
                    });
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception : " + e.Message);
                ErrorHandler.ThrowOnFailure(output.OutputStringThreadSafe("Unhandled Exception:" + e.Message + "\n"));
                this.BuildCoda(new BuildResult(MSBuildResult.Failed, null), output, shouldRepaintReferences);
                throw;
            }
        }
        //--//

        private void Message(IVsOutputWindowPane pane, String msg)
        {
            if(pane == null)
                return;

            if(msg==null)
                msg = "[no message string provided to MessageCentre.Message()" + new StackTrace().ToString();

            try
            {
                lock (pane)
                {
                    pane.Activate();
                    pane.OutputStringThreadSafe(msg + "\r\n");
                }
            }
            catch( InvalidComObjectException )
            {
            }

        }