Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Tim Barcz

Why use nails when a screw is the more reversible choice? Have Twitter, follow the conversation there at @timbarcz

August 2008 - Posts

  • Test Your Windsor Container Configuration

    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.

  • NCover Requires Admin Privileges To Run

    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.

  • PRG Pattern in the ASP.NET MVC Framework

    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

  • Using Firebug to Bypass Company Filter To Access Twitter

    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

  • What First - CI or Unit Testing?

    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?

  • Scrum - A Not-so-bad Development Methodology

    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.

    Posted Aug 18 2008, 02:49 PM by Tim Barcz with 7 comment(s)
    Filed under: ,
  • Strongly-Typed ViewData Without A Codebehind

    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="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.

  • The Tortoise and the Hare

    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.

  • I'm In the House

    If you're reading this, you've most likely been alerted by your feed reader that there's been a new post on the devlicio.us feed.  Now you're thinking, "Who's the new guy?"  I'll get to introductions here in a moment, but first I want to thank Sergio Pereira and the Devlicio.us crew for welcoming me so enthusiastically.  I've been a subscriber to the devlicio.us feed for some time now and have always enjoyed the content that comes from it's contributors.  I'm excited to now be a part of devlicio.us and it is my goal to help carry the torch and add to the already great content that is found here.

    Who is Tim Barcz?

    I'm a software developer who's passion for writing great software is only superceded by his passion to get better.  I enjoy learning and sharing.  Therefore as I engage you I ask that you engage back by leaving comments, emailing me, ect.  The goal for me is to ultimately provide useful content to you and improve myself in the process.  I can't do that if I am an island.

    I got started in programming on the web back in HTML and JavaScript with a site on Geocities.  Since that time I've worked in a variety of languages including a brief year-long stint in compiler theory which culminated by writing my own language and compiler (named "aplos").  Despite my varied activities and interests throughout the software world, I tend to gravitate back to the web.  I am an active participant in the Alt.NET community which, for me, simply means that I continually question the status quo.  I'm from Cedar Rapids, Iowa where I am active in the Cedar Rapids Ineta user group.

    Again, I'm honored to be blogging among some very cool people.  I look forward to the months/years ahead getting to know you through this blog and providing you with great content.

More Posts

Our Sponsors

Proudly Partnered With