Piecemeal Expression evaluation

One of the more interesting uses of Expressions is strongly-typed reflection.  It seems that most of the time dealing with expressions, I never care about ever actually evaluating the expression for any reason.  When all I'm doing is parsing and examining the expression, I'll never really need to evaluate the result.  But any expression can be compiled to a delegate, so you'll usually see code like this:

[Test]
public void Expression_example()
{
    Expression<Func<Customer, object>> expr = c => c.Name;

    var bob = new Customer {Name = "Bob"};

    Func<Customer, object> func = expr.Compile();

    var result = func(bob);

    result.ShouldEqual("Bob");
}

To create an expression, we need a lambda.  Unfortunately, the only way I've seen to create an Expression object is through the compiler.  In the above example, we create an expression that represents a Func<Customer, object>.  That is, the expression must be a lambda that expects a Customer and returns object.  This is the basis of most strongly-typed reflection schemes.  To actually execute the delegate behind the Expression, we call the Compile method, which returns a fully-functioning...function.

If you're interested in Reflection.Emit, I'd highly suggest popping open the code for System.Linq.Expressions.ExpressionCompiler in Reflector.  That's the bad boy responsible for turning our Expression into executable code. 

In the above test, the Compile() call returns a strongly-typed delegate; namely, Func<Customer, object>.  We get compile-time safety for calling the lambda, so we can't call it with something besides a Customer, for example.

But what if we want to compile something else besides the expression as a whole?  And why the heck would we want to in the first place?

Recently, I ran into a situation where I didn't care about evaluating the entire expression, just one part of it.  I wanted to have all of my HTML ID attributes in an ASP.NET MVC application generated from one place, so that both our front-end and our WatiN tests use the same mechanisms and EditModels to provide an iron-clad compile-safe manner of generating and using IDs (and NAMEs).  The interesting part came when I ran into arrays, where I had an EditModel looking something like this:

public class Customer
{
    public string Name { get; set; }
    public Address[] Addresses { get; set; }
}

public class Address
{
    public string Zip { get; set; }
}

In some form somewhere, a user could edit their list of addresses in one form.  To have all of the form model binding magic work correctly, I needed to take the array index into account, so that this expression:

HtmlIdGenerator.Generate<Customer>(c => c.Addresses[0].Zip);

Would generate a correct HTML NAME attribute, that included the index.  The end result looked something like "Addresses[0].Zip" for the NAME attribute value.

I was able to parse the Expression tree with no worries to get to the actual BinaryExpression that represented the ExpressionType.ArrayIndex expression type.  The problem I ran into was that the array index, in actual use, could be absolutely and anything that resolved to an integer.  This could be a constant value, like the above example, or a closure (where I pass in the array index in a loop), a method call, etc.  A strongly-typed Expression was nowhere to be found, as I had only the Expression type work with.  Its Compile method just returns Delegate, not a fancy Func<> or Action<>, or any other delegate type.

But it turned out not to matter, as Delegate has a DynamicInvoke, which allows me to pass in any parameters and returns any result as object.  With this in mind, I had my piecemeal Expression evaluation:

case ExpressionType.ArrayIndex:
    var binaryExpression = (BinaryExpression) visited;

    Expression indexExpression = binaryExpression.Right;
    Delegate indexAction = Expression.Lambda(indexExpression).Compile();
    int value = (int)indexAction.DynamicInvoke();

With the index value, I could now use that value in my HTML NAME/ID attribute value generator.  It didn't matter how the array index value was generated, as the Compile() method took care of all the details.  Closures, constants, methods, whatever.

No matter where I am in the Expression tree, I can always Compile() each Expression piece and evaluate it individually.  Any necessary parameters need to be passed in, but for cases like closures, it doesn't matter.  The closure already keeps track of any method parameters needed.  Neato.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Simplified MassTransit Configuration

One of the things I've missed since we integrated container support is the ability to quickly and easily create an instance of the ServiceBus. After Ayende agreed, I decided it was time to do something about it.

Behold the minimum amount of code necessary to create a service bus:

Picture 4.png

That's it. In fact, you can easily mock out the container with some nifty Rhino.Mocks usage:

Picture 5.png

