DomainAspects: Aspect Oriented Programming Infrastructure for Domain Driven Design

The DomainAspects library introduced here may be the birth of an open source project that could add real value to the .NET stack. On the other hand, it could be just a small exploration of Castle Windsor's aspect oriented programming construct called the Interceptor. Time will tell but I felt it would be worth sharing the bits at this early stage to gauge interest and get some preliminary feedback.

DomainAspects is an aspect oriented infrastructure library for domain driven .NET projects. It uses Castle Windsor's Interceptor to provide configurable aspect oriented audit logging, authorization and exception handling to domain operations. Service classes in the domain can take advantage of DomainAspects using a custom attribute, avoiding the clutter of infrastructure code in the business logic.

There are many variations for the definitions of aspect oriented programming and domain driven design. I'll let Wikipedia contributors sort out the "pure" definitions. I'm not a purist or self-declared expert on either of these topics. But for the record, I'll share my definitions of these two as succinctly as I can.

Aspect Oriented Programming - The separation of cross cutting concerns, such as logging, authorization, and exception handling, from the business logic core of the application. AOP can allow the business application developer to focus on implementing business requirements without worrying about consistently applying and debugging repetitive infrastructure code throughout the application.

Domain Driven Design - An approach to writing applications where the domain is the core of the application. The domain defines the data, data persistence and business operations available to a user interface or service host of which it has no knowledge. DDD seeks to separate the mechanical concerns of the application host from the core business operations and data in order to maximize the potential for application developer specialization and code re-use. Common constructs seen in the domain are entities, services and repositories with a dependency on a persistence framework or data access layer.

DomainAspects brings AOP to DDD to make it easier to write the domain layer. Now I can write my acceptance criteria driven tests for a business operation and then implement that business operation with pure business logic while one or two simple attributes assure the consistent execution of infrastructure code every time that method is called. Here's a simplistic example:

[InterceptOperation, Authorize(RolesRule = "!Guest")]
public string GetUserPhoneNumber(int userId)
{
  var userRepository = new UserRepository();
  return userRepository.GetUser(userId).PhoneNumber;
}

And using that operation is just as easy. Here's the code to call that operation using the DomainProxy (normal UI exception handling not shown):

private void ShowPhoneButton_Clicked(object sender, EventArgs e)
{
  using (var proxy = new DomainProxy<IUserService>())
  {
    var phone = proxy.Service.GetUserPhoneNumber(userId);
    this.txtPhone.Text = phone;
  }
}

The client or host code uses the DomainProxy wrapper to get an IDisposable instance of a Castle Windsor container instance of the service class which is in turn wrapped by the Interceptor proxy. Here’s a look at these three important classes:

da_class_1

Under the covers, three specific DomainAspects infrastructure things are happening via the auditor and authorizer objects injected into the interceptor along with the principal provider object injected into the authorizer object. Here’s a look at the classes in question.

da_class_2

The first two things that happen occur before the proxy proceeds with calling the business operation. The third only happens if the business operation code throws an exception.

  1. The OperationAuditor's LogOperationInvoked method is called allowing the invokation to be logged by your implementation of IOperationAuditor.
  2. The OperationAuthorizer's Authorize method is called where the authorize attribute's rule is enforced. In this case, the logged in user cannot be in the role "Guest" or an exception will be thrown. Note that the IPrincipal used to determine this is provided by the injected PrincipalProvider implementation.
  3. The OperationAuditor's LogOperationException method is called if the business operation throws an exception.

In future posts, I'll write about each of these parts and how they work, but for now, download the code and let me know what you think. You will need to download the Castle Windsor library and correct the references in the solution depending on where you have installed the Castle project library.

Download the code here: DomainAspects.zip (29.39 KB)

Target Framework and Platform Target: Get Your .NET Projects on the Same Page

It builds and runs fine on your local machine but when you deploy it to the server, all kinds of problems arise. Before you spent countless hours chasing ghosts, make sure you have your .NET projects on the same page, namely building for the right .NET Framework and targeting the right platform.

Open your project properties bag and try these first and then narrow it down. First, make sure your target frameworks for all your projects are in synch.

