Attach to process on Visual Studio - c#

I trying to do something very simple here.
I use Visual Studio 2012. I created simple visual Studio class called BLA. The whole code is below.
using System;
using System.Collections.Generic;
using System.Text;
namespace BLA
{
public class Class1
{
public void hit() {
Console.Write("sdf");
}
}
}
I build it without errors. I put a breakpoint in "Console.Write("sdf")" and then try attach to process to iexplore.exe.
The process it attached but I get an error
The breakpoint will not currently be hit. No symbols have been loaded for the document.
I tried searching in google and stackoverflow I got many answers but none of them solved my problem.
Any idea how?

What kind of application are you building, you mention that you attach to iexplore.exe is it a webapplication?
You could allways try System.Diagnostics.Debugger.Break() to give you a debugging option.

You have to create the object of class Class1 and call the method hit() from that object.

Related

What is unknown construction in class declaration?

I've just made a mistake while writing my code, and I find out some interesting unknown stuff.
public class OperationFactory(int code)
{
}
What (int code) it is here?
My compiler doesn't tell anything, so that's why I'm asking
I hope that You are not using Visual Studio IDE. are you?
I thought you are using Visual studio Code, need to install c# intelligence extensions if using other IDE's.
Compilation error. You may see warning if you are using Visual Studio IDE.
The Definition of class not allowing to take parameters msdn link
//[access modifier] - [class] - [identifier]
public class Customer
{
// Fields, properties, methods and events go here...
}

How to make a .dll and run it with NUnit?

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.

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.

MSTest: No tests are run because no tests are loaded or the selected tests are disabled

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.

Debugging C# Custom Installer Classes

I have written an installation class that extends Installer and overrides afterInstall, but I'm getting a null pointer exception. How can I go about debugging my class?
Something that is handy for hard to debug sections of code is
System.Diagnostics.Debugger.Break()
Will throw a breakpoint caught by any installed debugger (VStudio, WinDbg, Remote debugger etc...).
Use it to debug really tricky areas where regular F5+Go or "Attach to Process" is difficult or impossible to perform, some examples include:
short-lived processes
time-sensitive processes
breaking into spawned sub-processes
installers
service stop/start
distributed systems
The best way I've found is to write a unit test, and new up and initialize your installer class from your unit test:
[TestClass] public class InstallerTest {
[TestMethod]
public void InstallTest() {
// substitute with your installer component here
DataWarehouseInstall installer = new DataWarehouseInstall();
string assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string installLogFilePath = Path.Combine(assemblyDirectory, "install.log");
installer.Context = new System.Configuration.Install.InstallContext(installLogFilePath, null);
// Refactor to set any parameters for your installer here
installer.Context.Parameters.Add("Server", ".");
//installer.Context.Parameters.Add("User", "");
//installer.Context.Parameters.Add("Password", "");
installer.Context.Parameters.Add("DatabaseName", "MyDatabaseInstallMsiTest");
//installer.Context.Parameters.Add("DatabasePath", "");
// Our test isn't injecting any save state so we give a default instance for the stateSaver
installer.Install(new Hashtable());
} }
At least then it takes advantage of the IDE tooling better. This is especially helpful for very large installers with LOTS of components. Then you can also create ordered unit tests and run them in sequence to mimic your installer during debug or your automated builds.
Another tip would be general SOLID/GRASS software principles...develop in neat/thin layers, keeping your actual "custom action" installer logic very simple and instead call into any reusable API stuff you have that is specific to your installer(s), just as we are used to with UI development. (The installer is just another UI anyway.) This is especially key if your goal is to have a certain UI experience shared across all installers of your products.
Surprised no one has actually answered. Put a MessageBox.Show("hello") into your custom action's Install() member. Build the deployment in debug config. Install. When the MessageBox appears, go into VS IDE, Debug, Attach Process and look for the instance of msiexec that is labeled "Managed". Attach the debugger to that instance of msiexec. Now go back to the source of your custom action and place a breakpoint right after the call to MessageBox.Show(). Close the MessageBox and your breakpoint will be hit, and you're debugging in the IDE!
attach the installer process to Visual studio in Debug->Processes->Attach or CTRL + ALT + P
set the breakpoint and you should be able to go
In your installer method add Debugger.Launch() statement which will launch "Visual Studio just in time debugger" where you can attach an instance of visual studio and debug your installer class (MSI). This should work in Visual Studio 2010 as well. But you need to have administrative rights to do this. If you don't have administrative rights, you might have issues. So, log in as administrator for debugging MSI. For example:
public override void Install(System.Collections.IDictionary stateSaver)
{
Debugger.Launch();
base.Install(stateSaver);
}
In visual studio 2005, even Debugger.Break() use to work but somehow this does not work with Visual Studio 2010.
This is what actually worked for me.
System.Diagnostics.Debugger.Launch();
Then right click on the Installer Project and press "Install"
None of above worked for me. This is what actually worked. Note that you need to put insert "both" lines.
using System.Diagnostics;
MessageBox.Show("Test is about to begin");
Debugger.Launch();
I use EventLog.WriteEntry("source", "message"), and check the EventLog when installing. Maybe not optimal, but works for me :)
I use the following class to write a simple log into the target directory. In my opinion, it's easier than trying to use the Visual Studio debugger.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace MyCompany.Deployment
{
/// <summary>
/// Enables a quick and easy method of debugging custom actions.
/// </summary>
class LogFile
{
const string FileName = "MyCompany.Deployment.log";
readonly string _filePath;
public LogFile(string primaryOutputPath)
{
var dir = Path.GetDirectoryName(primaryOutputPath);
_filePath = Path.Combine(dir, FileName);
}
public void Print(Exception ex)
{
File.AppendAllText(_filePath, "Error: " + ex.Message + Environment.NewLine +
"Stack Trace: " + Environment.NewLine + ex.StackTrace + Environment.NewLine);
}
public void Print(string format, params object[] args)
{
var text = String.Format(format, args) + Environment.NewLine;
File.AppendAllText(_filePath, text);
}
public void PrintLine() { Print(""); }
}
}
For logging purposes (in 3.5) what about using:
Context.LogMessage("My message");
Write the following code in the beginning of the method that you want to debug
#if DEBUG
MessageBox.Show(Process.GetCurrentProcess().Id.ToString());
#endif
So when your method is called, the above code will be hit and you can then attach the debugger to the process(ctrl+alt+p) using the above process ID. You may have to start VS with elevated permissions.
build a VM, install Visual studio, make a copy of it (or create a differencing Virtual HDD) and run the installer under the debugger under the VM.
That is what I would do (but I'm no expert).
You can also use the installUtil.exe utility to test your installer component.
In case you created a c# class assembly with your Installer class, Change your debug settings to start the external program 'C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe'
and enter your commandline arguments accordingly (e.g. /Args=myargument "path to the assembly")
As last set your breakpoints, press f5 and you're set to debug your code.
--paralax
You might automate debugging of installer projects by adding following section to either .csproj or .csproj.user file:
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<StartAction>Program</StartAction>
<StartProgram>$(MSBuildBinPath)\installutil.exe</StartProgram>
<StartArguments>$(AssemblyName).dll</StartArguments>
</PropertyGroup>
Use project file if you want other developers benefit from this change and .user file if you want to use it by yourself.

Categories