I'm starting to convert the tests to use the mocked container approach to reduce the runtime of the tests. But so far the HeavyLoad, Starbucks and WinFormSample samples have been verified to work with the new model. The Windsor facility is also using the new model (Dru is going to update the other two tomorrow).

I'm pretty happy with the new configuration syntax, it certainly makes it easier to setup a bus with zero XML abuse. Look for more of this style of configuration/extension in MT in the near future.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Ten things to retire in 2009

This year, 2008, was a year that saw many a new term or expression get ingrained in the minds of us .NET developers.  Quite a few I'd rather not see in the next year, as they've overstayed their welcome.  Some are catch-phrases, some are misapplied concepts, and others fall into the "make my brain hurt" category.  Regardless of where they came from, here are ten .NET things I'd like to see make a graceful exit in the new year:

1) Open Spaces

I love me some open spaces, as I've had some great experiences with both the Austin ALT.NET Open Space and the recent KaizenConf open space.  But somewhere along the way, a great idea got usurped, strangled, mangled and mass-produced into some kind of buzz-word hippie-fest where we sit around in circles and sing kum-by-ya.  There's a book on the subject, yet, just like Agile, a non-agenda for a conference became associated with Open Spaces.  CowboyConf != Open Space.  What comes after FooBar Conf?  Wait, I know, it's ScheißenConf.

2) Any MS ORM

First was the EF Vote of No Confidence, then the realization that EF was worse than we thought it was, then a little LINQ2SQL love, then a sad realization that L2S was going away.  A popular, widely used, commercially supported ORM for .NET already exists.  It just doesn't come from the left coast.

3) Gloryhounds

Speaking of MS ORMs, has anyone else noticed the breeze blowing from all the hot air surrounding the new "experts" in the nascent technologies coming out of Redmond?  If it's not in Beta yet, you can't be an expert unless you're on the dev team.  Being an expert in a product doesn't mean you're an expert in the field, that's two entirely different purviews.  Any time a new acronym rears its ugly head, you can bet there are several book deals, speaking engagements, articles and consulting gigs lined up to take advantage of a yet-to-be-proven technology.  It would be amusing, if it didn't drown out the useful conversations.

4) LINQ 2 Your mom

LINQ query expressions (not just the extension method operators) opened a whole new world of internal DSLs for .NET developers.  Unfortunately, the compiler hooks to open up the "from...where...select" goodness were not made public, so the really interesting boo-like applications were left in the dark.  Instead, we get treated to weirdness like LINQ 2 Amazon and LINQ 2 WoW.  What was that Jurassic Park line?  "You were so preoccupied with whether or not you could, you didn't stop to you if you should."  Unless you really understand what the LINQ operators are doing under the covers, and what the underlying IQueryProvider object is doing underneath the covers, you're just creating a hot mess.

5) FooDD

We have enough acronyms driving our design.  DDD, TDD, BDD, SausageDD, let's call the whole thing off.  Unless you can define what these concepts/architectural styles describe, imply, infer in one volume, let's just not talk about it.   Underscores in a method name don't count as a sea change, paradigm shift, quantum leap or revolution.  The only caveat is if there is a Big Blue Book on the subject, which means it's a game changer.  Cherish that bible.

6) Feeding the trolls

Productive: (adj) Yielding favorable or useful results; constructive.  There are certain folks in our community that, when provoked, will actually respond to your inanity.  Do us all a favor, just shut up, and don't provoke.

7) Fluent interfaces

Yes, you found the magical mystical extension method!  It's a miracle!  Now put that hammer down, my face is not a nail.  Just like #4 in this list, we've taken a useful idea in internal DSLs, and fouled it up just like you knew we would.  You know what's a great DSL?  HTML.  If I have to have two dozen characters, parentheses, angle brackets and percent signs to create "<form>" tag, something went awry.  Clever is rarely simple, and unless that fluent baloney improves the situation, you're a glorified code-sturbater.

8) The BCS

Nothing to do with coding, except that computers help decide who is in the NCAAF championship, where millions of dollars are at stake.  One thing can be certain, Mizzou will never, ever vie for the title.  Ever.

Nor Texas Tech.

Just thought I'd throw it out there, as I know someone reading this has the pull to make it happen.

9) Fear

