Aug 10 2011

Async CTP – Be Careful With Exceptions!

Category: Asynchrony,C#,Software DevelopmentWil @ 10:38 pm

I’m certainly no Bill Wagner, Jon Skeet or any of the other extremely intelligent and talented individuals who know their way around the new C# and VB asynchronous “stuff” coming soon from Microsoft. However, why can’t I throw my tattered and torn hat in the ring every now and then right?!

While preparing code for my talk at the upcoming Dallas TechFest 2011, and writing code samples to demonstrate how exceptions work with async and await, I ran across some nastiness that I really don’t think should be working, or in this case… breaking, the way it is in the refresh of the Async CTP. Since I could not find any mention of this issue on any website or forum (I’m not saying they don’t exist), I am going to show you it here.

Without any further ado, exceptions… inside an async method. Exceptions are supposed to propagate to the caller who is awaiting the completion of an async call. But… take this code for example:

public void Run()
{
	try
	{
		MyVoidAsyncMethod(null);

		Console.WriteLine("Press a key...");
		Console.ReadLine(); // <--- BIG problem!
	}
	catch (Exception ex_)
	{
		Console.WriteLine(ex_.Message);
	}
	Console.WriteLine("You'll never see this!");
}

private async void MyVoidAsyncMethod(string betterNotBeNull)
{
	if (string.IsNullOrEmpty(betterNotBeNull))
		throw new ArgumentNullException("That's why we can't have nice things!");

	await TaskEx.Yield();
}

Here’s what you get if you execute it:

Press a key…

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: That’s why we can’t have nice things!

Server stack trace:
at DallasTechFest_2011.DeleteMe.d__0.MoveNext() in C:\DTF2011\DallasTechFest2011_Async\02 Exception Demos\DeleteMe.cs:line 27

Exception rethrown at [0]:
at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.b__1(Object state)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Press any key to continue . . .

The UI thread is blocked by the Console.ReadLine() and that totally hoses up the entire system… and it crashes the application immediately. This is an edge case and is definitely one of those, “Doctor, it hurts when I do this. Well, don’t do that!” situations. You probably shouldn’t be blocking the UI thread that called the async method anyway… so say’th the peanut gallery… and I agree.

However, it is inside a try/catch which “appears” to be completely ignored. This all has to do with the way the compiler generates the code for an async method. The first thing it is contractually obligated to do is to create an AsynVoidMethodBuilder object… and it does as you can see from the exception above. But since this is an ‘async voic’ method, it sort of freaks out… which I believe (ultimately) it shouldn’t.

Now, if you replace the async method with one that returns a Task<> like this:

private async Task<int> MyTaskAsyncMethod(string betterNotBeNull)
{
	if (string.IsNullOrEmpty(betterNotBeNull))
		throw new ArgumentNullException("That's why we can't have nice things!");

	await TaskEx.Yield();

	return 42;
}

Then… all you get for output is:

Press a key…

Moral? Not sure… maybe it’s don’t block your UI?! Maybe it’s just a hole that will be filled shortly by the C# compiler team before C# 5 ships. It’s worth noting at least. You’ve been warned!

Tags: ,


Feb 05 2011

Texas Hold ‘Em at FullTiltPoker.com

Category: pokerWil @ 2:39 pm

Yes, I know this is my development blog but there are a lot of .Net’ers out there who play poker; specifically, Texas Hold ‘Em. I play sporadically or on occasion online at Full Tilt Poker. It’s fun and, so far, it’s been a money-making adventure. Last night I was in a hand for a very short period of time and I was extremely glad that I got out of the hand when I did (pre-flop). Click on this image to see what a tragic hand this was for a couple of people with great hands:

Ah, that’s just the way it goes sometimes!




W3Counter


Tags: , , ,


Feb 04 2011

Vyew.com – FREE Alternative to WebEx and GoToMeeting

Category: Collaboration,Productivity,WebWil @ 9:39 am

Vyew.com
Vyew.com is a fantastic alternative to spending $50 a month or more on GoToMeeting (which requires a download) or WebEx. They Vyew interface is entirely web-based so there is no requirement of downloading any additional client software. It’s written with Adobe Flash and Java (as far as I can tell) and seems to be extremely well laid out and responsive. “Vyew allows you to meet and share content in real-time or anytime. Upload images, files, documents and videos into a room. Users can access and contribute at anytime.”

Vyew is 100% free as long as you’re ok with advertisements and a somewhat limited account. Still, the free account seems to have more power than the average Joe normally needs. Should you find yourself not one of the average Joes, you can opt to pay for a “bigger” account with no advertising. If you take this route, you’ll still pay 80% less than WebEx or GoToMeeting.