targetframework

Then make sure you give yourself as much latitude as you can by setting your platform target to Any CPU:

anycpu

Once you know your project and its dependencies are all on the same page and you still have problems on your deployment target, then go ahead and spend countless hours chasing ghosts.

ASP.NET MVC Custom Authorize Attribute with Roles Parser

Do you ever get frustrated with the limited nature of the ASP.NET MVC AuthorizeAttribute class’s limited Roles property which provides only a simple comma delimited list and creates a simple OR list? Would you like to be able to exclude specific roles or have a more complex expression such as:

!Guest & ((Admin | Supervisor) | (Lead & Weekend Supervisor))

Well, now you can. All thanks to the random convergence of great minds! (Or perhaps the obsessions of two code monkeys who have no life. You decide.)

While working on a project for a future blog post, I discussed the code with Nick Muhonen of Useable Concepts and MSDN author who offered to write a parser for an authorization strategy in the project that uses attributes similar to the ASP.NET MVC AuthorizeAttribute class.

Nick showed me the parser yesterday and after I agreed to say that I liked the code, he sent it to me with his blessing to use in my blog post project I’ve been working on. As I began to work the code into my project, I realized that this code deserved its own post as a descendant of the real ASP.NET MVC AuthorizeAttribute class for general use in the ASP.NET MVC world. I’m still planning to use the same parser for my future post, but here it is for your general use in your ASP.NET MVC projects.

The power starts in the return value of the RoleParser’s Parse method, the IRule:

public interface IRule
{
  bool Evaluate(Func<string, bool> matcher);
  string ShowRule(int pad);
}

Here’s the simple, but powerful SuperAuthorizeAttribute class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using SuperMvc.RoleRules;

namespace SuperMvc
{
  public class SuperAuthorizeAttribute : AuthorizeAttribute
  {
    private string _superRoles;
    private IRule _superRule;

    public string SuperRoles
    {
      get
      {
        return _superRoles ?? String.Empty;
      }
      set
      {
        _superRoles = value;
        if (!string.IsNullOrWhiteSpace(_superRoles))
        {
          RoleParser parser = new RoleParser();
          _superRule = parser.Parse(_superRoles);
        }
      }
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
      base.OnAuthorization(filterContext);
      if (_superRule != null)
      {
        var result = _superRule.Evaluate(role => filterContext.HttpContext.User.IsInRole(role));
        if (!result)
        {
          filterContext.Result = new HttpUnauthorizedResult();
        }
      }
    }
  }
}

You’ll note that the setter on SuperRoles creates a parser instance and generates an IRule for later use in the OnAuthorization override. This allows us to parse once and run many times, making the evaluation even faster.

I’m not going to dive into how the parser works. I’ll let Nick blog about that. The great thing is that it does work and it’s very fast. Here’s how it’s put to use. First a look at the controller code on which we test it and a peek at one or two of the test methods. The HomeController has been modified with some test actions:

//partial listing

public class HomeController : Controller
{
  [SuperAuthorize(SuperRoles = "!Guest")]
  public ActionResult AboutTestOne()
  {
    return RedirectToAction("About");
  }

  [SuperAuthorize(SuperRoles = "Admin & Local Office | Local Office Admin")]
  public ActionResult AboutTestFive()
  {
    return RedirectToAction("About");
  }

  [SuperAuthorize(SuperRoles = "!Guest & !(SuperUser | DaemonUser) & ((Admin & Local Office | Local Office Admin) & !User)")]
  public ActionResult AboutCrazyTwo()
  {
    return RedirectToAction("About");
  }

  public ActionResult About()
  {
    return View();
  }
}

And here’s the tests, including some crucial initialization logic, that allows us to verify the attribute works.

[TestClass]
public class HomeControllerTest
{
  [TestInitialize]
  public void Initialize()
  {
    string[] roles =
      {
         "Admin",
         "User",
         "Local Office"
      };
    HttpContextHelper.SetCurrentContext(new FakePrincipal("Fake", "testuser", true, roles));
  }

