COM exceptions on exit with WPF - c#

After execution both of the following test cases, a COM execution is printed to the console. What am I doing wrong?
If I run either test singly, or if I run both tests together, the exception is written to the console exactly once. This makes me suspect that there's some sort of a per-AppDomain resource that I'm not cleaning up.
I have tried the tests with NUnit and with MSTest, with the same behavior in both environments. (Actually, I'm not sure if running both tests in MSTest results in a single exception printout or two.)
Exception:
System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used.
at System.Windows.Input.TextServicesContext.StopTransitoryExtension()
at System.Windows.Input.TextServicesContext.Uninitialize(Boolean appDomainShutdown)
at System.Windows.Input.TextServicesContext.TextServicesContextShutDownListener.OnShutDown(Object target)
at MS.Internal.ShutDownListener.HandleShutDown(Object sender, EventArgs e)
Test code:
using NUnit.Framework;
namespace TaskdockSidebarTests.Client
{
[TestFixture, RequiresSTA]
public class ElementHostRCWError
{
[Test]
public void WinForms()
{
var form = new System.Windows.Forms.Form();
var elementHost = new System.Windows.Forms.Integration.ElementHost();
form.Controls.Add(elementHost);
// If the form is not shown, the exception is not printed.
form.Show();
// These lines are optional. The exception is printed with or without
form.Close();
form.Controls.Remove(elementHost);
elementHost.Dispose();
form.Dispose();
}
[Test]
public void WPF()
{
var window = new Window();
// If the window is not shown, the exception is not printed.
window.Show();
window.Close();
}
}
}

Looking at my own code again, the following line might help for the WPF test, right at the end.
Dispatcher.CurrentDispatcher.InvokeShutdown();

You probably can't unit test the Window and Form classes at all. Both WinForms applications and WPF applications have an Application class used to start the underlying plumbing (message pumps and whatnot). I bet it's the key to avoiding that exception.
You're not doing that there and may not be able to.
Every recommendation for unit testing I've ever read is that you refactor so that the Form classes and Window classes don't do anything you need to unit test (like the M-V-VM pattern in WPF). Could have something to do with not being able to show the UI.
There are other ways to test a UI. This answer discusses unit testing UI.

Related

How to get output from unit test [duplicate]

Context:
We have some users reporting issues with a file upload feature in our web application. It only happens occasionally and without any special pattern. We have been trying to figure it out for a long time, adding debug information anywhere we can think it might help, crawling the logs etc, but we have not been able to reproduce or figure it out.
Problem:
I'm now trying to reproduce this by using MSTest and WatiN to repeat the operation that is supposed to fail a large number of times (several hundreds). Just to have a clue about how far in the loop the test has gotten, I want to print something like:
Console.WriteLine(String.Format("Uploaded file, attempt {0} of {1}", i, maxUploads));
This does however not appear in the Output window. Now I know that you'll get the console output in the test results (as well as what you output from Debug.Writeline etc), but this is not available until after the test has finished. And since my test with hundreds of repetitions could take quite some time, I'd like to know how far it has gotten.
Question:
Is there a way I can get the console output in the Output window during test execution?
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System;
using System.Diagnostics;
...
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");
Use the Debug.WriteLine. This will display your message in the Output window immediately. The only restriction is that you must run your test in Debug mode.
[TestMethod]
public void TestMethod1()
{
Debug.WriteLine("Time {0}", DateTime.Now);
System.Threading.Thread.Sleep(30000);
Debug.WriteLine("Time {0}", DateTime.Now);
}
Output
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
I had the same issue and I was "Running" the tests. If I instead "Debug" the tests the Debug output shows just fine like all others Trace and Console.
I don't know though how to see the output if you "Run" the tests.
It's not the console, but it is in the output panel.
public class Test
{
public TestContext TestContext { get; set; }
[TestMethod]
public void Foo()
{
TestContext.WriteLine("Hello World");
}
}
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

Load testing Visual Studio, start up script / setup

I was wondering if it was possible to have a start-up script before running any load tests? For example, perhaps to seed some data or clear anything down prior to the tests executing.
In my instance I have a mixed bag of designer and coded tests. Put it simply, I have:
Two coded tests
A designer created web test which points to these coded tests
A load test which runs the designer
I have tried adding a class and decorating with the attributes [TestInitialize()], [ClassInitialize()] but this code doesn't seem to get run.
Some basic code to show this in practice (see below). Is there a way of doing this whereby I can have something run only the once before test run?
[TestClass]
public class Setup : WebTest
{
[TestInitialize()]
public static void Hello()
{
// Run some code
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
return null;
}
}
Probably should also mention that on my coded tests I have added these attributes and they get ignored. I have come across a workaround which is to create a Plugin.
EDIT
Having done a little more browsing around I found this article on SO which shows how to implement a LoadTestPlugin.
Visual Studio provides a way of running a script before and also after a test run. They are intended for use in deploying data for a test and cleaning up after a test. The scripts are specified on the "Setup and cleanup" page in the ".testsettings" file.
A load test plugin can contain code to run before and after any test cases are executed, also at various stages during test execution. The interface is that events are raised at various points during the execution of a load test. User code can be called when these events occur. The LoadTestStarting event is raised before any test cases run. See here for more info.
If you are willing to use NUnit you have SetUp/TearDown for a per test scope and TestFixtureSetUp/TestFixtureTearDown to do something similar for a class (TestFixture)
Maybe a bit of a hack, but you can place your code inside the static constructor of your test class as it will automatically run exactly once before the first instance is created or any static members are referenced:
[TestClass]
public class Setup : WebTest
{
static Setup()
{
// prepare data for test
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
return null;
}
}

Writing msUnit tests for asynchronous procedures

If you call the Start()-Method of a MyClass-Object the Object will start sending data with the DataEvent.
class MyClass {
// Is called everytime new Data comes
public event DataEventHandler DataEvent;
// Starts de Data Process
public void StartDataDelivery()
{
}
}
How do I write a Test for that functionality if i can Guarantee that the DataEvent will be Invoked at least three times during a fix time period.
I haven't done any asynchronous Unittests yet. How is that done, assuming that someone else needs to understand the test later?
MSTest hasn't had any serious updates for some time and I don't see that changing.
I'd strongly recommend moving to xUnit. It supports async tests (just return a Task from the test and await to your heart's content), and is used by many new Microsoft projects.

