How to programatically clean output in Visual Studio 2013 - c#

I print output on the console in WPF and ASP.NET-MVC applications by:
System.Diagnostics.Debug.WriteLine("text");
how to programatically clear the output window?

// Import EnvDTE and EnvDTE80 into your project
using EnvDTE;
using EnvDTE80;
protected void ClearOutput()
{
DTE2 ide = (DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0");
ide.ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").Clear();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ide);
}

This is what I use in VS2013, Win10, x64:
private static void ClearVS2013DebugWindow()
{
// add reference to "C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\PublicAssemblies\envdte.dll"
EnvDTE.DTE ide = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0");
if (ide != null)
{
ide.ExecuteCommand("Edit.ClearOutputWindow", "");
System.Runtime.InteropServices.Marshal.ReleaseComObject(ide);
}
}
Credit to the answers above.

Within the underlying APIs, the debug output is a forward only stream - you shouldn't assume that it is only viewable within Visual Studio. Debug output can only be written by an application, and if you need more detailed control, it should be shown within the User Interface of your application (whether that is a console window, which can be cleared; or a WinForms application, or WPF, etc.)

Related

How to execute Visual Studio commands in C#?

I want to execute Visual Studio command to import/export settings file in C#.
Can I do this using DTE2. If yes how to do?
How to initialize DTE2 and do..Please give the complete code.
Can I make use of this?
ExecuteCommand("Tools.ImportandExportSettings", "/export:\"C:/temp/setttings.vssettings\"")
If yes - then how to initialize dte2 and call the method?
You can try the following code to execute Visual Studio command to import/export settings file in c#.
First, you need to install nuget package ->EnvDTE.
Second, you can use the following console app to get the settings file.
class Program
{
static void Main(string[] args)
{
var filename = "D:\\own.vssettings";
var dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.
GetActiveObject("VisualStudio.DTE.16.0"); // version neutral
dte.ExecuteCommand("Tools.ImportandExportSettings", "/export:" + filename);
}
}
We need to note that if your vs version is vs 2010, we should use VisualStudio.DTE.10.0,
If your vs version is vs2013, we should use VisualStudio.DTE.12.0, If your vs version is
vs2017 or later, we should use VisualStudio.DTE.16.0.
My vs version is vs2017, so I used VisualStudio.DTE.16.0.
Result:(The part of setting file)

How do I open an .sln file in older Visual Studio in C# code?

I implemented a .NET application where the user browses for solution files. The user can choose to open these solution files in Visual Studio.
The problem is that the solutions need to be opened in Visual Studio 2008. Not in Visual Studio 2010 or above. This is necessary to keep the solution files in their original state.
All this should happen in C#. Bellow is the code but it opens the sln files with the default Visual Studio of the user.
if (file.EndsWith(".sln") && File.Exists(file))
System.Diagnostics.Process.Start(file);
Well, you are just launching a new process indicating file to the file and letting Windows to handle everything for you. Windows know that .SLN files should be opened with default associated program and that's it.
To change this behavior you have to programmatically analize the version of your SLN file, and based on SLN version open concrete version of VisualStudio passing as parameter the SLN file.
So you would need to emulate from your C# code something like:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>devenv.exe "C:\PATH\SOLUTION.sln"
It could look somehow like this:
private static void Main(string[] args)
{
var slnPath = #"C:\PATH\SOLUTION.sln";
var slnVersion = GetVersion(slnPath);
switch (slnVersion)
{
case ...:
break;
case 14:
var startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe";
startInfo.Arguments = slnPath;
Process.Start(startInfo);
break;
}
}
I figured out that it isn't necessary to detect the original version, in which the solutions were made. All solutions are created in Visual Studio 2008 by default.
Find the solution in the code bellow:
Add the reference EnvDTE.dll and using EnvDTE; in your code
public static void OpenSlnFile(string file)
{
System.Type type = Type.GetTypeFromProgID("VisualStudio.DTE.9.0");
EnvDTE.DTE dte = (EnvDTE.DTE)System.Activator.CreateInstance(type);
dte.MainWindow.Visible = true;
dte.Solution.Open(file);
}
Which program launched on clent depend on the registry key HKEY_CLASSES_ROOT\VisualStudio.Launcher.sln (referenced by HKEY_CLASSES_ROOT.sln)
When you open the file, it runs "c:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe" "%1", which reads the version from the .sln file and open the correct version.
About .sln file structure you can read at https://msdn.microsoft.com/en-us/library/bb165951.aspx

Where to get Windows.VisualStudio.Data?

Hello I'm am beginning with visual studio and C#
I saw a very nice thread here: Display a ConnectionString dialog
Sadly the Link for the sample code is dead
Either way I need to use the object : DataConnectionDialog
this object is in the Windows.VisualStudio.Data namespace. Where can I Include that it's not there in the add reference window. Where can I download that.
I am using VS community 2013
You can add reference to Microsoft.Data.ConnectionUI.Dialog.dll which can be found under
C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Microsoft.Data.ConnectionUI.Dialog.dll
Microsoft.Data.ConnectionUI.DataConnectionDialog dlg = new Microsoft.Data.ConnectionUI.DataConnectionDialog();
Microsoft.Data.ConnectionUI.DataSource.AddStandardDataSources(dlg);
if (Microsoft.Data.ConnectionUI.DataConnectionDialog.Show(dlg) == DialogResult.OK)
{
}

Expression Blend + Sketchflow - Addin?

Has anyone been able to get an extension up and running Expression Blend + Sketchflow preview? I'm looking for an example project.
I was following this article, but it is a bit outdated.
So far I:
Created a .Net 4.5 class library project
Added a reference to the Microsoft.Expression.Extensibility.dll in the new Blend Preview directory
Set my project to deploy to the appropriate Addins directory
Setup Visual Studio to run the new Blend.exe for debugging
Hooked up MEF and inherited IPlugin as in the example
But my plugin doesn't seem to load and no breakpoints are hit.
After reading your question I decided to start working on a new version of that tutorial.
A few things to get you started right away.
I've created the basic plugin like this:
using System.ComponentModel.Composition;
using Microsoft.Expression.Extensibility;
namespace Demo.Extension
{
[Export(typeof (IPackage))]
public class Demo : IPackage
{
public void Load(IServices services)
{
}
public void Unload()
{
}
}
}
Make sure you:
place the plugins in ...\Blend Preview\extensions
run visual studio as administrator to be able to deploy to that folder during debug
implement the IPackage instead of IPlugin
Got it working by following the demo here.
I used the few modifications above, and put things in the Blend Preview directory.

Detecting if a program was run by Visual Studio, as opposed to run from Windows Explorer

Is there a way to detect if your program was loaded through Visual Studio vs. whether it was started as a standalone executable?
Our software has a bug reporting feature to handle unhandled exceptions -- we need to be able to distribute debug builds to our beta testers, but we don't want the bug report to go off when we are in the middle of development, because the Exceptions are a lot more useful if VS catches them with a full stack trace, etc.
Right now, I'm disabling the bug report if Application.ExecutablePath includes bin\Debug or bin\Release, but I figure there is probably a more robust way of detecting whether the program was loaded through VS.
Obviously, we could set up a different build with some preprocessor macros, but for the sake of the question, assume that isn't a possibility -- I don't mind adding code, but I'm trying to make the fewest modifications to the build process, which is why command-line options are kind of a last resort as well.
If it matters, I'm using VS2003/.NET 1.1.
If you're doing this to determine if it is in any debugger (clarified by #JaredPar), you can use Debugger.IsAttached in the exception handler.
try
{
// ...
}
catch(Exception ex)
{
if (!Debugger.IsAttached)
{
ExceptionHandler.Frob(ex);
}
else
{
throw;
}
}
Alternatively:
public static void Frob(Exception ex)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
I don't do .net development, but in java I have done this by passing a flag into the startup options of the application. So you could pass a debug flag into the app from the IDE, and then check for that, when the app is run as an executable the flag would not be present. I would be surprised if .net didn't have something similar.
I know this is old but the provided solutions are not very satisfying.
I used the following class instead:
using System.IO;
using System.Reflection;
public static class Program
{
public static string ExecutablePath
{
get;
private set;
}
static Program()
{
var assemblyPath = Assembly.GetEntryAssembly().Location;
var assemblyDirectory = Path.GetDirectoryName(assemblyPath);
if (assemblyDirectory.EndsWith(#"\Debug") || assemblyDirectory.EndsWith(#"\Release"))
{
string projectFile = Path.GetFileNameWithoutExtension(assemblyPath) + ".csproj";
var root = new DirectoryInfo(assemblyDirectory);
while (root.Parent != null)
{
if (File.Exists(Path.Combine(root.FullName, projectFile)))
break;
root = root.Parent;
if (root.Parent == null) // we could not find it (should not happen)
ExecutablePath = assemblyDirectory;
}
ExecutablePath = root.FullName;
}
else
{
ExecutablePath = assemblyDirectory;
}
}
}
Then you can just use Program.ExecutablePath. If you already have a class named Program you can just extend it by those properties and methods.
If running from Visual Studio it will give you the project path where the csproj-file resides. This is the executable path without the "bin\*\Debug" or "bin\*\Release" stuff.
If not running from Visual Studio it will give you the path where the executable resides.
The solution is independent of debug settings, other attached debuggers or build configurations. The only important thing is, that your configurations are named "Release" and "Debug".
Note: As Troy Gizzi mentioned in the comments, this solution only works if you run the executable from another directory than the output directory. For my use case (simulate the deployment directory structure with the project directory as the root directory), this is a suitable solution. In general I copy my executable later to the deployment directory and expect the same behavior as if I run my program from within Visual Studio. Content and other dependencies are located relative to the project directory in my case.
Have you considered command line arguments? Run the program from Visual Studio with a --no-exception-handling flag (or whatever sounds appropriate), and don't handle exceptions if that argument is passed in. When you start the program elsewhere, without this argument, it'll behave normally.
Instead of tracking by process tree, I would add a configuration flag that enables the reporting feature. The flag can always default to "true" unless you are in your DEV environment then you set it to "false".
Sometimes the application is started outside the debugger and the debugger gets attached later. (Doubleclick on a file where the application is assigned to ...) I use this code to wait for the debugger attach.
using System.Diagnostics;
Process[] procName = Process.GetProcessesByName("devenv");
if(procName.Length > 0)
MessageBox.Show("Wait for debugger attach");

Categories