.NET Task Factory and Dangers of Iteration

I had a simple small array of objects. I wanted to send each of them into a method that would fire off and manage a long running process on each of them in a new thread pool thread.

So I remebered the coolness of the new .NET 4.0 Task and it's attendant Factory. Seemed simple enough but I quickly learned a lesson I should have already known.

I've illustrated in code my first two failures and the loop that finally got it right. Let me know what you think. Undoubtedly there is even a better way.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TaskFactoryExample
{
  public class ServerManager
  {
    IServerLib[] serverLibs;
    List<Task> taskList = new List<Task>();
    List<CancellationTokenSource> cancelTokens = new List<CancellationTokenSource>();

    public ServerManager(IServerLib[] servers)
    {
      serverLibs = servers;
    }

    // FIRST FAIL: only the last lib in the iteration gets sent to all ManageStart calls
    internal void Start_FirstFailed(string[] args)
    {
      foreach (var lib in serverLibs)
      {
        var tokenSource = new CancellationTokenSource();
        taskList.Add(Task.Factory.StartNew(() => { ManageStart(lib, args); }, tokenSource.Token));
        cancelTokens.Add(tokenSource);
      }
    }

    // SECOND FAIL: i is incremented finally to serverLibs.Length before ManageStart is called
	// resulting in an index out of range exception
    internal void Start_SecondFailed(string[] args)
    {
      for (int i = 0; i < serverLibs.Length; i++)
      {
        var tokenSource = new CancellationTokenSource();
        taskList.Add(Task.Factory.StartNew(() => { ManageStart(serverLibs[i], args); }, tokenSource.Token));
        cancelTokens.Add(tokenSource);
      }
    }

    // finally got it right - get a local reference to the item in the array so ManageStart 
    // is fed the correct serverLib object
    internal void Start(string[] args)
    {
      for (int i = 0; i < serverLibs.Length; i++ )
      {
        var serverLib = serverLibs[i];
        var tokenSource = new CancellationTokenSource();
        taskList.Add(Task.Factory.StartNew(() => { ManageStart(serverLib, args); }, tokenSource.Token));
        cancelTokens.Add(tokenSource);
      }
    }

    private void ManageStart(IServerLib lib, string[] args)
    {
      try
      {
        //code redacted for brevity
        //start long running or ongoing process with lib on threadpool thread
        lib.Start();
      }
      catch (Exception e)
      {
        //TODO: log general exception catcher
        throw; //leave in for testing
      }
    }

    internal void Stop()
    {
      try
      {
        foreach (var lib in serverLibs) lib.Stop();
        foreach (var tokenSource in cancelTokens) tokenSource.Cancel();
        foreach (var t in taskList) if (t.IsCompleted) t.Dispose();
      }
      catch (Exception e)
      {
        //TODO: log general exception catcher
        throw; //leave in for testing
      }
    }
  }
}

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!