  //[SuperAuthorize(SuperRoles = "!Guest")]
  //public ActionResult AboutTestOne()
  [TestMethod]
  public void AboutTestOne()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<RedirectToRouteResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutTestOne");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  //[SuperAuthorize(SuperRoles = "Admin & Local Office | Local Office Admin")]
  //public ActionResult AboutTestFive()
  [TestMethod]
  public void AboutTestFive()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<RedirectToRouteResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutTestFive");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  //[SuperAuthorize(SuperRoles = "!Guest & !(SuperUser | DaemonUser) & ((Admin & Local Office | Local Office Admin) & !User)")]
  //public ActionResult AboutCrazyTwo()
  [TestMethod]
  public void AboutCrazyTwo()
  {
    // Arrange
    ControllerContext context;
    var invoker = GetInvoker<HttpUnauthorizedResult>(out context);

    // Act
    var invokeResult = invoker.InvokeAction(context, "AboutCrazyTwo");

    // Assert
    Assert.IsTrue(invokeResult);
  }

  private FakeControllerActionInvoker<TExpectedResult> GetInvoker<TExpectedResult>(out ControllerContext context) where TExpectedResult : ActionResult
  {
    HomeController controller = new HomeController();
    var httpContext = new HttpContextWrapper(HttpContext.Current);
    context = new ControllerContext(httpContext, new RouteData(), controller);
    controller.ControllerContext = context;
    var invoker = new FakeControllerActionInvoker<TExpectedResult>();
    return invoker;
  }
}

All you have to do is download the code and plug in the SuperMvc project into your ASP.NET MVC web project and you too can have the power of parsed roles at your authorization attribute finger tips. Let me know if you like it or find an even better way to accomplish the same things.

SuperMvc.zip (281.93 KB)

Senior Enterprise Meetings Architect Wanted

We are looking for a very technical enterprise meetings architect for a large, well established organization in the Washington, DC area. You need to have extensive meetings orchestration experience and be an expert with PowerPoint-centric meetings architecture. You should also have some experience with multimedia animations playback. Advanced direct, teleconferencing and mixed-setting slide or teleprompter reading skills also desired.

A qualified candidate should be an expert in all aspects of the PowerPoint slide development process, including advanced transition and animated playback techniques. Candidates must possess dynamic monotonal verbal script delivery skills and be able to work well within large and sparsely attended meetings. Candidates must be able to translate business meeting requirements into technical meeting architectures and designs while leading a team of meeting engineers in the rapid development, testing and deployment of complex, content rich PowerPoint presentations.

Candidates must have a real passion for PowerPoint and be self-directed, confident and able to perform the task of expanding relatively simple content in thousands of pages of written documentation to accompany large slide decks packed with dense, monotonous text. Candidates should have a face and be able to articulate the written word clearly and in bold tones. Candidates should also be familiar with modern pointing devices such as laser pointers in addition to traditional uses of the stick and index finger to provide emphasis when presenting the finished meeting product.

Meetings Architect Specific Duties:

  • Mastery of building and maintaining enterprise meetings frameworks in response to business needs.
  • Mentor meetings development staff while implementing best practices and improving meetings design and development processes.
  • Work closely with business principals to understand enterprise meetings requirements.
  • Translate meeting requirements into workable meetings architectures.
  • Present tested, production ready meetings to executive staff for deployment in the field.
  • Accompany executive presenters in the field to provide advanced PowerPoint backup and support in critical presentation delivery scenarios.

Required Skills and Experience:

  • Ability to apply a broad array of skills and technologies to solve meeting presentation problems.
  • Ability to utilize PowerPoint, all versions, and Windows Paint and screen capture tools.
  • Ability to rapidly convert a one page outline or two minute conversation into a 60 slide presentation and 230 page accompanying notes and documentation handout.
  • BS in Library Science or English or equivalent technical training and professional work experience.
  • A minimum of 8+ year's cumulative experience developing enterprise meetings on the Microsoft PowerPoint platform and other technologies i.e. Windows Paint, etc.
  • Ability to troubleshoot and diagnosis complex PowerPoint problems.
  • Strong composition and obfuscation skills, as well as excessively verbose written and verbal communication skills.

