Wednesday, December 16, 2009

I'm All About ASP.NET MVC

Tomorrow, when I walk the halls of my corporate job and find myself caught in an eye-to-eye stare-down with a Java web developer I may not be thinking the same thoughts. I've had my share of Java vs. .NET arguments over the years and I hate to admit it but the Java people have a lot going for them. Often times Java is the runway for .NET's future look. Thus it is to no surprise now that we've gotten our hands on ANT, Hibernate, and jUnit we follow up by stealing Swing. .NET makes its rounds with all of Java's daughters--which happens to be one of my favorite interjections in a .NET vs Java discussion. You should see their faces.

What is ASP.NET MVC?

Every ASP.NET developer I've talked to in the last few days about MVC have asked me this question, which kinda surprised me. In general, many of them have never heard of MVC at all. My first interaction with MVC occurred after reading an article over at A List Apart about JavaScript MVC--which is my preferred client-side architecture. Great article.
MVC stands for Model-View-Controller. When you think about web work, isn't it generally you got some data(Model) that you present to the user(View) and allow them to interact with(Controller)? I know that about sums up my work experience. ASP.NET MVC is .NETs response to the Java/Ruby MVC craze. All us .NET-ers are definitely a few seasons behind.
Remember when the .NET web platform released? Almost a decade ago. Honestly though, the web was still emerging as a platform for applications. In my opinion, when Microsoft released ASP.NET they were thinking "how can we easily convert our application developers into web developers" and not "how can we make the best web development platform out there?" They've reaped the consequences for it too-- such as the ViewState, lack of true architecture guidelines, the page life-cycle, oh and how about their ASP.NET Ajax(Atlas) implementation? Horrendous. All ease of use and no performance. ASP.NET MVC is Microsoft's way of trying to come clean. Let's try to be more forgiving.

Bottom Line: Whats the Code Like

Amazing. Simply amazing. I've been working through the Wrox Professional ASP.NET MVC book and have over and over again found myself making "exactly!" outbursts. I'm not going to go through a complete overview of the MVC framework, but here are a few "highlights:"

Using LINQ to SQL as Your Model

ORMs (object relational mappers) are pretty popular right now--especially NHibernate. No surprise, they save you a ton of time defining classes and writing SQL statements. After you have a database table set up and accessible in your Visual Studio Database Explorer, a little Solution Explorer right-click add-new > Data > LINQ to SQL and you're rolling. With the class that is created, one can alter database data by easily interacting with the generated class. Like:

// Retrieve Dinner object that reprents row with DinnerID of 1
Dinner dinner = db.Dinners.Single(d => d.DinnerID == 1);

// Update two properties on Dinner
dinner.Title = "Changed Title";
dinner.Description = "This dinner will be fun";

// Persist changes to database

And yes, it supports transactions, SPROCs, views, checks your data for SQL Injection attacks, and is easily extendable using partial classes and partial methods. Not really an MVC feature, but new to me.

ASP.NET MVC HTTP Post Handling

This is one of the things that really impressed me. A situation I find myself programming over and over again is doing GridView FindControl()s to grab an inputted value. With MVC, you can create a method in your controller that accepts one of your model classes, completely avoiding all of the monotonous value/control finding work. The values are automatically mapped using .NET Reflection.

public ActionResult Create(Dinner dinner)
if (ModelState.IsValid)
dinner.HostedBy = "SomeUser";
return RedirectToAction("Details", new { id = dinner.DinnerID });
return View(dinner);

Theres More

I didn't even get to talk about Validation, separation of concerns, SEO-friendly URLs and more but... I need to get back to studying.

Tuesday, December 15, 2009

Using the YAML CSS Framework in ASP.NET

I've written the same CSS code at least a million times-- center the body, float the navigation, fix IE6--but I'm never going to do it again. Why? Because recently I've stumbled upon CSS Frameworks. Amazing stuff!

What is a CSS Framework?

Its kind of like a set of web page building blocks. Remember playing with Lincoln Logs as a child? They were great. However, imagine if instead of all that pre-cut goodness you had to fashion your own pieces. You'd be missing fingers! (Who gave that kid a knife?) Or bare minimum, trading play time for work time! Strangely enough, developers do just so. Essentially they are ignoring the vast amount of browser-specific tweaking that web design necessitates. Aren't there other areas of your project you'd rather be working on (like the ones that actually demand originality)?

