Skip to main content

Posts tagged with 'IL'

In the last post, we started using ServiceBase as a way to more generally address the services and use the callback to report errors to the UI.

What happens if I put the aspect on a method in a class that doesn't inherit from ServiceBase (because either I forgot, or I put an aspect on a class outside of the service layer by mistake)? Exceptions will be swallowed, not reported, and probably cause issues elsewhere in the project.

One approach would be to change the case from "args.Instance as ServiceBase" to "(ServiceBase)args.Instance". At least then, I'll get a runtime error about casting (but only if there's an exception). With PostSharp, we can do better than that.

In fact, remember when I said that PostSharp aspects have to be marked as [Serializable]? This is because, as compile time, PostSharp instantiates those aspect objects and serializes them to be used later at runtime. BUT, since the aspect is being instantiated anyway, PostSharp also does a couple of other optional steps: it can do some compile-time initialization (to avoid runtime reflection, for instance), and it can do some compile-time validation.

That's right, we can put some code in the aspect that can check to make sure that we're applying the aspect correctly. If we aren't, it will give us a compile-time error. We could check, for instance, that the aspect is being applied to a method in a class that inherits ServiceBase.

This code will only be executed at compile-time. If the declaring type (the class that the method is in) does not inherit from ServiceBase, then PostSharp will write out an error at compile time:

Compile-time initialization error in Visual Studio 2013

So now if I ever forget to use ServiceBase, or I use this aspect in the wrong place, I'll know right when I'm compiling. And because of this validation, I can also confidently change the cast from "args.Instance as ServiceBase" to "(ServiceBase)args.Instance", knowing that if the project compiles, that cast will never fail.

How are we doing:

  • This only works for ITerritoryService--what about the other services?
  • Swallowing exceptions: we should at least be logging the exception, not just ignoring it.
  • If the method has a return type, then it's returning null. If it's meant to return a reference type, that's probably fine, but what if it's returning a value type?
  • What if it's returning a collection, and the UI assumes that it will get an empty collection instead of a null reference?
  • Do we really want to return the exception message to the user?
  • What if I forget to use ServiceBase as a base class on a new service? <- We just took care of this

Next time we'll look at actually logging the exception.

In the previous post, we got the aspect to communicate with the service object by using args.Instance. But it only really works for one service: TerritoryService.

How can we get it to work with other services?

One approach would be to add a bunch of casts and if-statements:

I don't like that approach much. Another approach would be to create a base class that all our service classes would inherit from. I generally try to avoid this approach as much as possible, but I think it makes sense in this case. We could create an interface, like IHasValidationCallback, but let's take it one step further and create an abstract base class that already contains the implementation.

Now that the TerritorySerivce (and our other services) have a ServiceBase base class, we can update the aspect to use ServiceBase.

And there you have it: as long as all the services in the namespace inherit from ServiceBase, this will work.

So I think we're making progress, but let's review the issues from last time:

  • This only works for ITerritoryService--what about the other services? We just addressed this one.
  • Swallowing exceptions: we should at least be logging the exception, not just ignoring it.
  • If the method has a return type, then it's returning null. If it's meant to return a reference type, that's probably fine, but what if it's returning a value type?
  • What if it's returning a collection, and the UI assumes that it will get an empty collection instead of a null reference?
  • Do we really want to return the exception message to the user?
  • NEW ISSUE: What if I forget to use ServiceBase as a base class on a new service?

Yep, we fixed one issue, but we really just shifted the problem to a base class that could easily be overlooked. Next time, let's see if we can get PostSharp to help us with that.

In the last post, I laid out the bare essentials of an error handling aspect for my service layer.

Before I proceed further with the aspect, let's examine the layer right above the service layer: the UI layer. I'm using ASP.NET MVC.

With ASP.NET MVC, there is a concept of ModelState, which holds information about validations performed during model binding, and is also used by the controller to convey error information to the view (through the Html.ValidationSummary helper, for instance). I'm already using ModelState to convey simple validation errors; I'd like to use it to convey any errors that the service layer might encounter. There are many ways to approach this; I've chosen the "callback" approach--passing a lambda to the service layer in order to communicate error information from the service layer up to the UI layer. Here's the basics:

Dependency injection gives me an object that implements the ITerritoryService interface, but I have to take one more step and pass that service the lambda x => ModelState.AddModelError("", x) in the controller instructor. This is because ModelState doesn't actually get instantiated until the controller does (so I can't pass it to the service object any sooner).

Now, when there's an exception in Territory service, I can simply use this "callback" to add an error to the ModelState. (Side note: a benefit to this approach is that it does not couple TerritoryService to my UI: if I wanted to use this service with another UI--say, WebAPI or WebForms--then I would simply have to pass in a different lambda).

