Friday, May 02, 2008

I'm an Insider

Quick update:  I've been invited to join ASP Insiders!  I'm proud to be part of a select group of ASP.NET professionals who reach out to the community via forums, blogs, conferences, etc and are generally recognized experts in ASP.NET.



Some of the benefits of being an ASP Insider is to get in on some private discussion about design, new features, etc.  While I cannot publish any of this on my blog, I will be able to provide feedback in some areas (such as ASP.NET MVC).

Now, to go learn the secret handshake..
Thursday, January 17, 2008

The Texas Tour of ASP.NET MVC Comes to a Close

It’s been an exciting two weeks.  I visited user groups in San Antonio, Houston, Austin, and Fort Worth, and I got to meet and connect with a lot of interested developers about the new ASP.NET MVC framework.

Two of the events were recorded, so if I ever get my hands on the recorded bits, I’ll post them here in an easily watchable format.  (Don’t hold your breath though.)

My presentation had a minimal amount of PowerPoint.  I decided to focus on real code.  And people have thanked me for it! 

I covered:

  • Basics of MVC
  • Default Routes
  • Simple Controller / Action
  • Passing data to the views
  • passing strongly typed view data
  • Custom Routes
  • new/edit form for an entity
  • writing tests for controllers
  • rhino mocks for mocking out dependencies
  • dependency injection for controllers (using Windsor)
  • ajax integration with prototype

This is a lot to tackle in my 1/1.5 hour time slot.  And I do get a lot of blank stares when I talk about mock objects and dependency injection, but I think more presentations need to present realistic code, rather than simple examples.  The feedback I’ve gotten about this has been overwhelmingly positive, and I’m really glad people liked it.

Some questions that were asked during my tour…

“Ben, you are phenominally good-looking?  Are you available?”
umm no, I’m married (and now terrified)

What is that cool zoomey tool you used?  That’s awesome!”
that is called ZoomIt, by sysinternals.

What are you using for data access on your entities?”
It’s called Castle ActiveRecord, which uses NHibernate underneath.