It's no coincidence that one of the XP values is Courage.  Though we pride ourselves in pushing the envelope and branching out, why are we the quickest to bash a new concept?  If you signed the EF VoNC without even looking at EF, you're subtracting, not adding.  Walk a bit in those other shoes before dismissing the framework, tool, concept or idea.  Courage is trying something new despite all your inclinations not to.  Think TFS is garbage?  Try it out.  Think SVN is for pinko FSF weirdos?  Give it a week.  Funny how the loudest protests come from those with the most ignorance.

10) Bold typeface in blog posts

One of my bigger pet peeves is anything in bold.  It's a cheap trick to grab attention, yet it always works.  Yes, Atwood does it all the time and although it grabs attention, it's the blogger equivalent of that dork that "quotes" "all" "his" "words".  The last thing we need is another cookie-cutter Atwood knockoff.

11) Top ten blog posters that can't count

The worst offenders of all are those morons that create top-ten lists to grab attention and readers, yet can't count.  Oh wait...



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
PHP 5.3 alpha3 released!

The PHP development team is proud to announce the third alpha release of the upcoming PHP 5.3.0 minor version update of PHP. Several new features have already been documented in the official documentation, others are listed on the wiki in preparation of getting documented. It is imperative that more people join the effort to complete the documentation for PHP 5.3.0. Please also review the NEWS file.THIS IS A DEVELOPMENT PREVIEW - DO NOT USE IT IN PRODUCTION!The purpose of this alpha release is to encourage users to not only actively participate in identifying bugs, but also in ensuring that all new features or necessary backwards compatibility breaks are noted in the documentation. Please report any findings to the QA mailinglist or the bug tracker.There have been a great number of other additions and improvements since the last alpha, but here is a short overview of the most important changes:Namespaces (documentation has been updated to the current state)Rounding behaviorext/msql has been removed, while ext/ereg will now raise E_DEPRECATED noticesext/mhash has been replaced by ext/hash but full BC is maintainedPHP now uses cc as the default compiler, instead of gccA number of bug fixes to ext/pdo, ext/soap, the stream layer among othersSeveral under the hood changes also require in depth testing with existing applications to ensure that any backwards compatibility breaks are minimized.The current release plan expects a stable release sometime around the end of Q1 2009.

Categories: Computers | PHP | PHP Hypertext Preprocessor | Programming | Technology
An Online Image Thumbnailer

Hey folks, I’ve published a small online image thumbnail utility. If it proves useful (without bogging down our servers), I’ll leave it up for public consumption. If you’re interested in reading a little more about it, you can find the story below. If you’d just like to see [...]

Categories: Agile Programming | Computer Humor | Computers | CSharp | Dot Net | Emerald Software Group | Humor | Onboarding | Patrick Caldwells Blog | PHP | Programming | Project Management | Service Oriented Architecture | SOA | SQL Server | Technology | Web Development | Web Services | Windows Programming
Writing Anonymous Methods with Lambda Expressions

I like using Lambda expressions for anonymous methods. I don’t really have a good reason for it, but I like it, so here’s the difference. Let’s say you have a class exposing the following delegate: public delegate bool CheckExpirationDelegate(); public CheckExpirationDelegate CheckExpiration; The normal anonymous delegate would look like this: di.CheckExpiration += delegate() { return true; }; But, [...]

Categories: Agile Programming | Computer Humor | Computers | CSharp | Dot Net | Emerald Software Group | Humor | Onboarding | Patrick Caldwells Blog | PHP | Programming | Project Management | Service Oriented Architecture | SOA | SQL Server | Technology | Web Development | Web Services | Windows Programming
Why we need named parameters

C# 4.0 brings the idea of named parameters to C#.  While optional/default arguments are of questionable value (this is from my VB.NET days), named parameters can really clear up the meaning of a method call.  We're already faking named parameters, as seen here in the ASP.NET MVC codebase:

return GenerateUrl(
    null /* routeName */, 
    actionName, 
    null /* controllerName */, 
    new RouteValueDictionary(valuesDictionary));

Obviously the above example isn't compile-time safe and comments lie to you, so it will be nice to be able to provide named parameters, especially when the number of arguments grows in a method call.  Something to look forward to.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
10 things to embrace in 2009

With 2008 behind us, what better way to kick off the new year than another cheesy top 10 list.  This time, with more bold!

