We use Windsor as our IoC container.  Currently we use xml as the method by which components are registered.  Having done both, I prefer the xml mapping to code registration because I can change something in the app on the fly if I need to. I know some of you out there will disagree with me on this but that's ok.

One of the annoyances with xml is that you have to type the namespaces and classes along with assembly names.  We've found there is friction when we refactor our classes, changing names, moving classes,  and adding namespaces in that Windsor bombs.  When using the xml for configuration you don't get compile time checking, so a successful build may not mean working code, which in my opinion is bad.

We've simply added the following test to our unit-test project.  It still doesn't fail when compiling, but fails instead when we run unit-tests, which is closer to compilation than run-time.

   1: [Test]
   2: public void Can_initiate_Windsor()
   3: {
   4:     IWindsorContainer container = new WindsorContainer("windsor.config.xml");
   5: }

That's it!  It's very straight forward because all it's trying to do is start up windsor, the same way your application would, any exception that is thrown fails the tests, which causes the build to fail.


 
Categories: Tips & Tricks

Just ran into this and wanted to share with everyone.  I have NCover integrated into our continuous integration server.  I use it for informational purposes only.  In other words the build does not fail if coverage drops below a certain percentage.  A recent forced password change caused the CruiseControl.NET service to stop working as it was running under my account.  The reason it was running under my account is that I'm an admin on that machine and NCover.Console.exe requires admin privileges to run.  If you don't run under an admin account, the build server will work fine until it tries to run ncover, and then you get a deceptive error that can lead you to start looking in all the wrong places:

At least one test failed under code coverage.\r\nExternal Program Failed: c:\dev\ccnet\Website\build\tools\ncover\ncover.console.exe (return code was 1)

So rather than tying the service to my account I've gone ahead and created another account with admin privileges which is set to never have the password expire.  I don't like having the CruiseControl.NET service running off an admin account, but as far as I can tell it's the only way to get NCover to work.


 
Categories: Tips & Tricks

Have you ever been traveling through the "internets" and have been presented with the following?

image

image

As web developers we know what this means; a form was posted to the page and now you're trying to refresh that same page.  I'm not sure if there's been any significant usability study on the subject but I would imagine my Grandmother wouldn't know what to do here.  Enter the PRG pattern.

What is the PRG Pattern?

While the PRG pattern isn't knew, there isn't much out there on it for the .NET community.  PRG stands for "Post/Redirect/Get", I'll let Wikipedia explain the rest:

instead of returning an HTML page directly, the POST operation returns a redirection command (using the HTTP 303 response code (sometimes 302) together with the HTTP "Location" response header), instructing the browser to load a different page using an HTTP GET request. The result page can then safely be bookmarked or reloaded without unexpected side effects.

While this could be accomplished in webforms, it would be much more difficult since the postback model hangs on pages posting to themselves to implement button clicks and the like.  The MVC Framework on the other hand makes the implementation of the PRG pattern extremely easy. 

But How?  Can I See an Example?

I'm going to use an Login function as an example.  If the login attempt is successful, the user should be redirected to their account page, otherwise they should be redirected back to the login page.

image

We first will need two actions, one for displaying the login view and one for processing the login attempt, which I've provided below:

   1: /// <summary>
   2: /// Displays the login view (the form to enter credentials)
   3: /// </summary>
   4: public ActionResult Login()
   5: {
   6:     return View("Login");
   7: }
   8:  
   9: /// <summary>
  10: /// Handles form data from the login view, in other words, the form, which
  11: /// is on "login.aspx" has a form tag with it's action set to "ProcessLogin",
  12: /// the name of this method.
  13: /// </summary>
  14: public ActionResult ProcessLogin(string email, string password)
  15: {
  16:     IUser user = userRepository.GetByEmail(email);
  17:  
  18:     if (user != null && authenticator.VerifyAccount(user, password))
  19:     {
  20:         authenticator.SignIn(user);
  21:  
  22:         return RedirectToAction("Index", "Account");
  23:     }   
  24:     
  25:     //login failed
  26:     // add some message here in TempData to tell the user the login failed
  27:     return RedirectToAction("Login");
  28: }