Can I use ASP.NET validators?”
—Well not really.  The validators have viewstate, which won’t work.  Your validation definitely belongs in the Model, so you could just do server-side if you want.  If you want clientside validation, you could accomplish a similar result by using marker css classes and some clever javascript  (think <input type=”text” class=”required” name=”address1” /><span class=”error_message”>This is required</span>

If we use this on IIS6, will performance suffer?”
— Probably.  On IIS 5/6 you have to send all requests through ASP.NET, which can be slower.  I’m not an expert in this area, so definitely do your research before making any rash decisions.  When we have Windows Server 2008 and IIS7, expect vast improvements.

Do you know Justice Gray?”
—Sure do.  I’m a bona-fide potential friend of Justice Gray, and even have the certificate to prove it.  It’s serial number marked 00000000000003.  I carry it with me at all times for just such a question.

Can you use co-exist with webforms?”
—Yes!  If you hit a page with the .aspx extension, the PageHandlerFactory will pick it up and you will be in WebForms Land.  If you instead hit a route, you’ll be in MVC Land.  Learn to know the difference and you’ll be fine.

Isn’t it dangerous to output strings directly like that?”
—Yes it is.  Read my post about html encoding your values.

Your hair is impeccable?  What kind of gel do you use?”
— It’s called Fructis something-or-other… and it’s awesome!

So Microsoft has two methods of developing web applications?  Which should I choose?”
—If you like the rich eventing model and the ability to save state and mimick a smart client ui, then choose web forms.  If you value clean html, urls, separation of concerns, and testability, then choose MVC.  I will be choosing MVC more often than not from here on out.

When will it be released”
—Gawsh, I don’t know?  Fall 2008?  As soon as I know I’ll post it here.

(admittedly, a couple of those questions were not asked — I’ll let you guess which ones)

You can download the code and the presentation here:

File Attachment: save the world with asp.net mvc.zip (1612 KB)

I’d like to thank the user group leaders for having me speak, it was certainly a pleasure.  Where will the next tour be?

Wednesday, January 16, 2008

Thank you ADNUG and FWDNUG

I got the chance to meet an enthusiastic bunch of folks in Austin and Fort Worth this week, and I wrapped up my Texas Tour of MVC.  I really want to say thanks to groups for having me.  It was a pleasure to speak and connect with fellow developers in Texas.

I’ll be posting a massive recap this week that includes the code and powerpoint that I delivered.  I’d appreciate any and all feedback.

Now for that long drive home…

Saturday, January 12, 2008

Visual Studio 2008 CSS Support - Not Quite

One of the often-touted new features of VS 2008 is the improved CSS support.

I like having intellisense for CSS, sure, but I dont’ want to have a warning for classes that don’t exist…. like this:

Vs2008-css-warning

That green squiggly indicates a compiler warning.  It can’t find the CSS class, (which is referenced in the Master Page). 

But there are other reasons why you might want to define a class without defining an associated style.  You might be using it to distinctly select elements from the DOM using javascript. 

The ever-so-awesome prototype framework introduced this syntax:

$$(‘.info’)

which would select all of the elements with a class name of “info” for you to work with.

Just about every other javascript library out there now supports this syntax (or a similar one).

If this bugs you, you can turn it off by checking this box (in Tools -> Options) :

Vs2008-turn-off-html-errors

You may not want to do this, though…  it could potentially save you time if you’re looking for a rendering bug.

Another part of VS 2008 that I don’t really care about is this CSS designer.  I can’t imagine anyone who would actually use this.

I mean, come on… look at it!

Vs2008-css-builder

I guess if you don’t know CSS very well, you might want some options.  But that form is more confusing to me than border-top: solid 1px #999;.

(and one could argue, if you don’t know CSS, should you be defining styles at all?)

I really applaud Microsoft’s attempt to bring a better CSS development experience to the masses, but I think they missed the mark on this one.

Thursday, January 10, 2008

Thank you HDNUG!

I enjoyed giving the presentation on ASP.NET MVC tonight to about 90 eager developers at HDNUG here in Houston.

There were a few people that had played with the framework before, a lot who had heard of it, and about 1/3 of the room had never heard of it.  Awesome!

There’s always a balance between how intro a talk should be, but one of my goals with this talk is to show real application code; to show how you actually test these things, and what types of practices and tools that can enable this and make it easy.

I hope that the talk was well received.  If you went, I’d love to hear your feedback in the comments!

Some links from the talk:

I’m sending the code over to be posted at HDNUG right now.  After my tour ends next week, I’ll post a large recap that includes code and hopefully answers to common questions that I’ve been hearing.

They also recorded the talk, so once I get my hands on the video, I’ll throw it up here so others can have a look.

Thanks for having me HDNUG!

Wednesday, January 09, 2008

Be careful outputting strings in ASP.NET MVC

During my presentation at Alamo Coders last night, someon mentioned that it is unsafe to output user-entered strings like this:

<h2><%= college.Name %></h2>

The reason is, of course, that the user could be malicious and enter in a string such as this:

“<script>alert(‘I am evil’);</script>”

And it would evaluated on the page and all of your users would get an alert box.  This is leaving your door wide-open to clever attacks known as Cross Site Scripting and is very dangerous.

Instead, we should escape these strings so that they aren’t rendered as HTML or javascript, but rather textual characters.  That means that < will be translated to &lt; and so on.

To do that, the Html helpers that ship with the framework give you an Encode method, letting you do something like:

<h2><%= Html.Encode(college.Name) %></h2>

But the syntax is a bit cumbersome for every outputted value on a page.  I prefer the way Rails handles it… like this:

<h2><%= h(college.Name) %></h2>

And it turns out that you can add this extension method somewhere and be done with it:

public static string h(this ViewPage page, string input)
{
     return new HtmlHelper(page.ViewContext).Encode(input);
}
And that’s it!  Just remember to take this precaution, or you’ll regret it later.

Thank you Alamo Coders .NET!

Last night I kicked off my Texas Tour of MVC at Alamo Coders in San Antonio.

The room was pretty small and they filled it up with about 25 people.  It was a bit more personal and cozy than the Houston .NET User’s Group that I’m used to.

I ran a bit short on time, but luckily I had my ready-baked turkey in another folder so I was able to show my ajax portion of the presentation and I think it went well.

I got some feedback from a few people who found the talk to be covering too much.  (In addition to ASP.NET MVC, I covered inversion of control, mock objects, and a few other things).  I wish I had a bit more time to explain these things in more detail, as it can be like drinking from the firehose, however I think they are important topics, and necessary to understand if you expect to properly unit testing on your controllers.

For those of you that were there, here are the relevant links for more information…

Inversion of Control:

Mock Objects:

The javascript library I was using was prototype, available here: http://www.prototypejs.org.

Thanks again to Alamo Coders for having me!

Sunday, December 30, 2007

ASP.NET MVC Tour of Texas

Want to see what the hype is all about with the new ASP.NET MVC Framework?

I’ll be touring Texas speaking about it.  If you live in Texas, come check out my talk “ASP.NET MVC – Save the Developer, Save the World.”

Here’s the confirmed schedule:

  • January 8th – Alamo Coders (San Antonio)
  • January 10th – HDNUG (Houston)
  • January 14th – ADNUG (Austin)
  • January 15th – FWDNUG (Fort Worth)

We’ll take a look at the new framework, the design goals, and dig into some code.

Hope to see you there!

 

Sunday, December 09, 2007

The Long Awaited ASP.NET MVC Has Arrived

Enjoy:

http://asp.net/downloads/3.5-extensions/

Also, be sure and check out the brand-new open source project http://mvccontrib.org for all of the extra stuff that ASP.NET will not ship with.

Time to play!

Thursday, November 29, 2007

System.Web.MVC on the Horizon

Looks like we can expect the ASP.NET MVC CTP to be released in about a week.

Great stuff!  Check out some of the other major things that are coming out of Microsoft in the coming months at ScottGu’s blog.

Tuesday, November 20, 2007

Book Review - ASP.NET 2.0 Anthology

A few weeks ago, Jeff Atwood sent me a free review copy of his new book, The ASP.NET 2.0 Anthology.  He co-authored the book with K. Scott Allen (from OdeToCode), Wyatt Barnett, Jon Galloway, and Phil Haack.

Normally I wouldn't get excited about a book like this, but looking at that list of authors I was more than intrigued to give it a try.  Granted, the book is targeted for the beginner to intermediate ASP.NET developer, so a lot of it was not very helpful to me, but I did find quite a few good nuggets that I will take away and utilize in the future.

The first few chapters give a general overview of the newer features of .NET 2.0 and some other basic concepts.  I think that this would be helpful to someone just coming to ASP.NET (maybe from another language) and want to get started. 

The book was published by SitePoint, under their "Anthology" style.  This means the book is organized into 101 different "tips" phrased as questions that someone might ask on a forum or similar.  Some examples from Chapter 1 are "How do I use source control?" and "How do I go about using open source code?" -- I was pleased to see these sections in the book.  You normally wouldn't expect this and I think it helped make the book more well-rounded.

The middle chapters were a bit more targeted to the intermediate ASP.NET level, which made it more interesting for me.  They covered things like custom configuration sections, custom validation, how to maintain control state when viewstate is turned off.  All throughout I think the authors gave solid advice on all these features.  There was a good section on Membership and Access Control, which is sure to be helpful to intermediate ASP.NET developers.

The last few chapters were the most interesting to me, which is funny because most of them weren't specific to ASP.NET.  A section on troubleshooting bothersome SQL queries is sure to help people out.  There were a good number of general web developer tips, such as considering SEO and clean HTML for good search engine rankings.  I appreciated the tip on how to utilize URL rewriting at the IIS level, and how to serve-up custom images to evil hotlinkers on myspace (thanks Jeff Jon!).  These types of things are great to know when pursuing a career as a web developer.  The last chapter introduced SubSonic, which I think was awesome.  Not many developers that I meet have heard of SubSonic and I find it to be a pretty useful tool with a low barrier of entry.  It definitely warranted some attention in this book.

While a lot of the content was your typical ASP.NET 2.0 fodder that I avoid (like SqlDataSource), I thought that the authors did a good job of noting when things were applicable, for example when to use the Web Site model vs. Web Application Projects.  The book didn't have enough beginner content and explanation of ASP.NET to be a beginner book (which is a good thing), but it did have quite a lot of excellent tips that makes this book a great companion to any intermediate developer.

Tuesday, November 06, 2007

Prototype & Scriptaculous - Protips #1

I often talk to people who haven't worked with one of the cool javascript frameworks out there.  I am partial to prototype and scripaculous, but I also really like MochiKit.

If you aren't taking advantage of one of these, then perhaps this post is for you... I give you the ultra quickstart to diving into prototype and scriptaculous!

Things you shouldn't ever program javascript without

The best thing ever invented since rubber tires: a replacement for document.getElementById('control_id');

You know you're not supposed to use document.all or document.ctrl_id, right?  Well at least now you do. document.getElementById() is the cross-browser safe way of getting an element off of the page. The prototype equivalent is $('control_id'). This will automatically extend the element returned with some helpful utility methods (like extension methods in C# 3.0). -- more on this later.

Along the same lines is a useful method for selecting elements using CSS selectors. If you're a CSS junkie (like me!) you'll appreciate this.    

$$("div span.info");
This will return all of the DOM elements that would be matched by that CSS Selector. (for those who don't know, this would get all span tags with a class of "info" that are directly nested underneath a div.

Want to show or hide an element? Use Element.hide(ctrl), Element.show(ctrl), or Element.toggle(ctrl). You can attach these methods onto the element itself by saying Element.extend(ctrl). If you retrieved it via the $() method, then your object already has these methods.

Let's say you want to grab all of the span tags from a parent div tag.  Typically you'd do this:

var spans = parentDiv.getElementsByTagName("span");

but what is spans?  If you thought it was an array, you'd be wrong.  It's a NodeList, which is not nearly as powerful as a javascript array.  (With javascript arrays you can push(), pop(), shift(), and other cool things that you can't do with a NodeList.  Anyway, back to the spans collection, we can elevate this to an array by using the $A( spans ) method.  Now we can use all of the nice array goodness for that list.

Effects for that extra polish

How about fading an element?

new Effect.fade(elem);
This also takes options so you can control how fast it fades, for example. Check the excellent docs for all the gory details.

Want to make a slide out box?

new Effect.toggle(elem, "slide");
This will toggle the element using slide up and slide down. ("fade" and "appear" also work here for toggling).

How about some ajax?

Forget UpdatePanels. Most of the time we just need to fire off a request and get a list of values back from the server. Prototype has you covered there:

new Ajax.Request( "/path_to_server/ajax/AjaxHandler.ashx?op=getUsername&value=bob",
{
method: "get",
onSuccesss: function(result) {
if(result.responseText) alert('available!); else alert('taken');
},
onFailure: function(e) { alert('something went wrong ' + e); }
}

I don't know about you, but that's pretty painless to me.

Want something a bit richer?  How about an autocomplete textbox? I wrote this one to auto-complete cities as you type.

var url = '~/AjaxHandler.ashx?op=get_cities';

ac = new Ajax.Autocompleter(city_textbox_id, results_id, url,
{
paramName: 'filter',
frequency: 0.2,
minChars: 1,
indicator: indicator_id,
callback : function(element, filter) {
var state = $(state_dropdown_id);
var state_code = state.options[state.selectedIndex].value;

return filter + '&state=' + state_code;
}
});

That's it. I'm not kidding. I handed it a textbox, a div to display the results, and a url to get the data. It takes care of all of the ajax requests, the frequency limiter to prevent us from firing a request with every single keystroke, and returning the results into a list. It even has full keyboard support. The url looks like ~/AjaxHandler.ashx?op=get_citiees&state=TX&filter=Hou and it will return the matches that it finds (based on an HttpHandler I wrote).

What are your favorite prototype / scriptaculous protiops?

Friday, October 26, 2007

The MSFT Open Source Conspiracy Continues

The latest news just broke in the previously noted Microsoft Conspiracy to Consume good open source project leaders.  I'm sure you've heard it 10 times before me, but what the hell, what's 1 more?

Rob Conery, creator of SubSonic is joining Microsoft full time to work on SubSonic!  I think this is great news.  First, it reaffirms my belief that Microsoft has their eye dead on the community.  Things are changing, and for the better, mark my words (muahahah).

I can't wait to see how this will affect the project, because I know that Rob has passion, and now that he doesn't have to worry about other projects, clients, or deadlines... he can focus and make SubSonic even better!

Who will be next?  Speculate in the comments...



Wednesday, October 17, 2007

Bandaids, Coke, QTips, Kleenex, and Ajax

 I’m sure you’ve noticed these…

  • Bandaid - Adhesive Bandage
  • Coke - Soda (at least here in the crazy south)
  • QTip - Cotton Swab
  • Kleenex - Tissue

The world doesn’t need another one:

  • Ajax - Microsoft ASP.NET AJAX

For the 100th time… AJAX does not mean Microsoft ASP.NET AJAX!

Need I say more?

Tags:
Monday, October 15, 2007

MVC versus MonoRail and the Corporate Giant

A lot of buzz is going around about the MVC framework coming out of Microsoft.  I posted about how cool it was and got a couple of comments that basically said: 

They just copied MonoRail.

Well, yes.  In a sense they did.  And Rails.  And Django.  And another one that The Gu mentioned that I hadn’t heard of.  Is that a bad thing?  If you’re using MonoRail today, then you should continue to use it.  Unless you like some of the different syntax or ability to mock the core ASP.NET Runtime objects.

The reason I think that ASP.NET MVC is so exciting and important is because I often come to clients that refuse to (or make it very difficult) to use non-MSFT produced thingies.  Can I use Resharper?  No, we gave you Visual Studio.  Can I use NHibernate?  No we use Enterprise Library.  Can I use NAnt, StructureMap, MonoRail, SubSonic?  Often times the answer is no.  Recently I’ve had experience where our team dumped eWorldUI in favor of ASP.NET Ajax Control Toolkit.  The reason?  Easier to get approved since it has Microsoft’s name attached to it.  It doesn’t matter that eWorldUI is free and easy to implement.  It matters because somebody sees eworldui.dll in a bin folder somewhere and everyone wants to know where it came from.

When you work in an organization with 10,000 employees that has widely adopted Microsoft as a technology platform, trying to get something approved like MonoRail is like trying to convince a Catholic priest that he’s really a MormonOk so that doesn’t really make much sense, but what I’m getting across is that it’s hard.

Some of my readers have already gone down this route, and succeeded.  And I commend you.  But I have yet to get corporate adoption of something like that.  Maybe it’s my inability to convince people of the benefits, or sway their concerns about supportability and such.  Or maybe I just work with very beligerant clients. 

Some of my colleagues probably read this blog, so just so you know I’m not talking about you… I’m talking about the other guy. .

Back to my original argument.  Since this is a new framework coming out of Microsoft, I will not have to fight to get it adopted.  I can go in and say “this is how it’s done for real applications” and have Microsoft guidance to back me up.  Hell, some clients might even ask me for it!  That’ll be interesting.  I can’t imagine what it would be like for a client to come up to me and say “hey I was thinking, maybe we should use NHibernate for this…”

Thinking about that makes me kind of sad that it hasn’t happened before.  Am I just unlucky?  Am I just not skilled at convincing?  Or is this commonplace in the industry?

System.Web.MVC will reach an audience that MonoRail doesn’t:  The corporate giant who already swallowed the pill and will do anything that Microsoft pushes, good or bad.  And a lot of consultants work firmly in this space.

Tuesday, October 09, 2007

ASP.NET MVC or Scott Guthrie is My Hero

The collective jaws were dropped at ALT.NET.  Just about everyone attended this talk by Scott Guthrie.  If you’d like to watch this, Scott Hanselman has recorded the video and posted on his blog.

ScottGu-MVC

Rather than regurgitate it all here, I’ll quickly summarize what it’s like.

Remember HTML?  Yeah, that.  We are going back to our roots and back to the model that the web really lives in, not a psuedo, event-driven state-based model that is ASP.NET Web Forms.

Why don’t we like ASP.NET Web Forms?  I do like it, but it does have it’s problems.  The benefits of ASP.NET often cause other concerns to rise up.  Tired up re-populating data on the form?  Here’s some Viewstate for you.  Of course Viewstate causes page sizes to explode because most people just leave it on, even for read-only pages with no post-backs.  Think of a grid that you place on a page.  If you don’t have to postback to the same page again (like with a command field or something) then you can turn viewstate off and have a savings of almost 2X!  I for one think that ViewState can be awesome, but it is more likely abused than leveraged.  This is a pain point for many people.

The entire postback model, combined with the event-driven model is something that I have had to learn in-depth the hard way.  I really don’t think any of that knowledge is really helpful at all outside of ASP.NET.  I spent a crapload of time trying to get server controls to work in the complicated ASP.NET lifecycle, and does that knowledge transfer?  Probably not.

Lastly I think that ASP.NET’s templated control syntax often requires an equal or even more lines of code than the actual HTML would take in the first place!  Take the GridView for example.  Sure it’s great and it lets you bind data and get columns autogenerated for you, but take a look of that list of properties.  There is so much there that you almost need a degree in GridViews to be effective with it.

Microsoft has been paying attention to the community.  We’ve been readily ditching ASP.NET Web Forms in favor or Ruby on Rails or MonoRail.

ScottGu presented the new MVC framework (codenamed Scalene) to a huge audience.  There was a lot of trash talking (in a good way) between ScottGu and Scott Bellware.  It’s not easy to take blundt criticism from people like ScottB, but The Gu took it incredibly well and even dished it out a bit.

What I really liked about ASP.NET MVC is that there isn’t that much to it.  Here’s what you’d need to do to start using it on your project (exisitng or new):

  • Add the System.Web.MVC.dll (or however it will be packaged — no installer exists yet)
  • Add 1 HttpHandler to handle a new extension
  • Add 1 HttpModule, which provides all of the routing and black magic of MVC

Create a controller class, like this:

//This example is for you, Jacob Lewallen :)

public class ClownsController : Controller

{

    [ControllerAction(DefaultAction = true)]

    public void List()

    {

        ViewData = Clown.FindAll();  //you write this method or use Castle ActiveRecord for example

        RenderView("List");

    }

 

    public void SomethingSecret()

    {

        //this cannot be accessed by a url 
        //because it doesn't have the attribute

    }

}

Next you’ll need a view.  You can use aspx, Brail, or NVelocity as your templating language.  That’s freaking great that you can choose.

Here’s a quick example of an aspx view:

<h1>Clowns</h1>

<table>

   <tr>

    <th>Name</th>

    <th>Number of Balloons</th>

    <th>Likes Kids?</th>

   </tr>

 

   <% for(var c in ViewData) { %>

 

   <tr>

    <td><%=c.Name%></td>

    <td><%=c.Balloons.Count.ToString() %></td>

    <td><%=c.LikesKids? "yes" : "no" %></td>

   </tr>

 

   <% } %>

</table>

Notice how I get to use standard HTML constructs, use code blocks to provide view functionality & data, and I don’t have to mess with postback or viewstate at all because I don’t need it. 

Wait, you mean we have to learn HTML again?  D.H.H. often reminds us that the HTML is provides beautiful constraints that he is happy to work inside of.  We don’t have any naming containers here.  In fact, we don’t have any unnecessary id elements at all!  If we did, they would be exactly what we typed here, making javascript integration a lot easier.

To wrap this all up, a customizable route in the Global.asax will map the following url to render this page:

http://your_url/clowns/list    <—  look how clean!

The framework knows how that the format is http://your_url/[controller]/[action] and so it instantiates your ClownsController and looks for an action called List().

So much more to talk about, but I’ll be posting more details once I get my hands on it.

ALT.NET Goodness

Wow.  What an awesome event.

I’ll skip the play-by-play, because that has been covered to death.  Instead I’ll focus on my notes.  There are definitely some “meaty” posts in my mind that are still storming, so expect good things to come.  There are some good points here, but it’s a long post so I’ll be surprised if I get any comments .

Being a Catalyst for Change

I first attended a session on “Fostering Passion” and “Being a catalyst for change” which were grouped together.  A lot of people showed up and J.P. Boodhoo led us off.  He talked about the importance of a good, healthy work attitude, and if you aren’t getting what you need from your current employer then you should really seek out something better. 

  • You need to show pain before you can start evangelizing new stuff.  Ask people the question “How is that working for you?”  or “What would you want to improve first…. why?”  This gives you the context and the opening for suggesting new ideas.
  • Talk about problems in context with the 4 variables, this helps lead to whether something is “working” or not
    • Time
    • Scope
    • Quality
    • Budget
  • Hosting brown-bag sessions is a great way to get people excited.  Scott Hanselman pointed out that he found it valuable to create a “shadow government” of peers who you can individually get excited about different topics.  Ask them to give a lunch & learn and spread the word that way.  Somebody called them “Hanselminions”  —  epic.
  • JP Boodhoo stressed that we build relationships before we offer to “fix up their processes.”  If you come in wanting to change everything you’ll just alienate your team and ruin your credibility.
  • Another thing that we discussed is that newcomer’s to our community are going to be very overwhelmed…  currently there isn’t much direction.  We don’t want to be prescriptive, but a general “go in that direction” will definitely be helpful.

Advanced NHibernate

The next session I attended was Advanced NHibernate Techniques, facilitated by Jeffrey Palermo.  I found this to be awesome, because usually when I get to talk (or listen) to NHibernate at a user group or code camp, it’s focused on the beginner side of it.  Everyone in the room had been using it for a while, and had some really good suggestions and valid problems with it.

  • ActiveRecord vs. Persistant Ignorant?
    • I suggested that for dead-simple models, or a team that doesn’t know DDD, that AR was a much easier path with less friction, however you do quickly hit a limit here when you want to start using more Domain Driven Design such as the Aggregate root/aggregate relationship, repository pattern…  or if you need these to be remote… they can’t be used on the client side.  Somebody pointed out that it is very difficult to switch from one to the other, and this makes the initial decision very hard.
    • Howard Dierking pointed out that “No Simple CRUD app stays that way”
  • Database, Mapping, Code -> which first?
    • This was basically a poll question.  Almost everybody here started with code, then database, then mapping.  Very few people used hbm2ddl (like I do) to generate the database.  We all agreed that generating the database needs to be abandoned once you start doing tuning and specific tweaks.  The Eleutian guys (who have names, by the way… Aaron and Jacob) have a pretty hefty process that all starts with a modeling tool.  It kind of scares me, but they seem to have it working so that they don’t have to re-work anything.  To be truly DRY you definitely need another abstraction, however I’m not convinced that UML is it.   What if we had a Boo DSL that represented the mapping, and we could specify advanced DDD concepts there, and have it generate the code, hbm, and Database…?
  • Issues?
    • Aaron and Jacob have been stressing about Adaptive Queries and Read-only queries, and I need to make an effort to understand their problem.  Originally I dismissed this as a non-issue, but that’s a cop-out.  I want to understand what they are wanting that they aren’t getting with NHibernate.
    • We all seemed to agree that it’s painful that if you have a single error in your mapping file, the session factory throws an exception and just about every test in your application will fail.  This SUCKS for pinpointing the error.  I heard Howard mention something about jitting the mapping assemblies (I guess while writing?) — I definitely need to continue this discussion with him.
    • Partials mappings would be pretty cool, so you could generate the mappings based on default conventions, then you could override when necessary.

ASP.NET MVC Framework presented by Scott Guthrie

  • This flippin’ rocks.  A detailed post to follow.

Domain Driven Design – Facilitated by Dave Laribee and Scott Bellware (with a cameo from yours truly!)

  • This was pretty much review for me, but it’s always good to get refreshed.
  • Opening your mouth is a good way to get people to ask you another question (provided you didn’t say something completely stupid) — I kept getting asked to explain more topics here, which was flattering.
  • At one point I said “If you haven’t read Evans yet, go TODAY and buy his book.  Then read it 8 times.”  — This led people to believe that I had read it a few times.  Nope!  I still have 7 more to go .
  • A lot of discussion went around the different between responsibilities of the entities, and the responsibilities of domain services (not to be confused with application services or <gasp> SOA).

User Stories (facilitated by Scott Bellware & Raymond Lewallen)

  • The more I dig into this stuff the more I like it
  • Epics– 30,000 ft view (almost impossible to estimate) (if you have to, also provide a low confidence value)
  • Theme – closer, but not enough to estimate.  Gives more detail.  Many themes per epic
  • Story – small enough to provide estimate & acceptance criteria.
  • Ray said “I can give you a gantt chart & have it say whatever you want on it.”  — this is funny, but SO true
  • Estimation accuracy and Trust are increased as time goes on… providing you aren’t making empty promises early on
  • Don’t estimate a user story until you have acceptance criteria
  • Acceptance Criteria (AC) can be technical
  • AC helps define “done”
  • Early stories will add a LOT of new concepts
    • new models
      • tables, entities, whatever
    • some UI req’s
  • Estimating epics helps w/ product planning  (“How much can we put in by next year?”)
  • Release planning should NOT include epics.  Break them down.
  • AC transitions, which leads is implemented in TDD/BDD style
  • Test names should describe the behavior, not impl.  I’ve got to follow this rule more often.  A lot of tests I write are explicit in that I know what happened if it failed, but the actual story that I’m working on is missing.  The failing test has no context, and thus no value associated with it.
  • BDD classes are named after the state or original behavior.  The setups for this class put the object in that state.
  • Method names are named like the AC
    • public class When_a_case_is_opened
      • public void Its_status_is_changed_to_open

Are Executable Requirements Possible?

  • Jeremy Miller started off by stating the value of Fit vs. FitNesse and a lot of people showed pain with FitNesse. 
  • Fit/FitNesse works great when dealing with state-based testing
  • Behavior based testing is where it breaks down and becomes really cumbersome
  • He invited Joe Ocampo (from Los Techies) to talk about NBehave
  • NBehave solves their problem of providing change tracking and traceability into their organization because they have a strict environment that requires it.
  • They have a fluent language that looks like theUserStory.AsA(“Premier Member”).IWantTo(“get a discount on future purchases”).SoThat(“I can save money”)
  • I joked that they could also have another fluent interface that looked like SystemShall.(“Have a textbox”).ThatShallContain(“the user’s name”) 
  • This helps solve the issue where refactoring is difficult.  Since the strings above are keys for delegate hashes, you’ll get an exception if someone changes the text of a story.  This will spark a much needed conversation with the developers.

I’m still trying to bask in the awesomeness that came from this event.  All you naysayers out there are just upset that you missed out .

Tuesday, September 18, 2007

I'm on to you, Microsoft

There's a conspiracy going on here.  We all ignored the first signs of it, but now it's too apparent to ignore.   Microsoft is engaging in some devious master plan that will affect most of us.

We all read with shock and awe, Scott Hanselman's post where he announced he was becoming a blue badge.  People wondered what this would do to his blog content, or his contribution to DasBlog.  This was the first sign.  And we did NOTHING.

Today, I saw the 2nd sign, and I'm going to expose this Microsoft conspiracy for what it is.  Phil Haack just announced that he is joining the ranks as a Microsoft employee.  That's right, you heard me. 

Microsoft has hired the technical and charismatic leaders of the two most popular open source blogging platforms for .NET.  This is all a part of a master plan to squash the multi-billion dollar market so that Microsoft alone can swim in the sea of money that is to be made from .NET open source blogging.  Don't kid yourself, there is buku (TM) money to be made in this area.

Sure, both Phil and Scott claim to stay committed to SubText and DasBlog, respectively.  But we all know better.  Soon they will be hard at work, developing the most incredible blogging platform ever devised.  I even have a name for this stealth-assassin project.  It will likely be called Microsoft Collaborative Team Works For Online Weblogs Framework Foundation System 2008.  I can just hear Microsoft Marketing salivating at that title.

All kidding aside, I think that Microsoft is going to be changing it's image, especially in the ASP.NET arena.  They've snatched up some key individuals in the community and they will definitely be making waves.  You can quote me on that.

Wednesday, September 12, 2007

GridView Cell.Text Versus Cell.Controls.Add

I'm sure I've come across this before, but I'm writing this down so that I don't forget it later.

I'm working with a pretty hefty custom GridView and it's really trying my patience for this control.  Yeah yeah, it's all great if you want to bind a list of data coming from a SQL Query written in your aspx in plain-text.  The minute you start to customize it all that goodness turns into a mess of weird templating and strange quirks about ASP.NET, but I digress.

Anyway, this post relates to the fact that the TableCell class has a Text property and a controls collection.

If you are creating custom rows of data, you have to choose between doing
cell.Text = "content";
or
cell.Controls.Add( new LiteralControl("content") );
The difference is that the two are mutually exclusive.  If you have controls inside the table cell, then the Text property will be empty.  If you have the Text property set, then there can't be any controls.

So in my case I was setting the Text property, then trying to insert a LinkButton control right before the text.  So I diligently put
row.Cells[index].Controls.AddAt(0, theLinkButton);
Which happily wipes everything that was previously in the Text property.  Ugh.
Friday, August 31, 2007

Tsk, Tsk, Tsk - PNY Should be Ashamed of Themselves

Take a look at one of my co-workers found today.  The screenshot says it all.

Tsk-tsk

No, I didn’t destroy their database.  I was about to send an email to them when I realized it was fixed.

It amazes me that a large company such as PNY would do this.  It was probably written in Taiwan by someone who makes $4/hour, but still.  It makes you think twice before buying PNY memory.

Sunday, August 26, 2007

HoustonTechFest 2007 was a Hit

Houston Tech Fest 2007 was yesterday and it was an amazing success.  Over 600 people were present and I was able to see a lot of old friends and meet some new & interesting people.

I got to chill out with Brad Abrams and a few other folks from Microsoft, and it was great to meet Scott Bateman (fellow Houston blogger and advocate of Continuous Integration).  His talk was most excellent, he was very informative and it showed that he not only understood the concepts, but he was able to explain it all in a way that (I thought) was easily grasped by the audience.

Some of the other speakers included Mike Azocar, John Cook, Tim Rayburn (sorry I missed your talk again Tim!), and David Walker.

Funny thing about Tim’s talk.  I was in the room next door listening to David Walker talk about SOA and WCF, and we could hear Tim through the wall partition.  At one point I heard Tim say, “If you can’t hear me in the back, please shout out and let me know.”  I felt like shouting from our room .

I had two sessions, Advanced CSS & Javascript and ORM with NHibernate.  In the first session, I had a full room (over 100 people!) and the audience was very engaging.  It’s great to have an audience that has so many questions and comments on what you are saying.  It becomes more of a dialog, which I think makes the content so much more valuable for everyone. 

Sometime in the midway point of the talk the projector just turned off.  It’s hard to give a talk on CSS without some visuals, so I continued typing and said “Imagine if you wil…” to a room full of laughter.  About that time the projector turned on again.  I didn’t find out until later, but my friend Wes had sat on the cord and unplugged it, then silently plugged it back in.  Funny how a room full of geeks and nobody thought to check the plug when it turned off.  Ah well.

At the end of the talk I had a couple people come up to shake my hand and a little 4–year old girl came up, touched my arm, then ran away giggling.  (Don’t ask me…).  I really enjoy giving this talk and I would like to branch outside of Houston and start giving it elsewhere around Texas (and the U.S.).

My second session was on NHibernate and it was more cozy, with only 15 people or so.  I think NHibernate is a lot harder to make interesting for an intro class because it is a radically different way of developing applications that most people are exposed to.  There is so much material to cover and only a short amount of time, so I tried to focus on the code and keep the examples short and simple.  I think it was effective, though I’d like to branch off this talk and start giving more advanced lectures on NHibernate.

Thanks to all who came to the event (especially my sessions!).  I hope you all had as much fun as I did.

The files from my presentations can be downloaded here:

File Attachment: AdvancedCSSAndJavascript.zip (1161 KB)

File Attachment: nhibernate.zip (4001 KB)

Also, a lot of people were interested in the tools I was using during my demos.  My favorite text editor is E, which you can get at http://www.e-texteditor.com.  My zooming tool that I use is called Zoomit.  My launching utility is called Launchy and it saves me so much time everyday.  I use ReSharper for Visual Studio nirvana (seriously, get this tool).

Some links I mentioned at the talks:

http://www.csszengarden.com

http://www.exploding-boy.com

http://www.mochikit.com

http://www.prototypejs.org

And finally, my favorite CSS book that I keep recommending to everyone:  CSS Mastery.

Thursday, August 16, 2007

Elegant ASP.NET Caching

So you have a central method that returns some common data, say for example US States.

public IList<State> GetUsStates()

{

    List<State> states = new List<State>();

    using(IDataReader dr = DataAccess.ExecuteReader("SELECT * FROM US_STATES"))

    {

        State theState = State.Fetch(dr);

        states.Add(theState);

    }

 

    return states;

}

Pretty simple stuff, loop over a datareader, building “State” objects based on a row in the database.

Well since this data hardly ever changes and is the same for every user, it is a prime target for caching.  (Psst, if you didn’t know, caching can be one of the most effective performance tuning techniques you can perform — if done correctly).

Now that we want to enable caching, we can create a little helper class that makes it a bit easier to work with…

This is a watered down version of the cache API, but it solves 90% of the cases.

public class CacheHelper

{

    public static bool ItemExists(string key)

    {

        return HttpContext.Current.Cache[key] != null;

    }

 

    public static void Insert(string key, object obj)

    {

        TimeSpan oneHour = new TimeSpan(1,0,0);

        Insert(key, obj, oneHour);

    }

 

    public static void Insert(string key, object obj, TimeSpan span)

    {

        HttpContext.Current.Cache.Add(

            key,

            obj,

            null, //no dependencies

            DateTime.Now.Add(span),

            Cache.NoSlidingExpiration,

            CacheItemPriority.Normal,

            null //no remove callback

        );

    }

 

    public static T Retrieve<T>(string key)

    {

        return (T)HttpContext.Current.Cache[key];

    }

}

Now that we have the utility methods in place, we can alter our US States function to enable caching:

public IList<State> GetUsStates()

{

    string statesKey = "US_STATES";

    if (!CacheHelper.ItemExists(statesKey))

    {

        //add it

        List<State> states = new List<State>();

        using (IDataReader dr = DataAccess.ExecuteReader("SELECT * FROM US_STATES"))

        {

            State theState = State.Fetch(dr);

            states.Add(theState);

        }

 

        CacheHelper.Insert(statesKey, states);

    }

 

    //now it definitely exists in cache

    return CacheHelper.Retrieve<IList<State>>(statesKey);

}

This code quickly gets repetetive and ugly, but it gets the job done.  How can we do better?

We need to be able to provide the means of getting the data, but without actually executing it every time.  This sounds like a good use for a delegate!

In our CacheHelper class we define the delegate:

 public delegate object RetrieveDelegate();

It’s just a method signature that returns an object.

Then we define another method that will first check the cache, and execute the delegate if the data is not there:

public static T GetAndCache(string key, RetrieveDelegate retrieveObject, TimeSpan span)

{

    if (!ItemExists(key))

    {

        object value = retrieveObject(); //this makes the call to the database

        Insert(key, value, span);

    }

 

    return Retrieve<T>(key);

}

Now we have a method that can be smart about caching, but it is completely agnostic of what data to cache.  Now we can refactor our GetStates() method to this:

public IList<State> GetUsStates()

{

    return CacheHelper.GetAndCache<IList<State>>(

        "US_STATES",

        delegate {

            List<State> states = new List<State>();

            using (IDataReader dr = DataAccess.ExecuteReader("SELECT * FROM US_STATES"))

            {

                State theState = State.Fetch(dr);

                states.Add(theState);

            }

            return states;

        },

        TimeSpan.FromDays(1));

}

We only have to interact with the CacheHelper once, thus we only use the cache key once as well.  There are no if statements here either.  Just a single function call that excepts an anonymous method.

This is pretty clean and it makes caching in your application easier.  What do you think?  Do you have any ideas for improvement?  Let’s hear in the comments!

Tags: ,
Wednesday, August 15, 2007

dasBlog 2.0 Released!

The team has been working like mad to get this release out the door and now it’s ready!

http://dasblog.info/

This is a full ASP.NET 2.0 release!   Along with the new release comes a new look for the dasBlog website (designed by me).

Check out the release notes to see all of the great new features.