Thursday, December 06, 2012

csUnit Interim Release 2.8.4723

We have made available a new release of csUnit. This is an interim release with the version number 2.8.4723 and can be found on GitHub.

This release requires .NET 4.5. It doesn’t have an installer and no Visual Studio plugin. The download is a zip file that you need to extract into a folder then run csUnitRunner from there. If you encounter an issue please log the issue here with detailed info about your environment, the version of csUnit you are using and steps to reproduce.

We intend to create a WiX based installer next.

For more info about csUnit check out csUnit’s homepage.

Saturday, September 15, 2012

Free Azure Storage Explorers

When working with Azure you’ll eventually work with storage (blob, table, …). Wouldn’t it be nice if you had a simple way to browse through the content of your Azure storage? And wouldn’t it be nice if you also use the same tool to access your local Azure storage emulator?

Here are two tools that do exactly that. And in addition they are free.

The first tool is “Azure Storage Explorer” provided by Neudesic. This tool is open source, hosted on Codeplex. It is licensed under the “Common Development and Distribution License (CDDL)”. I’ve used this tool for several months now and was very valuable, allowing moving files, copying files, creating containers, deleting containers, etc. You can set up all your storage accounts, including local development storage and then access it without having to enter credentials again. It remembers your access keys.

The second tool is “CloudBerry Explorer for Windows Azure” provided by CloudBerry. This tools is available as freeware. I just downloaded it and played with it for a little while, so can’t provide any detailed insights yet.

Having a tool for browsing your Azure storage content is a handy tool for developers as well. That’s why I thought it would be worth mentioning here.

Happy coding!

Tuesday, September 11, 2012

NullReferenceException in Html.ValidationSummary()

I was implementing a view using ASP.NET MVC, MVC 4 in this case but I suspect the version is irrelevant. I received a NullReferenceException when any validation failed, ie the model state was invalid.

The stack trace was close to useless and looked similar to the following:

at ASP._Page_Views_Issue_Create_cshtml.Execute() in c:\projects\au\AgileTraxx\Web\Views\Issue\Create.cshtml:line 26
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)

Line 26 which the stack trace referring to was:

Html.ValidationSummary();

This wasn’t much help either. It took me a lot of experimentation to find out that in this particular case the property Model of the view was null. Once I set the model for this view, it all went nicely.

Note that not always it is obvious from scanning the code that one didn’t set the model for a view. Therefore I’m blogging my experience here and to give the recommendation that should you encounter the same or similar behavior, to the following:

  1. Set a breakpoint on the line where the exception is thrown.
  2. Debug the application
  3. When the breakpoint is hit, enter “Model” in the “Immediate Window” in Visual Studio and check whether it outputs “null”.

Happy coding!

Saturday, April 21, 2012

ASP.NET: Base Directory and Developer Tests

Assume that in your ASP.NET application you need to access a file that is part of the deployed web site. On the other hand you would like to also run some developer tests.

The way I like to organize developer tests is putting them in a separate project and a separate assembly. For example for an ASP.NET project “MySite” I would have a second project called “MySite.Tests”. In the test project I then reference the “MySite” project which gives me direct access to all code inside of “MySite”. Typically give all projects a strong name and therefore can make internals of “MySite” visible to code in “MySite.Tests” by placing the InternalsVisibleToAttribute on the “MySite” assembly.

The challenge now with accessing the file is that depending on whether they are run from within an ASP.NET server (IIS or WebDev.WebServer) or within a unit test runner, finding the root folder (or base directory) can be tricky in some cases.

For example we could use a solution based on the MapPath method of the HttpContext.Current.Server object. This is described in more details in an answer on StackOverflow and works when an HttpContext is available. When the same code is run in a unit test runner HttpContext.Current is null (Controller.HttpContext in MVC), so this solution wouldn’t work.

The solution that I have chosen and that works so far is based on the application domain. The following code is all that is required and it works in both IIS, WebDev.WebServer as well as when executed within a unit test runner:

var domainRoot = AppDomain.CurrentDomain.BaseDirectory;
var configFile = Path.Combine(domainRoot, Common.DbSettingsFile);

Happy coding!

Wednesday, April 18, 2012

MVC 3 and "Microsoft JScript runtime error: 'jQuery' is undefined"

In the course of working on an ASP.NET MVC 3 based project I updated jQuery via NuGet. This worked as expected, except for one view where the application then reported the error "Microsoft JScript runtime error: 'jQuery' is undefined".

The resolution was to check the Java Script references in the view that had the problem. It was also necessary to updated _Layout.cshtml as follows:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>@ViewBag.Title</title>
   <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
   <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
   <script src="@Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
</head>
<body>
   ...
</body>
</html>

After these changes it worked like a charm.

Monday, April 16, 2012

WiX 3.6 Beta Behavior When Building