Notice the different return types in the both of the methods.  Login() has one exit point, "return View("Login")"  and ProcessLogin has two exit points both of which use RedirectToAction() call, which instead returns an objected of RedirectToRouteResult, a subclass of ViewResult.  To properly perform PRG you must return a redirecting ViewResult from your action, such as RedirectToRouteResult, otherwise you'll get the dialog box pictured above.
 
Here is the login view (login.aspx).  The important part to pay attention to is the "action" attribute.
 
   1: <form name="loginActionForm" method="post" action="ProcessLogin" id="loginActionForm">
   2:    <fieldset class="login">
   3:        <legend>Login</legend>
   4:        <label for="email">Email</label>
   5:        <input type="textbox" id="lemail" name="email" maxlength="100" value="" class="required" />
   6:        <label for="password">Password</label>
   7:        <input type="password" id="lpassword" name="password" maxlength="256" class="required" />
   8:        
   9:        <input type="image" src="<%= AppHelper.ImageUrl("btn_go.gif") %>" class="submit" />
  10:        <div class="errorlist"></div>
  11:    </fieldset>
  12: </form>

By implementing the PRG pattern, I get nice clean urls that are bookmarkable.  My users also get a nice site that is traversable and aren't presented with confusing security dialog messages


 
Categories: MVC | Tips & Tricks

I like Twitter.  Unfortunately every day when I log into I never know what I'm going to get.  This is what I see about 50% of the time:

  image

At first I thought it was something wrong with Twitter, which is not all that crazy given their impeccable service record *grin*.  After a closer look with Firebug it's clear that the problem is on my end.

image

403 errors on the CSS files and jquery pretty much assure that my user experience is going to be pretty minimal.

Looking at request for screen.css we can see that the website, in this case a stylesheet resource, was blocked.

image

This is an error that I'm very familiar with.  When I try to visit anything on Jason Bock's site I'm greeted with:

image

The same thing is happening with some of the backing files to the twitter site, they are being blocked.

So how can you get around this?  Well Firebug allows you to edit the rendered html directly.  I've found that for some reason anything from assets1.twitter.com is blocked, but anything from assets2.twitter.com or assets0.twitter.com is not.

To get twitter to work, all I had to do was change the html:

image

Immediately after changing the URL for the css file, firebug goes off an fetches the unblocked css file and applies it's rules, making the page look correct.  Doing the same thing for the js files, behavior is once again in tact and my twitter looks normal.  I'm thinking if anyone out there has any experience with GreaseMonkey (firefox plugin) you could school me real quick on how to do this automatially.

image


 
Categories: Tips & Tricks

August 19, 2008
@ 02:13 PM

Here's a conversation I just had with another developer who is struggling to get his team to adopt some agile practices:

developer: if you were starting from scratch, which would you think is more important to setup first? CI or a unit testing process?
me: unit testing
developer: wow
developer:  ok
me: why is that surprising?
developer: i look at the mess i'm in everyday and i'd think getting a good build system in place would be first...
me: I think unit testing provides more value in that it allows you to add features knowing you haven't broken other features
developer: testing above a development process?
me: yes
me: testing provides more customer value

Let me be clear in stating that I think both are great value and a necessity, however the challenge was to choose one, presumably the most important.  I chose unit testing because one of the reasons I enjoy writing software that meets someone's needs.  As a developer one of the most nervous moments is when your code is released into the wild.  Will it work?  Will users they use it how you intended?  As a developer one of the most satisfying experiences is watching a user fire up a program you've written and it works flawlessly.  I think most customers would agree with that as well.  Having code that works is what they want.  Having code that works builds their confidence in you and reassures them that know what you're doing.  Testing provides this for me.  In advance I can test different scenarios and program that in and put my program through it's paces.

Now let me speak a bit about CI.  While I believe that testing is a component of CI, the developer in this instance meant a build server that kicks off automated builds.  While an automated build is nice, it doesn't nearly provide the value that unit testing does.  It's the things your build server does that increases it's value.  One of those things in our build system is running automated tests.  If you remove automated tests from a build server all you have is a dummy machine that compiles code.  That provides some benefit, but minimally.  You can replicate the behavior simply by updating your code often and doing a compile on your own machine.

As an agile developer I seek deliver value to stakeholders.  When viewed through that lens, I think unit testing clearly wins.

