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

October 2008 - Posts

  • Mass Transit - Part 2 of N

    Last week I posted the first in a series on Mass Transit, an open source enterprise messaging system.  This series is my public exploration into messaging for our eCommerce application.  In this post I'm going to dig in to see an actual working example.  I like to see something work, then dig in to figure out how it's all put together.  We'll take a look at a simple publish subscribe example to see the messaging in action.  In later posts we'll dig in deeper into the guts of MassTransit.  That said, let's see some MassTransit in action!

    Getting Started

    I've downloaded the MassTransit source from the Google Code repository and am going to run one of the samples provided with the source.  We'll look at their "PublishSubscribe" sample.

    image

    Project Structure

    image Opening the solution reveals nine projects, a few more than what I would consider a simple sample, however don't let the solution scare you away.  It turns out that you can for the most part ignore five of the projects, the mass transit infrastructure projects.

    There are four parts to this solution that are relevant and we'll focus on those:

    • Client - The client represents the application that wishes to leverage messaging.  It plays the role of publisher in this example.  It is worth noting however that in this example, as we'll see, this project is also a subscriber.
    • Security Messages - This is a pretty simple project as it should be.  This project encapsulates the strongly typed messages that will be passed throughout the system.  By having the messages in their own light-weight assembly we can keep our messages separate for their consumers.
    • Server - This project acts as the subscriber.  In a normal scenario this server may be sending out emails or logging particularly interesting things as messages come through or whatever else you may have a need for.  Like the client project, we'll see that this project also plays dual roles, the subscriber as mentioned and also a publisher.
    • SubMgr - The subscription manager, is quite a mystery to me.  It may not be obvious, but the subscription manager is needed to get everything to work.  As Dru explains it to me, it is the glue.  In my first go around with MassTransit, I created a client and server and was frustrated when nothing was working.  Talking with Dru, he quickly pointed out my error, I had no Subscription manager.  In the following posts I hope to clear up some of the mystery for myself around the subscription manager.  My understanding at this point of the subscription manager, which may be a bit simplistic, is that it pushes the messages to each of the queues which are interested in the message.  A publisher publishes a message, the subscription manager is the one that ensures that it ends up in the appropriate queue(s) for consumption by various subscribers.

    Getting Setup

    image In order to get this sample going you first have to create the MSMQ queues that this sample expects:

    • mt_client
    • mt_pubsub
    • mt_server

    You can create these queues in the Message Queuing area of the Services and Applications snap-in in the computer management area on your computer.

    Seeing Is Believing

    Now that we've got the project set up let's fire it up and see what we get.  Since we need all three applications running at once, the client, server, and subscription manager we can take advantage of a cool feature in Visual Studio, multi-project startup.

    With multi-project startup you start any number of projects in your solution.  From the properties dialog for the solution we can choose which projects we want to kick off.  (It is worth noting the order in which I have these projects launching.)

    image

    What's Going On

    When you run this example, the client application will ask you to enter a new password.  When you type in a new password  you will get a nearly instantaneous response letting you know the password was updated.

    image 

    The thing to bear in mind here is that at the point you hit the <enter> key submitting your new password, the client publishes a message and then it is done.  It appears instantaneous but you'll want to keep in mind that it is asynchronous.

    The Flow Of It All

    image The diagram to the right illustrates what is going on once you hit the <enter> key.

    1. The client publishes a RequestPasswordUpdate message (see the Security Messages project in the solution for this message object).
    2. The server in this case consumes the RequestPasswordUpdate message.  When it is notified of the message, it logs the new password, then...
    3. The Server publishes a new PasswordUpdateComplete message.
    4. The client consumes the PasswordUpdateComplete message and in so doing writes to the console that the password update is complete.

    It is worth noting here that the client knows nothing of the server and the server knows nothing of the client.  Our example could easily expand to have multiple clients (think for example a windows app or multiple web servers in a farm).  Likewise there could be multiple server instance, each consuming different messages.  In other words, we are very loosely coupled, which is a good thing.

    Conclusion

    I hope this introduction to the MassTransit was beneficial.  Now that we've seen the example working, in the next post I'll revisit the idea of durability.  We'll augment this example and simulate a breakdown in infrastructure and see what durability really means, which is really at the heart of this fantastic open source library.

  • Continuous Improvement - One Developers Journey

    When I started my current position six months ago I was brought in to help with development of their new website application. Whether my boss knew it or not, that meant that I would be bringing a host of baggage with me. When I came I brought along of ideas and practices that were new to the development team. The usage of an IoC container (Windsor), ORM (NHibernate), a build server, unit-testing to name a few.

    These tools and practices are often discussed both here on this blog and in the larger .NET blogosphere. Getting up to speed on them can surely be a daunting task. I’ve asked a lot of the guys I work with in terms of learning new tools and implementing better development practices. I wanted to take the opportunity to interview one of them and let him speak about his experience learning all of these ideas.

    Chris is a developer with a few years of experience with .NET. His exposure and experience to the tools mentioned above begins six months ago, when I joined the team. He approaches development as a student and one of the things I appreciate about him is his openness to the ideas I’m bringing to the table.

    I asked Chris to answer a few questions about his experiences over the last few months. The goal is to give some of you some insight into one developer’s journey to writing better software.

    What has been the biggest change?

    The biggest change is probably the learning curve that was involved in the new software, for example, using Subversion instead of Visual Source Safe. I had to learn new software, but once I felt comfortable in Subversion I realized that I really like it; unlike Visual Source Safe, which was a pain. I always treated it as a necessary evil.

    Has it been difficult?

    Some of it has been. Things like trying to figure out why NHibernate mappings are failing and why Windsor can't resolve a type. These are just things that you have to practice and familiarize yourself with to understand how they can break. It can get frustrating at times.

    What's been the hardest part?

    The hardest part is sticking with it and not going back to the "old ways". There have been times where I was puzzled with some unit tests and mocking and wanted to just give up; it seemed like the best option. More than once I asked myself, "Why do we have to do all this all at once?!?!" When that happens, I just step back, calm myself down and try again. There is always a solution, it just might take some time to figure out why I'm doing it wrong and fix it. Once fixed, it's great and I'm glad I didn't give up. If you're learning several new techniques and patterns at the same time, they can pile up and begin to overwhelm you. Patience is the best medicine in that case.

    What's been the easiest, if anything?

    I'm always amazed how much easier it is to integrate with other colleagues' code. Pulling a latest version from source safe and compiling, then pushing the code manually to the test server was a pain and caused countless headaches and stress. Not only the continuous integration, but the concepts promoting better abstraction really lend themselves to working with each other, not against each other.

    Do you feel like this is the correct path?  In other words are you writing better applications?

    I think this path is very conducive to writing better code. It's visible by the unit tests and code coverage. To me these are readily identifiable measurements to the quality of the code. I know code coverage can be 100% even on bad code, but confidence in my tests creates confidence in my code overall. I now have little confidence in code without unit tests.

    Any advice to someone who is reading this article?

    I have a personal trait to never accept anything as a good enough answer. This is sometimes a good, and sometimes a bad trait of mine. I think in this aspect, development, it's a good thing. For instance, you could be comfortable with drag-and-drop web forms controls, they work. Are they the best way to build web applications? One could argue for them, but I would argue a resounding no. There are a lot of solutions to problems out there and just because you know it as the best approach, doesn't necessarily mean it is the best. Do some research; learn some new techniques and you'll surprise yourself how many great ideas there are out there.

    I want to thank Chris for sharing his experiences here on this blog.  You can check out Chris' blog at http://www.dumpsterdoggy.com.

  • Mass Transit - Part 1 of N

    This post is the first in a series of posts I plan to do about MassTransit, an open source messaging system written by Dru Sellers (blog) and Chris Patterson.  I plan on blogging my observations as I explore both the implementation and the source code.  Before I dig into MassTransit specifically, I want first touch on a few introductory items.

    What Is Messaging?

    Messaging quite simply is a type of notification.  In the real-world we deal with this everyday.  Consider meeting someone for the first time and you say, "Hello, my name is <your name>."  You've published a message.  If the person on the end is polite, they will have "subscribed" to your message and choose to publish one back, for example, "Nice to meet you <your name>, my name is <their name>."  Another example is someone shouting, "FIRE!" in a crowded theatre.  That is a type of message, albeit an important one.

    In code, some messages are rigidly defined, such as when an event is raised.  Many messages, however are more loosely defined.  Consider for example the creation of a string, a log message if you will, that is stored in an in-memory queue.

    Can I Benefit From Messaging?

    Maybe, maybe not.  Once upon a time I worked for a company that offered a CMS product as part of it's product offerings.  This system started small but gradually had increased demands in the form of new features clients wanted added.  Pretty soon, when you clicked the save button multiple things were happening; a database row would be updated, an email would be sent, a new file would be written, another status file would be updated.  These were all executed when the user clicked the button, therefore every action was a blocking action, the server couldn't move on until it was done servicing that particular request.  Performance degradation wasn't a problem when only one or two things were happening but as users demanded more features performance suffered, which manifested itself in long page loads.

    In this example many of the things the application did after the user clicked the save button could have been moved to an asynchronous processing mechanism.  This is where messaging comes in handy, instead of doing all of those tasks in a blocking form you end up instead publishing messages and let some other process come along and do the work for you, asynchronously.  This provides for a much quicker and scalable system.  For example:

       1: public void Save(Entity entity)
       2: {
       3:     EntityRepository.Save(entity);
       4:     
       5:     Publish(ShouldSendEmailMessage);
       6:     
       7:     Publish(WriteFileMessage);
       8:     
       9:     Publish(UpdateStatusFileMessage);
      10: }

    What Makes MassTransit different?

    MassTransit is based on the idea of durability.  To explain durability I will point you to the title of an MSDN article by Udi Dahan named "Build Scalable Systems That Handle Failure Without Losing Data".  Durable messages means that the message can survive some outside event, such as a server reboot or a process recycling.  Imagine my in-memory queue scenario above.  Image the queue has 50 messages when the server reboots. Where do the messages go?  Since the messages were stored in-memory until they were handled, they are now lost.  In other words, these messages were not durable, data was lost.

    Poor Man's Durable Messaging

    I recently came across an application that chose to write the properties of an email to a database table rather than attempt to send the email real-time (for performance reasons).  In this particular instance there was another simple .NET console application that ran every few minutes that would look at the database table and see if there was anything in it, if there was it would pull the records and loop through each one sending an emailing and deleting the record after the email was sent.

    Durable, yes.  Scalable. No.

    Tell Me Why I Need It?

    I can hear you now, you're probably thinking, "Hey that database table idea is pretty slick.  I'm doing the same thing in my app and it works fine.  Why do I need a whole new framework to do this?"  The problem that MassTransit seeks to solve is that of scalability.  The database table for emails works well if all you have to do is send emails.  The more messages you want to handle the more database tables you have to add.  Want to add a row to an audit database whenever an action happens, you have set up the database table to hold the information you want the consuming application to handle.  In other words for N types of messages you have to do N things; and that's bad when you want to scale.

    Why MassTransit and not NServiceBus?

    The reasons I chose to explore MassTransit and not NServiceBus are not scientific at all.  You may not agree with them, and that is fine, but I'm providing them here so you know why:

    • Familiar and Friendly Authors - Dru Seller is one of the nicest guys I met while in Seattle at Alt.NET.  If I have questions or comments about MassTransit, I just pick of the phone and give Dru a call.  Granted not all of you have that ability, but again, I said these were my reasons.  If you are friends with Udi Dahan, I'd strongly suggest you take a look at NServiceBus.
    • Familiar Commonality - MassTransit uses and integrates with other frameworks/libraries that I use, most notably it's integration with Windsor/MicroKernel and secondly NHibernate.
    • Relatively Small - MassTransit is small, yet powerful, and covers the functionality I need.  Being small and young, it is easier for me to go through the project and it's history.
  • Tornado Update - Your Help Is Needed

    I'm sorry this is not a tech related post, but rather a call for your help.

    image Many of you won't know this but my wife's home town of Parkersburg, Iowa was struck by a tornado back in May.  My in-laws lost everything.  All that was left of their house was the basement, literally.  The tornado destroyed every building on their farm and killed nearly all of the livestock.  Worst of all Sarah's aunt was one of six people killed in the tornado.  The town is rebuilding and is in a unique position, please see the email below originating from my wife:

    As many of you know, my High School was destroyed with the EF5 tornado that went through Parkersburg, May 25th. Aplington-Parkersburg High School has been selected as a finalist in the contest listed below. Please take time to read the email and vote for A-P everyday. The contest runs Oct. 6th (today) - October 19th. This would be such a blessing to the school and community. I would really appreciate if you took the time to do this for the next couple weeks, it is an easy way to show your support and help out. 

    VOTE TODAY! AND EVEN BETTER, FORWARD THIS ON TO ALL YOU KNOW AND HELP ME SPREAD THE WORD!!! Also, if you have more than one email address, I encourage you to vote from both as any valid email address counts as a vote!

    Thanks!

    Sarah Barcz

    Please take a few minutes and vote for Aplington-Parkersburg at http://www.henkelhelps.com

    If you're concerned about your address ending up in some database I completely understand, but you can vote and protect your email/inbox, remember I showed you how to do that.

    If you do vote, please leave a comment below and let me know that you voted for Aplington-Parkersburg.

    Posted Oct 09 2008, 03:49 PM by Tim Barcz with 9 comment(s)
    Filed under:
  • Frictionless Subversion Updates

    Friend and fellow blogger Chris Sutton wrote a post the other day about updating source code with batch file.  I found it quite helpful given the number of open source projects I follow (or attempt to) and the different repositories we have at work.  A simple click and all projects registered in the batch file were updated.  The only problem is that any time I download a new project, I'm going to have to crack open the file and add in another project.

    Chris' solution reduces friction, I'm wanting to provide a solution that reduces it further:

    New Solution

    This new solution will traverse a directory and find all directories that contains the ".svn" directory which indicates the directory is under source control.  If the directory is under source control then the batch file issues an update command to bring the source up to date.

    File System Structure

    image

    The Batch File Source

       1: @ECHO OFF
       2: FOR /D %%a IN ("*") DO CALL :SvnCheck %%~dpa %%a
       3: PAUSE
       4: GOTO :eof
       5:  
       6: :SvnCheck
       7: set sourcedir=%1%2
       8: set dir=%2
       9: set svndir=%sourcedir%\.svn
      10: echo "%sourcedir%"
      11: CD %dir%
      12: IF EXIST %svndir% svn up
      13: CD ..
      14:  
      15: :eof

    Without getting into all of the details of the batch file syntax, the basics of what is going on here is that there is a for loop, looping through each directory.  If the directory has the ".svn" directory then the "svn up" command is issued.

    Happy updating (now with less friction)

    Update

    After reading some of the comments, particularly some by "Chris", I've went back and made this simpler.  Thank you Chris

       1: @ECHO OFF
       2: FOR /D %%a IN ("*") DO IF EXIST %%~dpa%%a\.svn svn update %%~dpa%%a
       3: PAUSE
    That's it, small, concise, and for all practical purposes down to one line.
  • Iowa Code Camp - November 8

    image

    I want to invite any of you who are within a few hours of Des Moines, Iowa to attend the second Iowa Code Camp on November 8th.  The first Iowa Code Camp back in May was a huge success. From Derik's write-up:

    Yesterdays event was awesome.  They had about 125-150 people show up for the first ever Code Camp in Iowa.  The venue could not have been any nicer and setup any better.

    I will be giving one presentation on using RhinoMocks and one workshop on TDD.  Below are the abstracts.  If you have the chance, take part, and register today.

    TDD: A Workshop in Driving Your Design with Tests

    If you've heard about Test Driven Development (TDD) and wondered what it was or how to do it, then this workshop is for you.  We'll take a practical, introductory approach to getting started with TDD.  We'll introduce fundamental object-oriented design principles including separation of concerns, dependency injection/inversion, and more.  This will be a hands on lab, so bring your laptops and a copy of Visual Studio 2008 and expect to learn.

    Easing your Testing With RhinoMocks

    When learning about testing you'll see trivial examples illustrating how to write tests. However most production code is non-trivial, making calls to configuration files or to a database which makes testing in isolation hard.  The use of mock objects allows you to isolate code you want to test by providing fake objects to your methods, allowing you to set up complex scenarios to test specific conditions.  In this session we'll first dig into some code that is not very testable and refactor it to make it more testable.  After the refactoring we'll use and explore RhinoMocks to see how we can test different scenarios in our code and verify our code is working as it should.

  • Rhino Mocks 3.5 RTM

    Yesterday Oren announced the release of RhinoMocks 3.5.  While the RC version has been out for a bit the RTM release fixes a few bugs.  You can read all about the enhancements and features in Oren's post

    The feature that excites me the most about the new RhinoMocks release is the AAA Syntax (Arrange-Act-Assert).  One thing I've always struggled with when explaining mocking to people is the record replay model.  The new syntax seems to be more natural.  I have no empirical evidence to back that last statement up, only anecdotal evidence from observing fellow employees interact with the new syntax.

    A close second in terms of changes is the deprecations of CreateMock().  In all the features, patches, improvements, and bug fixes this is the only item Oren bolded, which shows it's importance:

    CreateMock() is deprecated and marked with the [Obsolete] attribute. Use StrictMock() instead.

    This one is great for beginners who instinctively pick up the binaries and see the method CreateMock() and end up later with brittle tests.  Brad Abrams talks about the "Pit of Success" and quotes Rico Mariani:

    The Pit of Success: in stark contrast to a summit, a peak, or a journey across a desert to find victory through many trials and surprises, we want our customers to simply fall into winning practices by using our platform and frameworks. To the extent that we make it easy to get into trouble we fail.

    In earlier versions of Rhino it was too easy to use CreateMock() when DynamicMock() is what you wanted.  New mockers were often using the wrong method (I was one of these CreateMock() abusers/users).  The warning when using CreateMock, and the other enhancements/changes, make falling into the pit of success (with mocking) a much more likely reality.

    You can download the bits from Oren's download area.  When you download, I would encourage you to make a donation to Oren's open source efforts.

  • Testing Pre-Requisite - Care About Your Code

    There's a lot of posts and chatter about testing, TDD, and a number of other topics on this blog, the larger devlicio.us site, and the .NET community in general.  Before all that, it should go without saying, but it must be said; there is a pre-requisite to testing, care about your code.

    You have probably come across some code in your career that is less than ideal.  Maybe you've even submitted something to the Daily WTF. I'm currently combing some old code trying pull out some main concepts.  As I'm going through the code I'm seeing some things that really are quite alarming.  I'm not talking about differences in what I would do in terms in architecture, implementation, or even language choice.  I'm talking about blatant code rot, code that no one has cared for.

    Some stats for the current file I'm in:

    • Lines in file: 1820.  This is the mildest offense, while I don't endorse a class/file that large I can live with it.
    • Classes defined in the file: 19.  I find this a "little" excessive, Even if you don't subscribe to the "one class per file" rule, 19 is a bit much don't you think?
    • Example Method: 697 lines.  That number isn't entirely accurate as 395 of the lines are commented out.  I understand the scenario that probably led to this, in fact I'll admit to doing it.  You comment out some code as a fail-safe in case the new implementation doesn't work.  The problem here is that the code does work (and I use that term loosely).  The developer never cleaned up after themselves and their trial code.  This makes absolutely no sense when you have source control in place.

    Here's a method I came across today:

       1: Public Overrides Function ToString() As String
       2:     If IsNothing(_fields) Then
       3:         Return ""
       4:     End If
       5:  
       6:     Dim r2 As String
       7:     'make room for 1 char and 1 delimeter for each field
       8:     Dim retVal As StringBuilder = New StringBuilder("", _fields.Length * 2) 
       9:     For Each f As Field In _fields
      10:         r2 = r2 & f.Prefix &_ 
      11:             f.Value &_ 
      12:             f.Postfix &_ 
      13:             ConfigurationSettings.AppSettings("ControllerFieldDelimeter")
      14:         retVal.Append(f.Prefix)
      15:             .Append(f.Value)
      16:             .Append(f.Postfix)
      17:             .Append(ConfigurationSettings.AppSettings("ControllerFieldDelimeter"))
      18:     Next
      19:  
      20:     r2 = r2 & "<EOT>"
      21:     retVal.Append("<EOT>")
      22:  
      23:     'Return retVal
      24:     Return retVal.ToString
      25: End Function

    The first thing I noticed was the string concatenation in lines 10-13.  The problem is the "_fields" (the collection over which this code is iterating) can be large.  So concatenation isn't the best choice.  While clearly not optimal, let's let that slide for a moment.  The very next line, lines 14-17, there is some appending of seemingly the same data.  In the end r2, the concatenated value which was so expensive to generate, is never returned or used elsewhere.  All of those extra, wasteful concatenation calls are spent on worthless code.  The developer(s) who worked with this over time simply never cleaned up after themselves or cared for the code.

    I'm amazed that code like what I'm looking at is found in code bases.  I probably shouldn't be surprised but I am.  Today I was posting my reactions on Twitter and a friend Rhys Campbell commented:

    "395 of them are commented out".. delete them! do it! You know you want/need to

    I think Rhys is right, I will fix the code as I see it.  The codebase is being phased out but that doesn't mean it shouldn't be cared for.  If I am caring for code that is going to be obsolete and replaced soon, how much more important do you suppose is it to care for your current code?  If any of the above sounded like your code, get with it, clean up and care for your code.

    Posted Oct 02 2008, 09:20 PM by Tim Barcz with 5 comment(s)
    Filed under:
More Posts

Our Sponsors

Proudly Partnered With