Rather than focus on the negative, here are a few things I'd like to see continued and embraced in the year ahead.

1) Open spaces

Open spaces, coupled with targeted workshops, provided the best bang-for-your buck experience for technical conference this past year.  What started (in the .NET space) with 2007's ALT.NET Conference, continued with ALT.NET Seattle, spread to other cities, countries and continents, and taken to the next level with KaizenConf and workshop.  The quality of conversations at these events, before, during and after, in the sessions, in the hallways and continued at hotels and local dives and eateries, was top notch.  Open spaces encourage community growth through multiplication instead of addition, and I'm happy to see this format branch out more and more in the .NET community.

2) MS forays into ORM

A few years ago, ORMs were described as the "Vietnam of Computer Science".  It's an oft-misunderstood metaphor that still requires a read today.  However, as modern ORMs embraced the POxO (Plain Ol' Xxx Objects), much of the impedance mismatch problems disappeared.  I've used NHibernate on green-field, brown-field and mine-field applications, with NHibernate never missing a step.  ORMs are a viable and recommended data access strategy, but not every enterprise is ready (or able) to embrace OSS.  In these cases, MS technologies such as LINQ to SQL and the Entity Framework are valid options for teams tired of hand-rolling ADO.NET code.  Although each technology has its deficiencies (one so much so, I signed a Vote of No Confidence), the development teams are listening and incorporating feedback.  My sincere hope is that these technologies don't get reset or canceled, as we've seen with SQL Server Notification Services and Workflow Foundation.  However flawed it may be, efforts by MS to develop ORM technology are a step in the right direction.

3) OSS and MS

CodePlex.com is a site design, run and operated by Microsoft to host open source projects.  Several MS projects have made their way to at least open their source code (but not accept patches) onto CodePlex.  This again is a Good Thing.  I don't expect, nor will I ever care if MS open sources Windows or Office.  But it's encouraging to see DevDiv realizing the benefits of OSS.  I'm no FreeTard, nor do I see OSS leading society into some hippie magic love-land, but OSS can react more quickly to feedback than traditional closed-source software.  What I'd love to see is that one the first questions a new product team at MS asks itself is, "should we CodePlex this one?"  Just asking that question shows a huge shift in attitude.

4) LINQ query providers

Last year saw a big push to expand the LINQ providers to the major ORMs, including LLBLGen, NHibernate, and the MS offerings that included LINQ built-in (LINQ to SQL and the EF).  The way I see it, the more exposure LINQ query expressions get, the more we'll hear requests for the compiler hooks that made this magic possible made public.  While I'm not holding my breath, the increased attention on language-oriented programming and internal DSLs triggered an explosion of innovation.  The gut reaction to a powerful new tool is "how will it be abused".  Abuse is inevitable, but sharp tools drive innovation.  LINQ allows a terse querying syntax that's both easy to read, yet powerful.  You'll need to understand the basics of deferred execution and expressions to fully grasp the implications of the LINQ compiler magic, but once you do, many of the LINQ query operators (Where, SelectMany, etc) become quite elegant in LINQ.  But only if a LINQ query provider exists.

5) Expanding xDD ideas

DDD, BDD and TDD saw a big expansion into the .NET community in 2008.  For the first time that I can remember, MS products were designed with testability in mind.  Several of the MS products released on CodePlex also included unit tests.  In Rob Conery's excellent MVC Storefront series, Rob shares his journey in creating an awesome MVC application, using a wide variety of design principles and techniques.  BDD is starting to come on strong as well, with a BDD mailing list with folks from many communities (Ruby, .NET and Java) participating in the conversation.  Software development still has a long way to go to match the maturity of other engineering disciplines, but pushing better design, architecture and development practices will get our industry [BLARG]

6) Internal DSLs and Fluent Interfaces

The ease of parsing XML made it an easy choice for framework developers as a means to provide configuration.  As anyone that is familiar with Spring can attest, something went horribly awry.  As a programming language, XML stinks.  It's verbose, noisy, and stifling.  With extension methods, lambda expressions, and expression trees in C# 3.0, a lot of pieces were in place to support some quite powerful language-oriented programming.  Although we hit some bumps in the road (Fluent Interfaces aren't supposed to read like Tolstoy), some great internal DSLs in applications like Rhino Mocks and StructureMap show the potential of the C# language.  I'm personally looking forward to Fowler's DSL book, whose website already provides a great source of information on DSLs.  It's a testament to the power of these ideas to see how quickly they've taken hold.