Just noticed an interesting behavior of a solution that contains about 20 projects and one WiX project. It would fail when using “Rebuild All” with some strange error in a wxs-file that compiled fine previously. When using “Rebuild” on the WiX project it would build just fine. This was reproducible at that point.

To resolve it I restarted Visual Studio and all was fine again. I couldn’t reproduce the issue. I guess that it was some add-in that got a pointer or reference mixed-up.

My setup is: Visual Studio 2010 Professional, ReSharper, dotCover, AnkhSVN, WiX 3.6 beta.

Monday, April 09, 2012

More On Closing WCF Connections

Some time ago I blogged about how to implement a WCF client in C# using VS2008. In particular I mentioned that implementing the client side code with a using statement may potentially lead to problems as – against their own advice – Microsoft chose to implement the Dispose() method of class System.ServiceModel.ClientBase<TChannel> in such a way that it can throw exceptions. (Dispose() implementations should not throw exceptions.) This implementation that violates Microsoft’s own guideline is also described in an article where Microsoft recommends not to use “using” when working with WCF clients.

In this blog post I’ll revisit the options for handling client side code. In the meantime I’ve moved to VS2010 and I’m using .NET 4.0. To get started let’s recall the code from back then:

var client = new PondServiceClient();

try {
   _pondStatusMessage.Text = _pondNameTextBox.Text +
      (client.IsFrozen(_pondNameTextBox.Text) ?
      " is frozen." : " free of ice.");
   client.Close();
}
catch (CommunicationException ex) {
   // Handle exception
   client.Abort();
}
catch (TimeoutException ex) {
   // Handle exception
   client.Abort();
}
catch (Exception ex) {
   // Handle exception
   client.Abort();
}

So the canonical form (also described on MSDN) is to check for CommunicationException and TimeoutException. If the service defines Service Fault's you may want to catch those exceptions (FaultException<T>) as well.

It would be great if there were ways to fix this problem as there is one more issue with using the canonical way. Imagine you have lots of touch points between your client and a service. Wouldn’t it be nice if you could avoid all that try-catch business? It looks like a lot of code duplication after all.

Marc Gravell’s Solution

One possible solution is described by Marc Gravell in his blog. He makes extensive use of generics. Using Marc’s solution the above code would look something like this:

using (var client = new Proxy().Wrap()) {
   _pondStatusMessage.Text = _pondNameTextBox.Text +
      (client.BaseObject.IsFrozen(_pondNameTextBox.Text) ?
      " is frozen." : " free of ice.");
}

I agree with Marc that this solution would be safe, easy to call and would eliminate the code duplications. His solution calls the service client’s Dispose() method (ClientBase<TChannel>.Dispose()) but wraps it inside a try-catch construct. If an exception is thrown by the Dispose() it is swallowed.

The first concern I have with this solution is that it doesn’t call Abort() and Close() respectively as per Microsoft’s recommendation. It just swallows the exception that might be thrown by the Dispose method.

The second concern I have is that the expression “new Proxy().Wrap()” doesn’t appear very intuitive and easy to understand. This is probably a minor point as with more experience in using this solution one can will become used to it.

Jeremy Jameson’s Solution

Another option can be found at Jeremy Jameson’s blog. Jeremy suggests to derive a class and add a new implementation for Dispose(). To stay with the pond service example, that new class would then look as follows:

public class PondServiceClientWithDisposeFix 
   : PondServiceClient, IDisposable {
   void IDisposable.Dispose() {
      if (this.State == CommunicationState.Faulted) {
         this.Abort();
      }
      else if (this.State != CommunicationState.Closed) {
         this.Close();
      }
   }
}

With this class in place the implementation of the client side could then be re-written as follows:

using(var client = new PondServiceClientWithDisposeFix()) {
   _pondStatusMessage.Text = _pondNameTextBox.Text +
      (client.IsFrozen(_pondNameTextBox.Text) ?
      " is frozen." : " free of ice.");
}

Very elegant, easy to understand and correct by the looks of it. I was tempted to use this option if it wasn’t for a concern that I have with this. With reverse engineering it is possible to find out what ClientBase<TChannel>.Dispose() does. When Jeremy wrote his blog (March 2010) the Dispose() implementation simply called Close().

My concern is that the new implementation doesn’t call the base class implementation at all. By the way the PondServiceClient class is declared partial so the Dispose method could probably be implemented as an extension method as well. As long as the base class implementation is not called, this couldn’t resolve my concern, though. What if Microsoft at any time decides to change the implementation of ClientBase<TChannel>.Dispose()? This kind of change typically happens – thanks, Murphy! – we we expect it the least.

Even if the implementation was never changed, there is a small thing that concerns me. Microsoft has included a little note regarding the use of the ClientBase<TChannel>.State property:

image

So, Jeremy’s solution probably will work. But it is against Microsoft’s recommendation of not using the State property. In particular I get nervous because of the term “race condition”. If problems occur because of race conditions these are typically hard to find and resolve, therefore a very expensive type of issue.