What about you?  Would you test before build server?  Or would you choose the build server?  Why?


 
Categories: Agile | Musings

When I first graduated from college I worked on embedded systems where the process was a formal, military grade process.  When developing software I typically thought about what document I had to write next and what document(s) I may be missing.  In general, the MIL standards turned me off a bit to process, and for awhile left me thinking that process is an obstruction to true development.  As a 21 year old, you think code = development.  That was/is an immature point of view, but it was not a viewpoint that I was easily dissuaded from.  Further it's a point of view that many out there still hold dear, and not all who hold that view are recent college graduates.

Recently a small group of us decided to give Scrum a try and are using it to drive our current project.  Other than this effort, there is no formal process methodology in place.  My goal is to help change that in my new position.  Over the past several years many high value projects have never been worked on because there was no common backlog of all of the things that need to be done.

In my last job at Geonetric we adopted Scrum after the absence of a formal methodology and it provided a much needed framework around which to develop.  Many CEO's are not this up front with their deficiencies, but Eric is pretty awesome and very honest in his evaluation of Geonetric:

As we were in the middle of developing the newest version of our VitalSite product last fall, we weren’t making the progress we wanted-even though the whole team was running full tilt and putting in its best efforts. We had always been a bit informal about how we developed software-somewhere between draconian rigid requirements and completely freeform cowboy (and cowgirl!) coding practices. The problem was that being in the middle wasn’t working. So, we looked at some of the newest practices in the industry.

Eric goes on to list the benefits he's seen since adopting Scrum:

  • Since adopting Scrum, the first two releases of VitalSite 5 have been on-target, meeting both scope and deadline requirements (5.0 in January and 5.1 in May).
  • Software development is accelerating each sprint - we’re approaching twice the speed we had last year.
  • There’s much more collaboration between disciplines
  • The morale of the software team is higher
  • Quality of the software we’re delivering is better

With results like that I can see why a CEO would like scrum.  As developer though, I like scrum in that it doesn't get in my way.  There is administrative overhead to Scrum to be sure.  However it's very "XP" in that there aren't scads of documentation to write.  Generally as a software professional I like to write code and solve problems and for the most part Scrum allows me to do that.  My development does not feel slowed down by Scrum, which I believe for most developers, is a must in order to be adopted willingly.

One side effect of scrum is that is causes me to think about the process in a pleasant way.  This morning at our standup meeting, a fellow developer and I got into a discussion about how his extra exploratory work in the evenings should be factored into our sprint.  Should we could his work towards our sprint commitment?  Will his work negatively/positively affect our velocity for future sprints?  From my experience, developers typically don't worry about this stuff however with Scrum the sprint commitment is something that should be taken seriously.  As such it was good to see developers, of which I was one, having talks about other things that just the code.

I'm sure many other processes out there could achieve the same thing.  Scrum for us, both in this job and the previous, provided a nice framework that was palatable to developers. In that respect I'm perfectly happy using Scrum.  I will keep my ears open for new ideas and processes, but I think for any development methodology to be successful in an organization, it has to be readily and whole-heartedly adopted.  We've enjoyed Scrum so far and as such, it's a not-so-bad development methodology.  If you aren't using a methodology or your current process isn't working, you should give Scrum a try.


 
Categories: Agile | Scrum

image I'm not a fan of the codebehind and designer files that are generated when you create a new ViewPage.  I like a clean solution and for me that means view files (.aspx) that don't have plusses next to them (see the photo to the right and compare the Home and Login folders).

If you want to use strongly typed view data and you don't want to add the codebehind and designer files for the measly few characters you have to type to make a view strongly typed:

   1: public partial class Index : ViewPage<LoginData>
   2: {
   3: }

In this particular case I have to add two extra files to source control solely for the purpose of having "<LoginData>"...seems like a waste.

CLR Notation

If you want to do the same thing without the extra overhead of two files, simply use CLR notation.  The old inherits attribute:

   1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
   2:     CodeBehind="Index.aspx.cs" 
   3:     Inherits="JPCycles.MVC.Web.Views.Home.Index" %>

becomes

   1: <%@ Page Language="C#"
   2:     MasterPageFile="~/Views/Shared/Site.Master" 
   3:     Inherits="System.Web.Mvc.ViewPage`1[[JPCycles.MVC.Web.Models.LoginData, JPCycles.MVC.Web]]" %>

Not the prettiest code I've ever seen, but it gets the job done without extra (needless) files.


 
Categories:

image I'm not a fan of the codebehind and designer files that are generated when you create a new ViewPage.  I like a clean solution and for me that means view files (.aspx) that don't have plusses next to them (see the photo to the right and compare the Home and Login folders).

If you want to use strongly typed view data and you don't want to add the codebehind and designer files for the measly few characters you have to type to make a view strongly typed:

   1: public partial class Index : ViewPage<LoginData>
   2: {
   3: }

In this particular case I have to add two extra files to source control solely for the purpose of having "<LoginData>"...seems like a waste.

CLR Notation

If you want to do the same thing without the extra overhead of two files, simple use CLR notation

   1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
   2:     CodeBehind="Index.aspx.cs" 
   3:     Inherits="ABCCompany.MVC.Web.Views.Home.Index" %>

becomes

   1: <%@ Page Language="C#"
   2:     MasterPageFile="~/Views/Shared/Site.Master" 
   3:     Inherits="System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]" %>

Not the prettiest code I've ever seen, but it gets the job done without extra (needless) files.


 
Categories: MVC | Tips & Tricks

August 11, 2008
@ 12:14 PM

image We're all familiar with the Aesop's fable of the tortoise and the hare.  In the story, the hare, who is in every way is faster than the tortoise, loses a race to the tortoise.  The main principle of the story is that slow and steady wins the race.

In my development I am shooting to be a tortoise, really I am.  Read on and let me explain.

A few weeks ago I got some evil glares when I suggested at our .NET user group meeting that in enterprise systems that you don't have time not to test.  It's a common hurdle for those new to testing to say, "I don't have time to write tests."  Let's face it, we're all busy, that excuse is tired.  As an agile and lean practitioner I seek out ways to improve velocity and reduce waste, not take my already busy schedule and cram in another tool for the sake of another tool.  While writing tests does slow me down, it brings on tortoise like speed, which I would argue is a good thing.  Writing unit tests is one tool that provide me the ability to keep a more consistent velocity over the course of development.  Without tests I can surely write things faster, the problem arises as the codebase grows and each new feature or fix takes increasingly more time. Eventually, even simple requests become arduous to implement.  Slowly you see your velocity come to a crawl.

It's an insidious cycle that I've seen before and am currently in the throes of; an application is built from scratch implementing everything the business requires. The application is enhanced and bolted on to, until you realize that you could move much faster if you could start from scratch.  You make pleas to your boss and explain how much productivity would improve if you could shed the hideous code base.  One day he gives in, you rejoice and you make the leap, start from scratch, breathing a sigh of relief at how easy implementing the features are all the while reminiscing about the old framework and how poorly it was written.  And now that the application is rewritten from scratch the cycle, unless you were aware of it all the while, starts again.

You see, no one sets out to write crap code.  People do the best they can with the knowledge they have.  Code, following the second law of thermodynamics, tends towards chaos over time.  With unit tests in place I can refactor with more confidence and implement new features without the fear of breaking existing code.  If you have the ability to refactor, new code is no longer "bolted on" but rather "grafted in" becoming part of the system.  With a solid framework with tests in place you can much better stop the cycle of rewrites.  Quickly writing applications that degrade is the way of the hare.  Developing purposefully using unit tests causes me to be slow in the short run, but over the life of the application comes out far ahead.  In that way, I strive to be the tortoise.


 
Categories: Agile | Musings

August 10, 2008
@ 09:36 PM

After talking a bit with Sergio Pereira I have decided to seize the opportunity and join the great bloggers at devlicio.us.  Given the challenge to blog alongside great bloggers, and believe me it's a challenge to put out content that matches the quality of the other devlicious bloggers, I decided it would be good to push myself a bit.  If you've followed this blog over the past few months I've been putting a bit more focus and time into the blog space and getting my thoughts/experiences down here.  The decision to blog for devlicio.us is a challenge to myself to put even more focus into my writing and blog posts.

If you're curious what will happen to this blog, fear not.  For the time being this blog will stay right here and most content will get published to both places.  I would encourage you though to subscribe to the main devlicio.us feed as the content they put is of the highest quality.

If you want to follow me at devlicio.us check me out at http://devlicio.us/blogs/tim_barcz/


 
Categories:

August 6, 2008
@ 01:03 PM

Going through old catalogs we came across the following picture.  Let's play the game, "caption this photo".

leatherjacket


 
Categories: OT

As the CRIneta president for 2008 I'm lucky to be joined by other developers on the leadership team who care about our community.  After a great meeting last night with guest speaker Jason Bock a few of us went out for some drinks.  While we were discussing topics and ideas for the future we realized we need to better understand our membership in order to plan speakers/topics.  We have developers who work in large shops, some in small.  Some developers work solely for the web while others only in windows.  Some developers are working in the 1.1 framework while others are pushing the envelope with 3.5 and the MVC Framework.

With all the different types of developers, we thought it would be beneficial to learn about our membership in hopes to provide relevant content to our users.  Using SurveyMonkey.com we've put together a short survey that asks the members questions in hopes to find out the following basic information

  • How long you've been developing in .Net?
  • What language(s) you use?
  • Which frameworks you develop on?
  • Do you use source control? If so which one?
  • Do you use a build server?  If so which one?
  • Do you unit test?
  • Do you mock?
  • What software methodology do you use?

See any topics we've missed?

Has your user group ever done something like this?  Did it provide the results you were hoping it would?

The way I look at it, even if the results are all over the board and don't help us narrow down topics/speakers, it will be good to get a handle on where the group is at.  For that, I'm excited.


 
Categories: CRIneta

imageI have what I believe to be a fairly simple problem in theory, yet in reality it proves to be a bit more hairy.  Below I present the problem and the requirements as I see them as well as a few possible solutions.  The solution I've settled on may or may not be correct, so I'm tossing out here to see what you guys think.  By all means please post some feedback.

Problem

To have a common, consistent logging access across multiple assemblies (that I own) in an application.

Requirements

  • I want to be able to have logging capabilities in any method of any class in my application.
  • I want to define logging once and only once for my application. 
  • I want to maintain testability by not having any unnecessary dependencies or unmockable objects. 
  • I want as few assemblies to be aware of dependencies as possible.
  • If at all possible I wanted to avoid having all of my classes have an external dependency on some interface (such as ILog)
    • I also want to avoid every class having a public property which exposes an ILog (for setter injection)

The Structure

To the right is a picture of the assembly dependency diagram.

Solution #1

I could use Windsor's logging facility as suggested by Casey Charlton except that the solution provided only seemingly works for my top level assembly, ABCCompany.MVC.Web.  I don't want my other assemblies to be aware that I'm using an IoC Container.  I especially don't want the assemblies to know I'm bound to a particular IoC container (in this case I'm using Castle's Windsor container).  I've emailed Casey about this and we are going to try to talk this through.  I'm interested to hear what his thoughts are given that on Castle's site it says about the logging facility (emphasis mine):

The logging facility provides a seamless way to add logging capabilities to your application. There are two levels of integration.

  • Allow your classes to receive an ILogger instance for logging support
  • Allow you to ask for an ILoggerFactory instance to provide logging support to classes that are not managed by Windsor.

While I wait to talk with Casey I have to discount this solution since I cannot see past the first assembly on how this would work and therefore cannot use this as my solution of choice.

Solution #2

This is what I've come up with so far.  Please comment if you see issues. 

I have set up a static class inside of the ABCCompany.Framework assembly from which all methods could call for Logging purposes.  This satisfies the requirements above which states that I do not want constructor dependencies nor public setters on all classes.  This solution however does mean that every assembly much also ship with the ABCCompany.Framework assembly and all of it's dependent assemblies.  I'm okay with this until I hear a reason that this is bad.  I view this much like when I do work with Castle that in order to get any behavior I have to bring Castle.Core along to the party.

I liked Casey's solution (Solution #1) except that I cannot see past it working in one and only one assembly.  I thought I could modify his solution by simply having a static class, which any assembly can reference and call.  By default the Logger would be set up with a NullLogger.  The Logging class would have a method available to change the underlying logger.  It would then be incumbent upon the application layer to change the logger if they actually wanted logging.  In my app this is the first thing that happens, the NullLogger is replaced by an actual logger by calling Log.SetLogger().

As you can see from the code below I've followed much of Casey's example.

   1: private static ILogger logger;
   2:  
   3: public static ILogger Logger
   4: {
   5:     get
   6:     {
   7:         if (logger == null)
   8:         {
   9:             logger = NullLogger.Instance;
  10:         }
  11:         return logger;
  12:     }
  13: }
  14:  
  15: public static void SetLogger(ILogger value)
  16: {
  17:     logger = value;
  18: }

I do have a dependency on the Castle.Core assembly (due to usage of types in Castle.Core.Logging).  However none of the classes using the Log static class have to reference anything to do with Castle since I've have methods which pass through to every method in ILogger (see example below):

   1: public static void Debug(string message)
   2: {
   3:     Logger.Debug(message);
   4: }
   5:  
   6: public static void Debug(string message, Exception exception)
   7: {
   8:     Logger.Debug(message,exception);
   9: }
  10:  
  11: public static void Debug(string format, params object[] args)
  12: {
  13:     Logger.Debug(format, args);
  14: }
  15:  
  16: public static void DebugFormat(string format, params object[] args)
  17: {
  18:     Logger.DebugFormat(format, args);
  19: }
  20:  
  21: public static void DebugFormat(Exception exception, string format, params object[] args)
  22: {
  23:     Logger.DebugFormat(exception,format, args);
  24: }
  25:  
  26: public static void DebugFormat(IFormatProvider formatProvider, string format, params object[] args)
  27: {
  28:     Logger.DebugFormat(formatProvider, format, args);
  29: }
  30:  
  31: public static void DebugFormat(Exception exception, IFormatProvider formatProvider, string format, params object[] args)
  32: {
  33:     Logger.DebugFormat(exception, formatProvider, format, args);
  34: }

The usage pattern becomes quite simple in that any class that references ABCCompany.Framework can use the ABCCompany.Framework.Logging.Log class.  No external references needs

The reason I chose to bind myself at the framework level to Castle's ILogger interface and not something like ILog (log4net) was because ILogger is an abstraction over the ILog interface.  Castle also provides some concrete implementations of ILogger, one of which is for log4net

  • log4net (requires Castle.Services.Logging.Log4netIntegration.dll)
  • NLog (requires Castle.Services.Logging.NLogIntegration.dll)
  • ConsoleLogger
  • DiagnosticsLogger
  • StreamLogger
  • WebLogger (TraceContext)
  • NullLogger (used as placeholder)

As far as testing is concerned, the solution imposes no restrictions on testing.  In my testing assemblies my logging calls are swallowed by the null logger.  If I want to ensure the logger is called in my testing (interaction based tests), I can mock an instance of ILogger and call Log.SetLogger() and set up expectations on the mock ILogger.

As I've mulled over this solution now for about a day it feels pretty solid.  As I go through the requirements above they are all satisfied.  However I can only see as far as my current knowledge so I'm hoping that if you see issues with the above that you'll let me know.


 
Categories: .NET | Programming

August 4, 2008
@ 09:55 AM

I posted earlier this year with the basic question, Is Var Better?  I'm not the only one to question the reintroduction of var.  Rhys Campbell went as far as to say some abuse the new keyword. I will say that my initial aversion to using var has softened a bit.  However there are at least two issues I have with them.

  1. Implicit conversions
  2. Intellisense

Implicit Conversions

In my latest project I've encapsulated all domain knowledge in it's own assembly in DDD fashion.  We have the notion of a ProductSku, a unique identifier for a product.  A Product object therefore has a ProductSku property which identifies it.  I could have implemented the ProductSku property as a string type, but in thinking about my domain and remembering March is Not a Number ProductSku is now it's own first-class citizen type.

I have the following code to perform implicit conversion from a ProductSku to a string:

   1: /// <summary>
   2: /// Performs an implicit conversion from <see cref="JPCycles.Domain.ProductSKU"/> to <see cref="System.String"/>.
   3: /// </summary>
   4: /// <param name="sku">The sku.</param>
   5: /// <returns>The result of the conversion.</returns>
   6: public static implicit operator string(ProductSKU sku)