7) Quitting while you're ahead...or behind

Top 10 lists are lame, even if they sprinkle in the bold.  Bogard out.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
HR-XML Integration in Human Resources Software

Most of the programming and architecture work I do is in the human resources space. I write software for paperless onboarding and acculturation, personell change management, background checks and verification services, new employee requisitioning, and the like. As you can imagine, I spend a great deal of time and effort integrating with human [...]

Categories: Agile Programming | Computer Humor | Computers | CSharp | Dot Net | Emerald Software Group | Humor | Onboarding | Patrick Caldwells Blog | PHP | Programming | Project Management | Service Oriented Architecture | SOA | SQL Server | Technology | Web Development | Web Services | Windows Programming
Article :: Accessing Your MySQL Database from the Web with PHP

In this chapter, learn how to access a database from the Web using PHP, read from and write to the database, and filter potentially troublesome input data.

Categories: Computers | InformIT | InformIT Web Development | Programming | Service Oriented Architecture | SOA | Technology | Web Development | Web Services
Kanban in Software Development. Part 2.5: A Variation on Queues - Pipelines for WIP and Done

In part 2 of my Kanban in Software Development series, I talked about completing a kanban board with queues, order points and limits. We saw how to take a complete development pipeline and work with a team, its processes and its bottlenecks. In the end, we had a kanban board that could easily represent the processes of the fictional team that we outlined.

One of the questions that I've often asked about a kanban board is how anyone would know when work in one column is done and ready to be pulled into the next column. For example - if a kanban card is sitting in the Analysis column, how does a developer know when that card is done so that they can pull it into Development and start coding it? I found the answer to this question when I was at the Kaizen Conference in October. Jef Newsom did a workshop on kanban and we ended up with this same question, and a solution.

A Pipeline for Analysis - WIP and Done

To facilitate the visualization of the difference between work in progress and work that is ready to be pulled to the next column, we can use the concept of a pipeline and split our existing queues into a WIP and Done step. For example, we want developers to pull work from the Analysis queue into the Development pipeline. We can show which cards are ready to move by splitting Analysis into sub-columns of WIP and Done.

image

When an Analyst is ready for work, they would pull from the Backlog into the Analysis / WIP column. When the analysis work is done and the card is ready to go into development, the card would be moved into the Analysis / Done column. Since we are wanting to maintain the concept of a queue for the overall Analysis column, we have create the WIP and Done subdivisions as a pipeline (noted by the dashed line). This allows us to keep our order point (3) and limit (5) in place for Analysis, and know what work is ready to be pulled into Development.

Applying Pipeline per Queue Across The Board

Not every queue needs to be a pipeline.

Consider the Backlog - the customer is placing the prioritized list of features in this column. The cards in this column exist so that the analysts will know what work needs to be done - not because any work needs to be done in this column, explicitly.

The Delivery column may not need a pipeline, either. If the delivery process is composed of sending an installer package to the customer, then there is no real work to be done in this column aside from sending that package. However, if there is some specific integration work (say, changing a web.config file) that needs to be done, we could include a WIP and Done pipeline for delivery. For this simple example, we'll say that there is no configuration change needed. Let's assume that the installation package changes all the needed configuration files based on user input.

With all of this in mind, we can apply our WIP and Done pipeline to the Analysis and Customer Acceptance columns.

image

Alternative Visualizations

There are other ways of visualizing WIP vs Done cards for a given column, of course. For example, you could forgo the pipeline idea and simply add a queue between Analysis and Development. This may require you to adjust your order points and limits between analysis and development - at least, where those order points and limits apply (Analysis vs. the queue between Analysis and Development). You could also split the column horizontally instead of vertically, creating either the top or bottom half as the WIP with the other being Done. Or you could just note the status on the kanban card itself. I'm sure there are a number of other ways to show this information, as well. The point is that the pipeline visualization that I'm showing here is not the only way. Find what works for you.

Where Do We Go From Here?