How do I stop running code from executing?

I'm playing a little bit with some C# Winforms/WPF code and just stumbled upon something strange.
Let's say I have a code like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DoSomething();
// something more if everything worked okay
}
}
What puzzles me is that I cannot simply close the application from the method DoSomething before the constructor finishes its job. If anything during the execution of DoSomething fails, I need to close the application immediately; however, it just keeps running, executes the part // something more... and THEN closes, but that's way too late for me.
I have to put the code for closing the form inside the constructor itself with a following return; and then it works, but I don't really find that an acceptable solution. I'm trying to move such validation logic from the constructor to my methods.
I've tried things like:
public void DoSomething()
{
Close();
}
and
public void DoSomething()
{
Application.Current.Shutdown();
}
But it doesn't seem to work. Yes, both codes do close the application, but only after a fully finished constructor code.
Why would I need such a thing? Well, because at startup I need to check for various things, like availability of the connection and hardware, validate the user etc, and if anything fails, there's no point of executing more code.
I tried the same principle with Winforms and WPF (hence the tags) — works the same way.
Can anybody provide an explanation or a solution?
Just try using Environment.Exit(-1) in your situation and all will be good.
ADDED: This is the best reference i can get for you.
Difference between Application.Exit vs Application.Shutdown vs Environment.Exit
Application.Exit() is for exiting a windows forms application in a graceful way. Basically, it stops the message pump, closes all windows and lands you back in the Main() method just after the call to Application.Run(). However, sometimes it doesn't appear to work - this is usually because there are other foreground threads (apart from the UI thread) still running which are preventing the thread from ending.
Application.Shutdown() is (broadly) the equivalent of Application.Exit() in a WPF application. However, you have a bit more control as you can set the ShutDownMode so that the application shuts down when the main window closes, the last window closes or only when this method is called.
Environment.Exit() kills all running threads and the process itself stone dead. This should only be used in WF or WPF as a last resort when the more graceful methods are not working for some reason. It can also be used to make an abrupt exit from a console application.
Another Reference: How to properly exit a C# application?
You can always ignore your fellow developers and just use Environment.FailFast()
But really - don't. If you have critical things to do, S.A verifying the serial port is connected to the nuclear power plant, just do it prior. There's no rule forcing you to Application.Run(...) as soon as Main() is called.
There have already been posted viable solutions for your problem.
Just to answer your follow-up question: the reason why methods like Close() and Shutdown() do not immediately exit your application is that both just push messages into the application's message queue. They are only processed after MainWindow's constructor finished and code execution returns to the message processing loop, maybe even after some other still pending messages in the queue have been handled too.
On the contrary, methods like Environment.Exit() or Environment.FailFast() are kind of hard-core os functions leading to more or less immediately killing the process.
A workaround would be to throw a exception and handle it in application.UnhandledException
Define an Exception class:
public class InitializationException : Exception
{
public InitializationException()
{}
public InitializationException(string msg)
: base(msg)
{}
public InitializationException(string msg, Exception inner)
: base(msg, inner)
{}
}
and change your code like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
try
{
DoSomething();
// maybe something more if everything went ok
}
catch( InitializationException ex )
{
// log the exception
Close();
}
}
public void DoSomething()
{
if (notSomethingOK)
throw new InitializationException( "Something is not OK and the applicaiton must shutdown." );
}
}
This is a clean and maintainable solution.
System.Windows.Forms.Application.Exit();
Conceptually such things should not be used in class constructors. Constructor is somewhat made for instance initialization with starting state and not the actual things may happen (like exceptions, message boxes, etc).
Don't forget that you can just return; from constructor, if you need to break its execution. This is better tactic (most times you don't need to just shutdown application on error without displaying some text).
There are "window shown", "visibility changed", "loaded" and many other events in C# on Windows/WPF, that you can override virtually or add as an event handler. Initialize your form/app there.
They're normal methods so all works as expected. You can try throwing exceptions that your application entry point (Main function) will just catch and ignore.
For WPF, check this:
- https://msdn.microsoft.com/en-us/library/system.windows.forms.application.setunhandledexceptionmode(v=vs.110).aspx.

How to write to Console.Out during execution of an MSTest test

Context:
We have some users reporting issues with a file upload feature in our web application. It only happens occasionally and without any special pattern. We have been trying to figure it out for a long time, adding debug information anywhere we can think it might help, crawling the logs etc, but we have not been able to reproduce or figure it out.
Problem:
I'm now trying to reproduce this by using MSTest and WatiN to repeat the operation that is supposed to fail a large number of times (several hundreds). Just to have a clue about how far in the loop the test has gotten, I want to print something like:
Console.WriteLine(String.Format("Uploaded file, attempt {0} of {1}", i, maxUploads));
This does however not appear in the Output window. Now I know that you'll get the console output in the test results (as well as what you output from Debug.Writeline etc), but this is not available until after the test has finished. And since my test with hundreds of repetitions could take quite some time, I'd like to know how far it has gotten.
Question:
Is there a way I can get the console output in the Output window during test execution?
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine (In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System;
using System.Diagnostics;
...
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
// or Trace.Listeners.Add(new ConsoleTraceListener());
Trace.WriteLine("Hello World");
Use the Debug.WriteLine. This will display your message in the Output window immediately. The only restriction is that you must run your test in Debug mode.
[TestMethod]
public void TestMethod1()
{
Debug.WriteLine("Time {0}", DateTime.Now);
System.Threading.Thread.Sleep(30000);
Debug.WriteLine("Time {0}", DateTime.Now);
}
Output
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
I had the same issue and I was "Running" the tests. If I instead "Debug" the tests the Debug output shows just fine like all others Trace and Console.
I don't know though how to see the output if you "Run" the tests.
It's not the console, but it is in the output panel.
public class Test
{
public TestContext TestContext { get; set; }
[TestMethod]
public void Foo()
{
TestContext.WriteLine("Hello World");
}
}
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

Categories