Therefore if we want to follow that recommendation we are back to square one. We would have to surround the use of ClientBase<TChannel> derived objects with boilerplate try-catch statements.

Using Anonymous Methods

Basically the problem is that in order to remove the code duplication a pair of code snipped has be executed before and after the service invocation. Proper handling of communication objects almost sounds like an aspect… so for a moment I even considered looking into libraries like DynamicProxy2 or Ninject. On second thought, though, these felt like overkill for something that appears very simple.

Enter anonymous methods. Basically you can pass a block of code to a different method that does things, executes the block of code, maybe does other things, then returns. How does this apply to the code snippet for the pond service example above. Let’s try to highlight with colors what the boiler plate code is and what the code is that is different:

image

The code within green rectangles is the actual implementation while the code in the orange rectangles is the boilerplate code. Note, how the orange pieces surround the second green piece.

The way to simply this is using a class that works like an interceptor. I implemented a class called ServiceClientInterceptor and it’s main method now looks as follows, again using green and orange rectangles as above:

image

As you can see the green rectangle simply invokes the function that was passed in. With the ServiceClientInterceptor in place you can now write the client side code as follows:

using (var client = new PondServiceClient()) {
   new ServiceClientInterceptor(client).Invoke(() => {
      _pondStatusMessage.Text = _pondNameTextBox.Text +
         (client.IsFrozen(_pondNameTextBox.Text) ?
         " is frozen." : " free of ice.");
   });
}

Line 2 in this example show the beginning of an anonymous method that is passed in as a parameter to the Invoke() method. The cool thing is that inside of the anonymous method you have access to the variables that are accessible at the point of where the anonymous method is defined. It is not limited to where the intercept invokes the execution of that anonymous method.

As a result you can now wrap service invocations with try-catch statements without code duplication.


With this general concept working there are of course further questions that I haven’t covered in this blog post. For example, what if you want reuse the service client for further invocations in the same using block? What if you had multiple service clients that are used within the same anonymous method? I’ll leave these to you for further explorations as there several options in each case.

The solution presented here meets the following requirements:

  • Allows use of using construct
  • Properly closes or aborts WCF connections depending on exception thrown
  • Avoids code duplication
  • Does not make use of ClientBase<TChannel>.State property as per Microsoft’s recommendation

To complete this blog post, below is the full source for the ServiceClientInterceptor class. In that case I have changed the parameter type of the Invoke method to Action. In the screenshots above I still used ServiceMethod which had an identical definition but was the result of earlier experimentation. The Action delegate encapsulates a method that has no parameters and does not return a value. As always you are welcome to use this code at your own risk.

If you know of a solution better than any of the ones mentioned in this post I'd like to hear from you. Happy coding!

public class ServiceClientInterceptor {
   public ServiceClientInterceptor(
         ICommunicationObject serviceClient) {
      _serviceClient = serviceClient;
   }

   public void Invoke(Action func) {
      try {
         func.Invoke();
         _serviceClient.Close();
      }
      catch (CommunicationException ex) {
         _serviceClient.Abort();
         // Handling and/or re-throwing exception is 
         // application specific
      }
      catch (TimeoutException ex) {
         _serviceClient.Abort();
         // Handling and/or re-throwing exception is 
         // application specific
      }
      catch (Exception ex) {
         _serviceClient.Abort();
         // Handling and/or re-throwing exception is 
         // application specific
      }
   }

   private ICommunicationObject _serviceClient;
}

Saturday, March 03, 2012

VisualBasic .NET and C#

In case you need to compare language features of VB.NET and C#, you might find the following URL helpful. It contains a quite detailed comparison of both languages.

Thursday, January 19, 2012

ReSharper Not Showing Any Tests?

Version 6.x of ReSharper appears to have a tendency to forget about some tests in a solution once a while (at least once a day in my case). When using “Run All Tests From Solution” it can happen that it shows only a subset of them. In extreme cases it can happen that no tests are shown in the “Unit Tests Session” window.

I’ve noticed that the behavior becomes better after removing all other extensions. I don’t feel this is very practical. The extensions I use are AnkhSVN and Powertools and I’m using Visual Studio 2010 on a 64 bit Windows 7. All software are the latest released versions and has the most recent patches or service packs applied.

I reinstalled everything but that didn’t change the behavior. When I run all unit tests outside of Visual Studio, e.g. using csUnit, it is all fine.

One way to resolve this is following these five steps:

  1. Close Visual Studio
  2. Delete the _ReSharper.* folder that is located in the folder containing your solution
  3. Start Visual Studio
  4. Reopen your solution
  5. Select “Run all tests from Solution” from the ReSharper menu

Since once in a while the web deployment functionality requires a restart of Visual Studio as well, I now have two triggers that may force me to restart Visual Studio.

Yes, it is annoying but at least now I have found this work around. Maybe it helps saving you some grief as well.