We have another tool in our belt, now. If need be, we can visualize the WIP vs work Done for a given queue, allowing us to see when we can pull work forward. But, like all tools in our belt, it is not *the* answer and this additional visualization may not be necessary for your team.

If your team is small or has great communication, you may not need any special distinctions to show work in progress vs work ready to be pulled. You could rely on the daily standup for people to report when they are done, or do it ad-hoc - when someone finished a card, they announce it to the team immediately. In a larger team, though, it may become necessary to have some visual distinction between work in progress and work completed for a given column.

Small teams might get away without it; larger teams might need it; its up to your team to decide. The key is not to apply these ideas as blanket rules that must be followed, but to allow the individual project and team to decide what is right for them. And as always, allow the process to change when it needs to. Always inspect, adapt and continuously improve.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
On Your Health and Your Career

People haven't really heard from me in a while, and there's a few reasons for it, but I'm about to talk about the major one.

Sometime around the Kaizen Open Space in Austin, just a little before actually, I stopped being able to look at my computer screen. On an average day, 5 to 10 minutes looking at the screen and I wanted to gouge my eyes out. I was getting severe headaches. I was extremely tired, or at least, my eyes felt like they were. I was irritable. My eyeballs itched. It sucked man.

So that meant very little computer time on most days. No twitter. No blogs reading or writing. No writing code. Basically I kept the time limited to email that I needed for work, and the bare minimum time in visual studio. Since I'm all manager-y now, I don't get to write a lot of code anyway, so that kind of just worked out. During that time a new WoW expansion came out, and trying to keep up with my friends was a chore, and most of the time I was online I was actually not looking at the screen. (Which is a shame, because Blizzard put a lot of work into it and it's very visually stunning.) When I did have to spend non-trivial time in the IDE, I just dealt with the pain.

So this has actually been happening off and on to me since late 2004. At one point I bought grocery-store reading glasses that seemed to help just so I could write code and get through the day. But the problem kept going away after a couple of weeks, and, me being me, I just let it go. But this time it was way worse than ever, and going on 2 months duration. I broke down and finally went to an optometrist (with much prodding from a close friend).

Now comes the part of the story where I start coming to grips with the ravages of time. Having spent all my life with perfect vision, I was unprepared for an eye test where I couldn't read the bottom two lines of the chart. The tech actually got impatient with me because I stubbornly sat there trying to will my eyes to focus on those letters, but it didn't happen. Long story short: I had somehow gone from perfect vision to nearsighted, farsighted, and a slight astigmatism. Were I the designer of the human body, nearsighted and farsighted would cancel to an acceptable middle state. Anyway, I now am bespectacled at all times except when sleeping. Advancing age and upwards of 15 hours of computer time per day were to blame said the doctor man, and so my glasses also have some special whosamawhatsit on the lenses specifically for computer work.

Were it not for the fact that I need the computer to live I might have been content to let this eye thing go until they got fed up and leapt to their deaths leaving me with gaping sockets. But now, well, last week I paired all day 2 days in a row and was ready for more. And the headaches are gone. And I don't feel tired anymore (not from sitting around on the computer anyway). And while I'm still not completely adjusted to them (my eyes are still pretty fatigued by the end of the day), I know the glasses are helping. And I'm kicking myself in the ass for ignoring the problem for so long.

Your health affects your livelihood brothers and sisters of the sedentary knowledge-worker persuasion. I know when I put on a few pounds it's reflected in my productivity and I can guess what the scale will say by my average level of energy change over the course of a few days. And when I'm not getting enough exercise my mood is unpredictable, my irritability and anxiety are high, my posture suffers and my time at the keyboard becomes physically painful. And when I eat poorly for a few days my code quality measurably suffers. And when my eyes don't work, well, I'm not good for anything at all.

So, in this upcoming time of annual stock-taking and resolution-making, this is my reminder to you and me that your health matters, and your productivity as coders and managers and members of society is very closely linked to your physical well-being, so keep it in mind. And stop pretending you aren't getting older, and make those doctor appointments to keep things in order. You are the most legacy system you'll ever work with, so you need to take extra care to keep it performing optimally.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Article :: Working Within the Adobe Dreamweaver CS4 Environment

Get to know the Dreamweaver authoring environment so you can be more effective and efficient as you create Web pages and manage Web sites.

Categories: Computers | InformIT | InformIT Web Development | Programming | Service Oriented Architecture | SOA | Technology | Web Development | Web Services
Making frameworks container-aware

I'm currently knee-deep in NHibernate custom listeners, for the purpose of adding auditing to our application.  Besides current documentation being plain wrong on the subject (I'll update on the solution in the future), I hit a rather frustrating snag around the instantiation of my custom listener.  One of the shouldn't-be-frustrating-but-yet-it-is side-effects of committing fully to Dependency Injection and Inversion of Control Containers is all the code out there with "extension" points that don't allow custom factory implementations.  Sure, your framework allows for custom Floogle providers.  But how does it create the IFloogleProvider implementations?