The only caveat is that it is not “live” like WebEx or GoToMeeting… meaning you can share but you can’t see the presenter’s screen in real-time fashion. That may be a deal breaker for you.

Give them a shot and let me know what you think!



W3Counter


Tags: , , ,


Feb 04 2011

Better Testing… Part II

So you’ve dug in and started directly testing (using the extension methods I provided in Part I) your protected and private methods where, hopefuly, the vast majority of your business logic resides. In this post I want to show you how to invoke a method that is an overload on the same class. Using the GetMethod method on Type will puke if more than one method with the same exact name exists on the type you’re attempting to call. Here’s how to fix that problem:

	// Call the AddException method on the _importer object.
	// The 2nd parameter to 'Call' is the parameter list to pass to AddException
	// The 3rd parameter to 'Call' is the types of the parameters expected by the AddException method
	_importer.Call("AddException", new object[] { new Exception("blah") }, new [] { typeof(Exception) });

You can see that the parameter list is an object[] so the Type.GetMethod method has no way of differentiating between two methods with the same name solely by looking at the parameters passed in. You have to specifically tell it, “Hey, I want you to call the ‘AddException’ method that expects an ‘Exception’ parameter.

Some might say, why not just create a phat testing base class instead of creating these extension methods. You could do that. However, I personally feel that this is slightly cleaner and a bit more readable. There are times when a testing base class comes in quite handy and I pretty much always use one… for a completely different reason though.

Let’s take a traditional look at how to write a test where you expect an exception to be thrown.

[Test, ExpectedException(typeof(ApplicationException))]
public void Demonstrate_NUnitWayOfExpectingExceptions()
{
	// This 'throw' will cause the test to pass because this test is
	// decorated above with the 'ExpectedException attribute.
	throw new ApplicationException(exceptionMessage);
}

If you do it this way, there’s no (decent) way to look at the thrown exception or do anything beyond where the exception is thrown. That’s not exactly ‘ideal’ when more than one type of exception could be thrown or if you want to do multiple things in the same method after the exception is thrown. Now let’s look at a slightly better way to do just that.

If you downloaded the source code in Part I, you’ll find a class named TestingBase.

[Test]
public void Demonstrate_ExpectException()
{
	// ExpectException (on base class) is great when you expect an exception but
	// ... the ExpectedException attribute just doesn't give you enough flexibility
	string exMessage = ExpectException<ApplicationException>(() => { throw new ApplicationException(exceptionMessage); });
	Assert.IsNotNull(exMessage);
	Assert.AreEqual(exMessage, exceptionMessage);

	// We're also free to continue more testing and still be in the same 'state'
	// Here we can write several lines of code 'inline'... no problem.
	exMessage = ExpectException<FileNotFoundException>
		(() =>{
				using (var reader = new StreamReader("this is not a valid file path"))
					reader.ReadToEnd();
			});
	Assert.IsNotNull(exMessage);
	Assert.IsTrue(exMessage.Contains("Could not find file"));
}

In the test above, we are calling a base class method called ExpectException which, as you can see, expects an exception of type ApplicationException to be thrown. ExpectException takes an Action and will execute the action and swallow any thrown exceptions, validate an exception is actually thrown, and ensure that the thrown exception is of the specified type. It also returns the message inside the exception so just in case you have more than one code branch that throws the same type of exception but has a different message… you’re able to validate that as well as is done in the code above.

Using the ExpectException method gives you more flexibility and to continue executing code in the test. There are times when you may need to write a test that calls a method twice in order to have it throw an exception. The ExtractId method in the Part I post has logic to ensure that the Person Id is only added once so that no two people can have the same Id. That is an example of a case where you would need to call that method twice. Now, ExtractId doesn’t throw an exception on the first call but it’s just an example and if it did, you could use ExpectException in that situation to make quick work of that test.

If you don’t want to bother with checking the returned exception string, you can use the other method on that base class called ExceptionWithMsg. Here’s an example of how to use it:

// ExceptionWithMsg is "implemented in terms of" ExpectException... meaning it
// just calls ExpectException and then verifies that the exception message contains
// the textual fragment passed in.
ExceptionWithMsg<FileNotFoundException>
	(() =>{
			using (var reader = new StreamReader("this is not a valid file path"))
				reader.ReadToEnd();
		},
		"Could not find file"
	);

ExceptionWithMsg just calls ExpectException and tests the message for you… as you can see from the implementation:

protected void ExceptionWithMsg<ExceptionType>(Action action_, string exceptionMessageFragment_)
{
	Assert.IsTrue(ExpectException<ExceptionType>(action_).Contains(exceptionMessageFragment_));
}

Enjoy!



W3Counter


Tags: , , , ,


Next Page »
Get Adobe Flash playerPlugin by wpburn.com wordpress themes