Submit your resume today!

Visual Studio LightSwitch Beyond the Basics

Before you make up your mind about LightSwitch prior to beta release, watch the new video on Channel 9. Before you decide that LightSwitch is for non-developers, watch Joe Binder in this video extend a LightSwitch application with a Silverlight user control and a custom WCF RIA Service.

The key point, I believe, made in the video is that EVERY LightSwitch application is essentially a 3-tier application. The extension of the Data Access tier with WCF RIA Services makes it possible to extend those tiers into the enterprise infrastructure easily.

lsoverview

The demo also makes a very important point. When you write a real LightSwitch application, you will be writing code. While LightSwitch might be appealing to non-professional or hobbyist or business types, whoever uses it successfully will in fact end up writing code. Will they have to be an expert developer. Not if they have support from the enterprise pros that build the infrastructure for the business.

I still want to see and play with the beta before making up my mind, but what I’ve seen so far looks very promising.

Microsoft Visual Studio LightSwitch Unfairly Judged Before Beta Released

Two days ago, Microsoft unveiled Visual Studio LightSwitch. I heard about it first on Somasegar's blog and have followed the chatter and the growing list of blog posts and comments. I watched the Channel 9 preview video and the VS Live keynote video introducing LightSwitch. And then I watched them again making notes.

I'm deeply disappointed in a number of bloggers I regularly read and their many commenters that have parroted their sentiments. I won't name them here. Their negative reactions demonstrate an ill informed prejudice and predisposition to discount all 4GL tools without careful analysis and thoughtful evaluation.

Based on my careful notes of the demo videos and "official" blog posts about the tool, these bloggers and many commenters have made statements and critical judgments of LightSwitch that are demonstrably false or grossly inaccurate. And the first early beta is not even available yet. This rush to judgment ill becomes the professional stature and experience of these otherwise well respected members of the .NET development community.

From a certain point of view, I understand the nearly autonomic reaction of these .NET development community leaders. Professional developers have long dealt with the problems that so often plague solutions created by a host of desktop 4GL tools such as Access, FoxPro, FileMakerPro, PowerBuilder and many others. These tools have been highly successful in the business world seeking to just get something working that they could afford. In enough cases to be considered a plague by many professional developers, these solutions have far exceeded their limits as the business grew and ran into some of the hard and harsh limitations of these tools.

Many professional developers have been put into that crucibal of having to tell the business owner that their pet solution will not scale, has to be completely rewritten, and the effort will cost mega dollars to get a similar solution that will scale and grow with their business. The business owner doesn't want to spend the money, so he insists that the developer just make the 4GL solution work. Happy developers then fire their client. Needy and miserable developers then swallow their pride and spend more hours in frustration dealing with a 4GL too they come to hate more often because the solution wraps around a database that was designed by someone who thinks of dinner when you say the word table.

Scott Adams owes his fame and fortune in no small part to the advent of ill conceived 4GL tools and the more horribly designed solutions created with them by the pointy haired bosses who fancy themselves tech savvy.

So I understand the rush to judgment, but the facts are not there to support the negativity and biased ignorance I've seen in so many recent blog posts and comments.

Anyone can actually take the time to watch the videos and read the official blog posts and carefully consider what they have learned. Any professional presented with a tool for solving a problem that has never been satisfactorily solved in the past who automatically dismisses the latest attempt does himself and those who respect his opinion a disservice.

Here is what I've learned after reviewing the demostrations and taking detailed notes and carefully considering the possibilities without making invalid comparisons to the host of 4GL tools on the market today.

  • LightSwitch is NOT a 4GL in the traditional sense of closed source, desktop bound, proprietary database, with few if any extension points.
  • LightSwitch is a set of .NET assemblies and Visual Studio designers and project templates that produce a model based on XAML from which a Silverlight 4 and WCF RIA Services solution is generated.
  • LightSwitch is a .NET solution and can be extended in Visual Studio Pro (and up) with standard Silverlight control projects and server side support projects.
  • LightSwitch supports three data sources: SQL Server (and SQL Azure), Sharepoint 2010, and most importantly WCF RIA Services. In fact, SQL Server access in the 3-tier solution is done via WCF RIA Services and Entity Framework. I was not able to determine exactly how Sharepoint access is supported under the covers but would assume that the same solution is generated, with WCF RIA Services providing access to the Sharepoint list libraries and other Sharepoint data on the host server.
  • There is certainly an incoherent marketing message from Redmond on the subject of the target audience but it is clear that while marketing speak would have business buyers believe that they will be able to write applications without code, the fact is that some coding skill will be required to write even the simplest of applications in LightSwitch where commonly found business rules such as validations and computed values on existing data sets are required.

Based on what I've seen so far, it seems the sweet spot for LightSwitch might be the entry level developer or what one blogger called the "productivity developer" with professional support from senior developers and architects constructing back end systems, designing databases and providing safe and simple WCF RIA Services for the less experienced developer to consume to deliver line of business applications that may never need the skilled hands of the top notch developers.

I want to learn more about LightSwitch and see it and play with it before I make up my mind about its usefulness. I want to see how easy it is to extend and expand a LightSwitch application in Visual Studio Pro as promised but not demonstrated. I want to learn more about the extension points. And I want to see and perhaps participate in providing constructive and informed feedback. More importantly, I want to see what the Microsoft team does with that feedback.

Bottom line. It's far too soon to judge. Let's get the beta and provide Microsoft with some constructive feedback instead of the diatribes I've seen so much of in the last couple of days.

Add Reference Search with Visual Studio 2010 Pro Power Tools

My absolute favorite feature of Visual Studio 2010, so far, is the javascript Intellisense support via the <reference> tag. Add the following line to your .js file and you get jQuery Intellisense.

    /// <reference path="/scripts/jquery-1.4.1.js" />

My second favorite feature, so far, was just added with the Visual Studio 2010 Pro Power Tools just released by Microsoft the other day. It is the Add Reference Search feature. Behold…

addrefsrch

There are a bunch of very cool features added by this small but powerful extension pack, but not having to scroll through a list of assemblies to find the one I’m looking for is a godsend.

You can read about all the goodies on the download page, but two other honorable mentions are:

Ctrl+Click is now the equivalent of right click and selecting Go to Definition. Booyah!

Ctrl+Alt+] on a selected block of assignments will align the = operator making your code block far more readable.

I highly recommend this extension. Thanks Microsoft!

Google’s Folly

If you leave your door unlocked and someone enters your house for nefarious purposes, can you blame your lock manufacturer? Will you switch to a new brand of lock? Or if you open the door and pickup the the strange package you weren’t expecting from your doorstep, take it into your home and open it, do you sue the contractor or architect who built your house when it explodes? Do you declare your house to be unsafe and abandon it to live in a shed?

Well, it seems that if you’re Google, you do.

PC World reports today that Google has announced by leak that they will abandon Windows, blaming Microsoft for the Chinese invasion they suffered in January. Anyone with the slightest bit of brains knows this is an economic and political stunt and has nothing to do with security. The Trojan that Google claims allowed the Chinese hackers into their computers was, according to Symantec, entirely preventable.

Now, five months later we learn that rather than admitting the embarrassing fact that they either left the door unlocked (had un-patched machines) or invited the hackers in (opened attachments on vulnerable machines), Google is announcing that they will toss out their rival’s OS to spite their own face. Instead they will jump on the Linux for the Desktop and Mac OS bandwagon.

That’s fine. It’s a free country. But Google is just as big a target now as they were then and any honest security expert will tell you that Linux and Mac OS vulnerabilities exist and are ripe for exploitation. When Google is attacked again after having put its head in the sand, who will it blame then?

The bottom line is that you cannot blame your security failures on the lock manufacturer or the contractor who built your house if you’re not even willing to lock the door or question the anonymous package left at your doorstep. This is Google’s folly. They have opted for an effectively placed marketing jab against an opponent while leaving their left flank exposed for another Chinese hack attack. When it comes, will they blame the President of the United States or the Secretary General of the U.N.? Or will Google take responsibility for its own security?