In the NHibernate code, I found this snippet that instantiates custom listeners, which are configured through an XML configuration file:

public void SetListeners(ListenerType type, string[] listenerClasses)
{
    if (listenerClasses == null || listenerClasses.Length == 0)
    {
        ClearListeners(type);
    }
    else
    {
        var listeners = (object[]) Array.CreateInstance(eventListeners.GetListenerClassFor(type), listenerClasses.Length);
        for (int i = 0; i < listeners.Length; i++)
        {
            try
            {
                listeners = Activator.CreateInstance(ReflectHelper.ClassForName(listenerClasses));
            }
            catch (Exception e)
            {
                throw new MappingException(
                    "Unable to instantiate specified event (" + type + ") listener class: " + listenerClasses, e);
            }
        }
        SetListeners(type, listeners);
    }
}

One. glaring. problem.  It uses Activator.CreateInstance to create the instance, which internally calls the default constructor.  As a developer for custom listeners, this means that we need to define a no-argument constructor:

public class AuditPreInsertUpdateEventListener : IPreUpdateEventListener, IPreInsertEventListener
{
    private readonly IUserSession _userSession;

    public AuditPreInsertUpdateEventListener(IUserSession userSession)
    {
        _userSession = userSession;
    }

    public AuditPreInsertUpdateEventListener()
        : this(ObjectFactory.GetInstance<IUserSession>())
    {
    }

When doing constructor injection, you normally don't create this constructor.  Frameworks like ASP.NET MVC, WCF and others provide hooks for custom factories or instance providers.  Containers receive a request to instantiate a component, and the container will create the dependencies, call the right constructor and pass those dependencies in.

From a developer's perspective, it's very helpful not to have to define any unnecessary no-arg constructors, as it muddies code.  There is at least one solution out there, such as the Common Service Locator project.  Now, NHibernate does allow programmatic configuration, so I do have the option to create the instances myself and pump them into NHibernate.  All I've really done is eliminated the possibility of using XML configuration, which isn't too fun if you're doing things like XML manipulation as part of your deployments.

For framework developers, something like Activator.CreateInstance should be a red flag, that maybe we should provide alternate means of instantiation.  As IoC containers become more mainstream, I think we'll see more changes in major frameworks to support containers out-of-the-box.  Until then, pointless dual constructors it is.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Providing both Authentication and Anonymity

I was reading a little tgdaily today and I found an article about a new iPhone app that may be showing up in the app store in the near future. The new application is called Trapster and it’s a “social-networking speed trap warning website.” I know what you’re asking. Well, I don’t actually know [...]

Categories: Agile Programming | Computer Humor | Computers | CSharp | Dot Net | Emerald Software Group | Humor | Onboarding | Patrick Caldwells Blog | PHP | Programming | Project Management | Service Oriented Architecture | SOA | SQL Server | Technology | Web Development | Web Services | Windows Programming
PHP Advent 2008

December is a busy and exciting time of the year. PHP Advent is an attempt to capture and share doses of wisdom from a few of the people in the PHP community who have been kind enough to share their thoughts and tips. Please join us on our daily journey by subscribing to our feed or following us on Twitter. Happy holidays.

Categories: Computers | PHP | PHP Hypertext Preprocessor | Programming | Technology
Shortening The Feedback Loop

Thank you everyone who attended our presentation last night at the Calgary Agile Methodologies User Group. We had a tonne of fun, and hope that you took away some valuable information.

CAMUG eComplianceCAMUG eCompliance   CAMUG eCompliance



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology