I have a c# console application project in visual studio that should only be run:
with the debugger attached
and only after a full clean / rebuild
Is there a way to force the project to fail if hasn't had a full clean/rebuild prior to launch?
Background info: The application is used to deploy versions of another application. It gathers up everything that's needed from various sources including downloads, zips them and and places them in a version deployment system.
One of the sources it gathers up files from is the output directory of another project that it references. The full clean/rebuild is required to ensure that output directory contains the latest and correct binaries.
The REAL problem I'm trying to solve is making sure that we are deploying the latest and correct binaries from another project.
The only way for an application to know if it was built-clean is for it to inspect the rest of the files in the directory it lives in, how you do that is up to you (try using FileInfo and inspect the LastWriteTime property).
As for the debugger, try this:
using System.Diagnostics;
using System.Threading;
...
public static Int32 Main(String[] args) {
if( !Debugger.IsAttached ) {
Console.WriteLine("No debugger attached. Execution will resume once a debugger is attached.");
while( !Debugger.IsAttached ) Thread.Sleep( 100 );
}
}
I'am totally new to Windows Store App programming,
so i'am also new to Visual Studio Express.
My goal is to test a simpple class method.
As mentioned here the Express version do not have any built-in Unit testing.
In this thread, Rafal provides a solution.
I exactly did it like described, so my external tools look like this:
When i execute it (Tools --> "Execute NUnit"), Nunit starts and the Gui of NUnit appears. But suddenly this exception occurs:
And in Exception Details:
System.IO.FileNotFoundException...
at NUnit.Util.ProjectService.WrapAssembly(String assemblyPath)
at NUnit.Util.ProjectService.ConvertFrom(String path)
at NUnit.Util.ProjectService.LoadProject(String path)
at NUnit.Util.TestLoader.LoadProject(String filePath, String configName)
My project folder has this structure:
The test classes are in "WebTest.Shared".
I think i need a .dll to run in NUnit as mentioned by Jon here.
So, how can I make a dll out of my project to run it with NUnit?
Can anyone guide me through this problem? (Please step by step)
EDIT:
After i worked in ChrisM idea, the exception stll arises without "${BinDir}${TargetName}.dll/run" block (the exception details are the same as before):
EDIT No. 2:
I have set those values:
Title: Execute NUnit
Command: D:\Path\To\NUnit\bin\nunit.exe
Arguments: $(BinDir)$(TargetDir)$(TargetExt)/run
Initial directory: $(BinDir)
EDIT No. 3:
After closing and reopening VS Express
i got this new Exception:
And in NUnit Exception Details:
System.ApplicationException: Unable to find test in assembly
System.ApplicationException...
EDIT No. 4
Here is my test class (StringUtilitiesTest.cs):
using System;
using System.Collections.Generic;
using System.Text;
using WebappTest.Shared.Utilities;
using NUnit.Framework;
namespace WebappTest.UnitTest
{
[TestFixture]
public class StringUtilitiesTest
{
[Test]
public void TransferFunds()
{
Assert.AreEqual("Hello", StringUtilites.getString("Hello"));
}
}
}
In external Tools:
Have you tried replacing the curly braces {} in the argument box with normal ones ()?
Visual Studio 2017 Express (the final express version) includes the test explorer. Add the NUnit3TestAdapter NuGet to your project, and the test explorer should discover your tests.
I created a Windows service in C# (4.0) and am trying to install it using installutil tool in command line. However I get an exception. I managed to find out what part of my code is causing the exception - using some crappy logging but whatever - but now I want to understand why. So what I want to do is debugging the installation of my Windows Service.
I know how to debug the service itself, but here, I want to debug the content of my Installer.Install(IDictionary stateSaver) method in the service.
I tried to attach the debugger to the cmd.exe process but it obviously doesn't work. I was thinking also to attach the debugger to the installutil process but I have no clue how to do this.
I had a look to this post: How do you debug a windows service that is being installed? and several others but in this case, for some reason, this guy seem to have his service already in the services.msc which is not my case.
How can I achieve this?
You can put a Debugger.Break(); statement in the installer code, and it should launch the debugger for you.
If the above does not work, I have found this process works too. Basically, you compile in debug mode and install the service (I used installutil.exe through the command line). In code you pop-up a message box with the process ID. Startup a second instance of studio, attach it to that process and debug. The message box pauses it to allow setup. The process ID isn't important, its named InstallUtil.exe. I usually put a Debug.Break() in after the message box to guarantee it enters the code.
using System.Windows.Forms;
using System.Diagnostics;
...
#if DEBUG
int processId = Process.GetCurrentProcess().Id;
string message = string.Format("Please attach the debugger (elevated on Vista or Win 7) to process [{0}].", processId);
MessageBox.Show(message, "Debug");
#endif
....
How to debug the installation of a custom windows service
I have a c# solution with the following structure:
mySolution
myProject
myProject.MSTests
References
Microsoft.VisualStudio.QualityTools.UnitTestFramework
sutMSTests.cs
sutMSTests.cs:
[TestClass()]
public class sutMSTests
{
[TestMethod]
public void MyTest0()
{
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(4, 2 + 2);
}
}
When I try to run the tests via Test, Run, All Tests In Solution, I get the following on the VS2008 status line:
No tests are run because no tests are loaded or the selected tests are disabled.
Test, Windows, Test View shows no tests.
Note: I created the tests manually (works for xUnit.net) instead of using Microsoft's wizards.
I've compared my hand created MSTest setup to the setup another test that I generated using the wizard and they appear to be sufficiently similar.
Question: What are the most likely causes of the error message above?
Edit 2010-02-25: More information:
I right clicked the Solution Items folder, and choose Add, New Project, type Test Projects,Test Documents::Visual Studio Test Project template.
The new project's default do nothing test "TestMethod1" was detected and passed.
However, my test did not show up ... so I copied and pasted my test method into the default test test project "TestProject1".
My test was detected in "TestProject" BUT not in its original location.
I closely compared the files, organization, and settings of "TestProject1" with my hand created test project.
At this point, I am guessing that some setting gets made by the Visual Studio Test Project template that is not easily detectable.
imo, it should be just as easy to create a test project by hand as it is to create one with the Visual Studio Test Project template.
please note: I'm not saying that I'm against using the Visual Studio Test Project template; for me, I like to understand what's behind the curtain since this makes me imho a much better programmer.
Another one for the googlers - this one turned out to be my problem, and it's embarrassingly boneheaded of me. Make sure that your test project is set to build in whatever solution configuration you're using. If the test assembly isn't being built, VS won't be able to find any tests in the non-existent assembly, and you'll bang your head against the wall for a while :-)
Possibly a bit late, but this question googles up well, I thought I'd throw some crumbs in for future googlers.
Bryan Cook suggests checking the ProjectTypeGuids in his blog post about Manually creating a MS Test Project. Apparently the magic GUIDs you need are {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} for c# and {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F} for VB. See his blog post for more details.
In case the blog post ever goes away you need to add the following element in the main property group in the csproj file:
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
Another idea for the Googlers out there. My problem was trying to get ignored tests running again. Same MS error message occurs if you remove the Ignore label. Does not automatically re-enable the test. This article takes you through the last step. http://richallen.blogspot.com/2008/05/ms-test-re-enabling-ignored-tests.html
The fix is simple, even though it shouldn't be needed, if Visual Studio worked as it should.
To sum up what others have contributed, particularly in this article, here's what ultimately worked for me:
Use the Configuration Manager to make sure your test project is selected to build in whatever configuration and platform you're using (ex: configuration=Debug and platform=x86)
Make sure your method belongs to a [TestClass] and that it's both marked [TestMethod], and NOT using the attribute [Ignore]
Use Test View to find your test.
Open your Properties window (F4), and make sure your test is enabled
The original poster did do this, but I arrived here after not having done this:
Be sure that [TestClass] is declared at the top, public in scope:
namespace XYZ.API.Repository.Tests
{
[TestClass()]
public class ClientTests
{
I was receiving the same message and it turned out to be that I had my unit test project on a network drive. Once I moved it local it ran fine. Just something to try if you get this error.
John
I've just manually done this:
Created a new C# class library project with the following code:
namespace SO_Answer
{
public class Class1
{
public void Test()
{
var k = "Hello";
}
}
}
Saved the project and then went to 'File->Add->New Project' and chose 'Test Project'. After VS created the unit test project, I added a reference to the class library project I created earlier.
In my test I have this code:
namespace Unit_Test
{
/// <summary>
/// Summary description for UnitTest1
/// </summary>
[TestClass]
public class UnitTest1
{
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
#region Additional test attributes
// You can use the following additional attributes as you write your tests:
// Use ClassInitialize to run code before running the first test in the class
// [ClassInitialize()]
// public static void MyClassInitialize(TestContext testContext) { }
// Use ClassCleanup to run code after all tests in a class have run
// [ClassCleanup()]
// public static void MyClassCleanup() { }
// Use TestInitialize to run code before running each test
// [TestInitialize()]
// public void MyTestInitialize() { }
// Use TestCleanup to run code after each test has run
// [TestCleanup()]
// public void MyTestCleanup() { }
#endregion
/// <summary>
/// The test method 1.
/// </summary>
[TestMethod]
public void TestMethod1()
{
var f = new Class1();
}
}
}
The only code I added was the a using statement and the var f = new Class1(); statement. Looking at the MSTest runner, I can see TestMethod1 appear.
I can't think of a reason why your unit tests are not being picked up. The only time I've had this is because I was using the MSTest runner to try and view NUnit tests by mistake. Try starting from scratch.
This could be another reason. Check whether the solution is running on 64bit. If so change it to x86.
This must be a bug and is an absolute pain especially as you have to reenable every single test method individually. However a bit iof lateral thinking produced a better solution - rename the test class and rebuild. Then rename it back. Seems to work.
Ooops - no it doesn't. Renaming the class works but when it's renamed back it reverts to the original settings.
The trick is to close down Visual Studio and delete the .vsmdi (visual studio test meta data) file. This will be regenrated.
When you run into this issue, in Visual Studio, you have to create a Test Project.
1. Select Test in Tool bar and choose "New Test". Create your project and at this point create your test method. It should work after this point.
For posterity: I just found that marking tests as static made them silently fail to appear in the test list. Apparently that isn't allowed.
None of the other answers worked for me. I kept getting the following message in the output window:
------ Discover test started ------
========== Discover test finished: 2 found (0:00:00.1310428) ==========
No tests found to run.
In my case, the problem only occurred after I created a new configuration called 0-Local. I had to add <DebugSymbols>true</DebugSymbols to the relevant section of my csproj file, so it looks like this:
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == '0-Local|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\0-Local\</OutputPath>
</PropertyGroup>
Do you have a VSMDI file in your solution? I believe this file is required (NOT VERIFIED).
this is typical problem i have faced too. but the easiest solution I followed as my own is...just to build the project once and rebuild it again. so that you can resolve it.
Had this same issue but reading over the previous answers, everything looked good.
In my case, I had just run the test suite made a small change, built the solution and tried to run the test. No go. I tried building a couple more times and looking for problems other people had tried. Still no go.
I hit enter in one of my test methods to add a new and hit F6 to build the solution and clicked run Unit Tests.
Bingo! Everything ran smoothly.
I was making use of a public TestContext TestContext method to write to the test output and changed the scope to private. This made every test not discoverable. Changing it back to public helped.
Another one for googlers using NUnit, especially those who have migrated from MS Unit test to NUnit. Please remove the project type Guids that are identifying the project as MS Test project from the project file.
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
If your code is CLI (managed c++) and your test class inherits from an abstract base class, make sure that your test class implements the base's pure virtual method.
if you didn't implement it, you may see the "no tests found to run" message.
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");