The YAML CSS Framework

The folks over at have run their product through the browser-specifc gauntlet. Emerging unscathed is a solid, well-thought, and well-documented package that you can quasi-drop into your web application. I need to reiterate the "well-documented." In fact, if I was teaching a class on web design I would use the framework's free pdf as it's textbook. Don't know what a float is? Or why they're not working in IE6? Any CSS novice should check it out. Unfortunately I did just write quasi-drop...

The Downside of the YAML CSS Framework

It's not all roses. In fact, its rather intimidating to jump into. The first time I downloaded it I felt as though the css files had been arranged by Stephanie Toppin(art featured). After consulting the documentation I was finally able to see the method through the madness. To elaborate on said madness:
  1. The framework relies heavily on CSS imports-- an Ajaxian no-no.
  2. The ultra-cool form styles rely on setting the <form> tag's class. (You know, that thing in ASP.NET that usually surrounds the entire page.) That is also a no-go.
  3. The folder structure makes me want to pull my hair out. I'm serious.

Making it Work in ASP.NET

To start out, lets put all the files in one place. Not only does this remove our CSS import issues, but also will decrease our HTTP requests and therefore improve our page's performance. So, that means:
  1. Taking YAML's base.css, content.css, form.css, and print.css and putting all their contents into one file. Done and done. Situation=averted. You will still need to reference the IE-specific fixes page separately, however.
  2. In order to rectify our form tag issues, all we need todo is change all the code that says form.yform to just .yform. Easy! Now us .NET-ers can wrap our wannabe forms in a div.yform and reap the rewards of all of YAML's pre-styled goodness.
I tend to keep all of my custom css classes in a section at the bottom of my concatenated YAML document.

Get Back to Work

... on things that deserve your attention!

Friday, November 13, 2009

jQuery & .NET WebMethods: An Introduction

At some point in my programming I began to dislike the .NET page life-cycle. Sometimes I feel as though it was Microsoft's way of trying to impose a structure on something that really didn't need a structure. PHP and Java Servlets have proved this.

Regardless, with the advent of .NET AJAX WebMethods one can skip the life-cycle. For those of you who have been living in a cave for the last few years: 1) Your beard rocks. 2) AJAX (Asynchronous Javascript and XML) basically means that the web browser has a new role. In the old days, the browser would make a request and the server would send it an entirely new page for it to spit at the user. With AJAX, the browser sends a request and the server returns data, and then the browser performs actions on that data (like applying logic to the data and then updating page content). With AJAX the browser is in on the action; it is no longer just a middleman.

Setting Up Your First WebMethod

How do you add a WebMethod to your .NET page-behind code? Check out this code:

public static string SayHi()
return "Hi";

If you were to add this code as well as import System.Web.Services, you could call this function from your client-side JavaScript. No page life-cycle, no post-back; just a request for some data and a response. Using jQuery, the JavaScript code for this would look something like:

//this is the same as jQuery's $(document).ready([function])
//which means that it will call this function as soon as the page is loaded
$(function() {
type: "POST",
//notice we put the page name and the function name here
url: "default.aspx/SayHi",
//the json data to send to the server (we'll discuss later)
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
//if the request is a success do something with the data
success: function(msg) {
//this alert box would say hi
//this paragraph with id="hiparagraph" would say hi
//this textbox with class="hitextbox" would say hi
//if the request is a failure, blame the user
error: function(xhr, textStatus, exception) {
alert('You are a failure.');

I know what you're thinking-- wow this is boring. And it is at this point. However, if you were to ask .NET to do this the old fashioned way, with a label and some code-behind assign-age I bet it would take twice as long-- maybe longer. In my experience, I have seen request/response times get cut to 1/10th (even 1/20th) the original time by using jQuery and WebMethods. For real.

What is JSON and What Happened to the XML?

All I know is that I haven't used XML directly yet in an AJAX call. JSON is JavaScript Object Notation. Its simple to learn-- check out this page for a little background.

What can you send or receive in the JSON? Short answer: anything. In our example we sent nothing, and received a string. With AJAX calls you can send any sort of JavaScript object. As for what you can receive, feel free to use any of the .NET generic types and any of your own custom made classes-- .NET will translate them into JSON for you.

In Conclusion

Now that we have a better way of communicating with the server, what can we do with it? In the next post we will get into some advanced scenarios and techniques with jQuery and .NET WebMethods.

Thursday, November 12, 2009

The Best Indie Albums of 2009

It is definitely the best time of the year.

If you're anything like me at all you have christened each new year by scouring magazine after magazine after online list in search of new music. Its so easy to do now-- especially with the mass amounts of online blog authors spitting out opinions.(eh-heh) So here it is-- the best indie albums of 2009. Get caught up! Find a new love!

The Top Indie Albums of 2009 in random order

The Dirty Projectors - Bitte Orca

Truly unique! Amazing! I first heard the Dirty Projectors on the Dark is the Night compilation. On this cd I can hear traces of Led Zeppelin III, as well as hip-hop and R&B influences. Which is more amazing-- the intricate, melodic guitar work or the dead-on vocal harmonies? You decide. Regardless, you can put the songs Two Doves and No Intention on my favorites list.

Grizzly Bear - Veckatimist

I really hesitate to put this one up here. Its not that I think it doesn't deserve to be here, or that I should leave it off because every other critic is going to pick it. Its because of the cd's mood--dark and haunting--seriously. At times I've had to turn it off and put on something happier. That being said, this cd is pure genius. There are few albums I listen to where I feel as though each note, effect, and instrument were precisely chosen for the exact moment; which is the way I feel about this one. (the last time being Amnesiac, I believe) If you haven't peeped the youtube video for Ready, Able, do peep my friend. So put Ready, Able and While You Wait for the Others on my favorites list.

M Ward - Hold Time

Otherwise known as the happiest, most gratitude-filled album of all time, Hold Time is the album to put on after Veckatimist. I guess in that sense its like Jack Johnson, except Mr. Ward has style and I don't want to bludgeon him with his own acoustic guitar. Its a simple sounding, honest, soulful, up-building album. For real though, this album is indie Prozac. So take lots with alcohol, and put the songs For Beginners and Blake's View on my favorites list.

Ramona Falls - Intuit

I always have room to hear someone mixing electronic, rock, and acoustic all on the same track. Ramona Falls is one of the best at doing so. If you don't believe me, find some youtube video featuring the song Clover-- expertly done. Additionally I like the fact that he used the "scarcely used, but catchy and ambiguous" lyrics formula. Its beautiful. Put Clover and The Darkest Day on my favorites list.

The XX - xx

The Cure. That's really all I need to say. Do you like The Cure? Then get its electronic reincarnate here. Simple and laid back. I really like how this band has a girl and guy singer that volley lyrics around. Put VCR and Heart Skipped a Beat on my favorites list.

Beirut - Realpeople Holland & March of the Zapotec

I haven't been this jealous in a while. For real though, to be able to gain mastery over both the electronic and Godfather's-soundtrack scenes is beyond my ability as a musician. The strangest part-- that the two can and do mix together so well. Its difficult to explain without sounding like I'm trying to sound like I know what they're doing. And i don't. So just listen to it. Put La Llorona and My Night with the Prostitute from Marseilles on my favorites list.

Passion Pit - Manners

At first I was turned off by this band's vocal style because it seemed borderline whiney. You see, I threw my studded belts away years ago. Regardless, a few listens later I noticed that I was completely in love with their catchy synth leads and child-choir goodness. There will be no second coming of The Postal Service-- but this is good enough. Put Little Secrets and Swimming in the Flood on my favorites list. BTW, this makes a great running cd.

Honorable Mentions

Camera Oscura - My Maudlin Career
Animal Collective - Merriweather Post-Pavillion
The Black Atlantic - Reverence for Fallen Trees
Edward Sharpe & The Magnetic Zeros - Edward Sharpe & The Magnetic Zeros
Yeah Yeah Yeahs - It's Blitz!
Wilco - Wilco

...what did I forget?