Let's get the aspect to use that callback.

By using args.Instance, we can get a reference to the object in which the method resides. If that object can be cast to ITerritoryService, then we can simply call AddModelError. This works great: now anytime there's an exception in TerritoryService, it will be added as an error to ModelState and displayed to the user.

But clearly there are still issues here:

  • This only works for ITerritoryService--what about the other services?
  • Swallowing exceptions: we should at least be logging the exception, not just ignoring it.
  • If the method has a return type, then it's returning null. If it's meant to return a reference type, that's probably fine, but what if it's returning a value type?
  • What if it's returning a collection, and the UI assumes that it will get an empty collection instead of a null reference?
  • Do we really want to show the exception message to the user?

Next time, we'll start addressing the first issue, and figure out a way to make this aspect more generic.

I've written a lot of AOP demos, given a lot of presentations on it (AOP For You and Me and The Class That Knew Too Much), and I even wrote a book about AOP in .NET. These aspects are all great places to start, but I thought I would take it a little deeper in a blog post series, detailing a real aspect I'm using in a real project, how I built it, and the reasoning behind the decisions I make. Because this is a much more practical example, this aspect is not generally applicable. You can't just drop it in to your project without tailoring it a bit. (If you are interested in those types of aspects, PostSharp has custom design patterns, ready for you to use today).

I'm only going to show you the basics of the aspect right now, and I'll build it up and add to it as this blog post series goes along. Note that this is an active project, and therefore it's still a work in progress. Part of the reason I'm doing this series is to help me get some real feedback!

My goal with this aspect is add error handling to my service layer. This service layer sits between my UI layer (an ASP.NET MVC application) and my data layer (which uses Dapper on a SQL Server database). When this aspect is done, it should:

  • Catch exceptions
  • Log (most) exceptions
  • Ensure that a useful/helpful/friendly error message is given to the UI, instead of bubbling up the exception
  • Make sure the service method returns something useful, if it's meant to return something

As an aspect, then, I can apply this to every public service method so that I don't have to worry about writing it over and over, and I don't have to worry about forgetting to add it to new service methods.

Let's start easy with a basic shell of an aspect:

I'm using MethodInterceptionAspect. I guess I could use OnMethodBoundaryAspect instead (or even OnExceptionAspect), since most of the code I'm going to write is going to end up being in that "catch" block. But let's just stick with this for now, and consider changing later (because of how PostSharp's API is structured, I know that this won't be very difficult).

Notice that there are two attributes on this aspect.

As it stands right now, this is not a good aspect, since it will just be swallowing all the exceptions. But it's as good as place to start as any, especially if you aren't familiar with AOP/PostSharp.

I'll also create another file in my project called Aspects.cs, which will contain assemly attributes so that I can apply this aspect to every method in the namespace where I put all my services.

I put an AspectPriority of "10" on it because I actually have another aspect in my project that I use to manage SQL transactions that has a priority of "20". I want the exception handling aspect to be the highest priority (lowest number).

Make sure you understand what's going on here before continuing. If not, you may want to review those presentations I linked to, check out the PostSharp documentation, or maybe check out my PostSharp Live webinar series.

Web accessibility: contrast

February 28, 2014 mgroves 0 Comments
Tags: html accessibility

I took a look at an issue submitted to an OSS project relating to contrast. The submitter of the issue claims that the text is hard to read on the Safari web browser. I looked at it in Chrome as well as Safari, and it looked roughly the same. Here it is:

Potentially low contrast text in Safari

Does that look hard to read? To me, I can definitely read it, no problem. But that's a rather selfish point of view: not everyone has the same ability to see as I do. We often hear about making web sites more accesible for users with screen readers (for the blind), but this is a case where it might be fine for someone with very healthy vision, and it might be fine for someone with no vision, but it might not be okay for someone with low vision.

So, I could just ask my Twitter followers what they think, but it would nice if I had a more concrete, objective way of knowing if this issue needs fixed or not. The W3C contrast ratio guidelines (pointed out to me by Jon Plante) gives me that concrete guideline to follow: a contrast ratio of at least 4.5:1. WebAIM's Color Contrast Checker makes it easy for me to do the math.

I opened up the above screenshot in an image editor1, and used it to figure out what the background and foreground colors are (MS Paint can do this, though you'll have to do the decimal-to-hex conversion yourself). The background color is #EFEFEF and the (main) foreground color is #B1B1B8. Here are the results:

WebAIM's Color Contrast Checker showing a failure

So, yes, this issue definitely has merit, so I submitted a pull request to NuGetGallery.

1In many cases, you can simply look at the CSS, but since this markup was in a disabled textbox, the browser actually dims the color. Hence the reason I needed to use an image editor.

 

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter