VB.NET has the reputation of being a second class language in the .NET world. A lot of this has to do with the history of VB and its transformation from VB6 into VB.NET. Conversely, there is a perception that C# is the "real" .NET language, and I think that comes from its (much shorter) history.
At a recent user group meeting, someone joked that VB had been deprecated, and I will admit that I picked up and echoed that joke. I hope that folks could tell that I wasn't serious. When I'm talking to people, I try to point out VB resources where I can -- for example, my favorite Silverlight and WPF books have both VB and C# versions available -- but I'm personally more familiar with the C# resources since those are the ones I use on a day-to-day basis.
Today, VB.NET and C# are pretty much the same language with different syntax (at least that's how I like to think of them). And the great thing about .NET is that whatever language you work with still gets compiled down to the same IL, and you can use assemblies in your project that are created in any .NET language (in fact, you probably don't even know what language a third-party assembly was created with).
Real programmers don't get stuck on syntax. Programmers in general are opinionated and have their tools and languages of choice. Good programmers generally have several different languages under their belts (and not just .NET languages, but things like Ruby, Python, Perl, Delphi, and Java). I have my language of choice (which is currently C#, but has been different in the past), and before I start a task I try to make sure there isn't another tool that would do the job better.
Why the Bum Rap?
So, why does VB.NET have this reputation? My theory is based on looking at the history of .NET. When .NET launched, it was a brand new platform. Along with that launch, Microsoft was promoting a brand new language (C#) that was created just for that platform. In order for .NET to succeed, Microsoft had to get as many people on board as possible. C# was the vehicle they used for most of their demonstrations. This was because C# had all of the capabilities of .NET (at the time). Because of this, C# became equated in many people's minds as the "primary" .NET language.
But Microsoft also knew that there were millions of people invested in VB. They could not succeed if they forced all of the programmers who were comfortable with the VB syntax to switch over to a C-based syntax. And more importantly, they couldn't force those developers to abandon all of their existing code. So, we got VB.NET. And that's sort of where the problems started.
First of all, VB.NET was very different from VB6. There were a number of "features" that were put in to VB.NET to make migration of existing VB6 code easier. But if programmers wanted to really start using the .NET platform to its full potential, they needed to re-write quite a bit of code to fit in with the new paradigm.
VB.NET and C# had quite a few differences in the early versions. There were some constructs in C# that did not have an equivalent in VB.NET (and vice-versa). In addition, Visual Studio tended to favor C# when it came to features such as refactoring and IntelliSense. C# would get these feature updates first, and then they were made available to VB.NET later (as much later as the next release).
Forget Everything You Thought You Knew
But it's time to forget everything you thought you knew about the differences between VB.NET and C#. With the latest release of .NET 4, the languages are almost equivalent; there are a few minor differences, but for all intents and purposes, you can accomplish the same tasks in similar ways.
Steve K. pointed me to this blog article from Steve Wiltamuth regarding the futures of both languages: VB and C# Coevolution. In short, Microsoft is committed to moving both languages forward in the same direction and keep parity in the features and tools (such as the refactoring and IntelliSense features in Visual Studio).
Wrap Up
The good news of the similarities between the languages is that both C# and VB.NET programmers can take advantage of the vast amount of sample code that's available on the net.
Having both C# and VB.NET is great for the .NET development community. C# (and the C-based syntax) provided a comfortable migration for folks using Java and C++; VB.NET provide a comfortable migration path for folks using VB. Together, this has created a mix of developers that can share code and still hang on to their preferred syntax. That sounds like the best of both worlds to me.
Happy Coding!
Thursday, July 8, 2010
Monday, June 28, 2010
Upcoming User Groups
I'll be presenting at a couple of upcoming users groups in the Greater Los Angeles area. Here are the dates and links to the websites:
Tuesday, July 6
LA C# (Manhattan Beach, CA) - http://www.lacsharp.org/
Wednesday, July 7
SoCal .NET (Buena Park, CA) - http://www.socaldotnet.org/
Meetings start at 6:00 p.m., and it's a great chance to interact with other developers in your local area. Hope to see you there!
Tuesday, July 6
LA C# (Manhattan Beach, CA) - http://www.lacsharp.org/
Wednesday, July 7
SoCal .NET (Buena Park, CA) - http://www.socaldotnet.org/
Meetings start at 6:00 p.m., and it's a great chance to interact with other developers in your local area. Hope to see you there!
Sunday, June 27, 2010
Thanks for Coming - SoCal Code Camp San Diego
Thank you to everyone who took the time to attend my sessions at the SoCal Code Camp this weekend. I had a great time doing the presentations, and I hope you found the information useful.
As a reminder, all of my sessions are available on my website here: JeremyBytes.com - Demos.
If you liked the sessions (or didn't like the sessions), feel free to drop me a note at feedback@jeremybytes.com. I'll also be glad to answer any follow-up questions you may have.
Happy Coding!
As a reminder, all of my sessions are available on my website here: JeremyBytes.com - Demos.
If you liked the sessions (or didn't like the sessions), feel free to drop me a note at feedback@jeremybytes.com. I'll also be glad to answer any follow-up questions you may have.
Happy Coding!
Sunday, June 20, 2010
Book Review: Effective C# - Second Edition
I just finished up Effective C#: 50 Specific Ways to Improve your C# (Second Edition) by Bill Wagner. This is a collection of expert tips presentented in a clear and concise manner. These are targeted at the intermediate/advanced developer; it is assumed that you understand the basics of C# programming. With that said, this is an excellent resource for folks like me. Bill Wagner brings to light best practices, some pitfalls, and issues to consider, especially if you are designing libraries/APIs for consumption by other developers.
Overview
This is an updated version of Effective C# (First Edition) and More Effective C#. Each of these covered different versions of the .NET framework. This edition covers C# 4; the content is not limited to "what's new in C# 4." It covers items that go back to the earliest versions of .NET, but also includes new items such as dynamic typing and parallel programming with PLINQ.
As the title suggests, there are 50 "items" (spread over 6 chapters). The book is a fairly brief 300 pages; which translates into an average of 6 pages per item. The items are well-presented with an introduction to the problem space, a recommendation (based on a set of parameters), and clearly written code snippets. Each item is also summarized in a closing paragraph that reiterates the problem and solution.
Here's one thing that I like: Bill Wagner does not say "always do this." Each recommendation includes the pros and cons as well as when you may want to do things one way versus another. Many items will also refer to other items in the book. This helps build a cohesion to the overall text.
Chapters
Here's a quick listing of the chapters with a few items from each to give you an idea of the types of things covered in each:
Item 8: Prefer Query Syntax to Loops
Wagner takes a look at advantages that query syntax (LINQ) has over loops (for, while, do, foreach). He doesn't say that standard loops are bad or that we should stop using them. Instead, he shows some specific examples that illustrate how query syntax can make your code more readable and maintainable.
Personally, I've become a big fan of LINQ. But it did take me a while to get to that point. Wagner challenges the developer to step out of his/her comfort zone (loops) and take a look at query syntax and to consider the difference between the imperative model (telling your code how to do the task) and the declarative model (telling your code what task you want to do).
Item 14: Minimize Duplicate Initialization Logic
Wagner points out the pitfalls of having multiple constructors as part of your class and having "copy/paste" code in each of the constructors. This seems obvious once you think about it; after all, we always strive to minimize duplicate logic. The first tendency may be to move all of the logic into a shared private method, but Wagner points out that this is not the optimum solution. Instead look toward having the simpler constructors (those with fewer or no parameters) call the more complex constructors (those with several parameters).
Then he goes a step further and shows specific cases where you may introduce bugs in your code if you are not careful with how you implement the shared logic. In addition, he takes a look at the efficiency of the code generated by the C# compiler in various situations.
Overall Quality
The overall quality of the text is very good. I did notice a few typos here and there (no one is perfect -- I'm sure you'll also find some typos in this post). There was only one item (#23) that had what I would consider significant issues with the code samples. Fortunately, there is a blog on the SRT Solutions (co-founded by Wagner) web site that lists the errata. Be sure to check this out.
Tech books are notoriously hard to produce due to how quickly technology changes (especially Microsoft technologies). The errors that I noticed were well within the tolerable range and did not distract from my understanding of the content.
Recommendation
I would definitely recommend this book to intermediate and advanced C# developers. There are a number of items (especially in the dynamic and parallel items) that gave me insight into things to watch for as I look into the new features in C# 4. As any developer advances, he/she usually ends up creating shared libraries (shared utilities, for example). Wagner includes many items that cover best practices for creating shared libraries and APIs that are consumed by other developers. This is also helpful when one works as part of of a team on projects that have multiple interoperating assemblies/modules.
So, pick this book up. It has bite-sized chunks of good information and some good tips on new C# features.
Happy Coding!
Overview
This is an updated version of Effective C# (First Edition) and More Effective C#. Each of these covered different versions of the .NET framework. This edition covers C# 4; the content is not limited to "what's new in C# 4." It covers items that go back to the earliest versions of .NET, but also includes new items such as dynamic typing and parallel programming with PLINQ.
As the title suggests, there are 50 "items" (spread over 6 chapters). The book is a fairly brief 300 pages; which translates into an average of 6 pages per item. The items are well-presented with an introduction to the problem space, a recommendation (based on a set of parameters), and clearly written code snippets. Each item is also summarized in a closing paragraph that reiterates the problem and solution.
Here's one thing that I like: Bill Wagner does not say "always do this." Each recommendation includes the pros and cons as well as when you may want to do things one way versus another. Many items will also refer to other items in the book. This helps build a cohesion to the overall text.
Chapters
Here's a quick listing of the chapters with a few items from each to give you an idea of the types of things covered in each:
- C# Language Idioms
Item 3: Prefer the is or as Operators to Cast
Item 5: Always Provide ToString()
Item 8: Prefer Query Syntax to Loops - .NET Resource Management
Item 14: Minimize Duplicate Initialization Logic
Item 15: Utilize using and try/finally for Resource Cleanup
Item 18: Distinguish Between Value Types and Reference Types - Expressing Designs in C#
Item 22: Prefer Defining and Implementing Interfaces to Inheritance
Item 24: Express Callbacks with Delegates
Item 25: Implement the Event Pattern for Notifications - Working with the Framework
Item 32: Avoid ICloneable
Item 35: Learn how PLINQ Implements Parallel Algorithms
Item 37: Construct Parallel Algorithms with Exceptions in Mind - Dynamic Programming
Item 38: Understand the Pros and Cons of Dynamic
Item 40: Use Dynamic for Parameters That Receive Anonymous Types
Item 44: Minimize Dynamic Objects in Public APIs - Miscellaneous
Item 45: Minimize Boxing and Unboxing
Item 47: Prefer the Strong Exception Guarantee
Item 48: Prefer Safe Code
Item 8: Prefer Query Syntax to Loops
Wagner takes a look at advantages that query syntax (LINQ) has over loops (for, while, do, foreach). He doesn't say that standard loops are bad or that we should stop using them. Instead, he shows some specific examples that illustrate how query syntax can make your code more readable and maintainable.
Personally, I've become a big fan of LINQ. But it did take me a while to get to that point. Wagner challenges the developer to step out of his/her comfort zone (loops) and take a look at query syntax and to consider the difference between the imperative model (telling your code how to do the task) and the declarative model (telling your code what task you want to do).
Item 14: Minimize Duplicate Initialization Logic
Wagner points out the pitfalls of having multiple constructors as part of your class and having "copy/paste" code in each of the constructors. This seems obvious once you think about it; after all, we always strive to minimize duplicate logic. The first tendency may be to move all of the logic into a shared private method, but Wagner points out that this is not the optimum solution. Instead look toward having the simpler constructors (those with fewer or no parameters) call the more complex constructors (those with several parameters).
Then he goes a step further and shows specific cases where you may introduce bugs in your code if you are not careful with how you implement the shared logic. In addition, he takes a look at the efficiency of the code generated by the C# compiler in various situations.
Overall Quality
The overall quality of the text is very good. I did notice a few typos here and there (no one is perfect -- I'm sure you'll also find some typos in this post). There was only one item (#23) that had what I would consider significant issues with the code samples. Fortunately, there is a blog on the SRT Solutions (co-founded by Wagner) web site that lists the errata. Be sure to check this out.
Tech books are notoriously hard to produce due to how quickly technology changes (especially Microsoft technologies). The errors that I noticed were well within the tolerable range and did not distract from my understanding of the content.
Recommendation
I would definitely recommend this book to intermediate and advanced C# developers. There are a number of items (especially in the dynamic and parallel items) that gave me insight into things to watch for as I look into the new features in C# 4. As any developer advances, he/she usually ends up creating shared libraries (shared utilities, for example). Wagner includes many items that cover best practices for creating shared libraries and APIs that are consumed by other developers. This is also helpful when one works as part of of a team on projects that have multiple interoperating assemblies/modules.
So, pick this book up. It has bite-sized chunks of good information and some good tips on new C# features.
Happy Coding!
Monday, May 31, 2010
Updated Sessions
I have updated a number of my sessions for Visual Studio 2010 and/or Silverlight 4. I will be presenting three of these sessions at the So Cal Code Camp coming up on June 26 & 27, 2010. These are all available for download here: http://www.jeremybytes.com/demos.aspx.
Introduction to the BackgroundWorker Component with WPF
Long running processes are a user experience killer. How many times have you had an application "lock up" while trying to do some function? The BackgroundWorker component in .NET allows you to spawn those long running processes in the background and keep your WPF, Silverlight, or WinForms user interface responsive. We'll take a look at the features of the BackgroundWorker in a WPF application including running a background process, updating the progress in the UI, and cancelling the process before it has completed.
This session has been expanded to include Exception Handling and additional error checking.
Walkthrough: BackgroundWorker-WPF2010.pdf
Sample Code: BackgroundWorker-WPF2010.zip
Introduction to Data Templates and Value Converters in Silverlight
Business applications are all about data, and laying out that data is critical to creating a good user experience. Silverlight has several tools, including Data Templates and Value Converters, that make this easier for the business developer to manage. By the time we're done, you will have a good understanding of the basics of both of these valuable tools.
This session has been updated for Silverlight 4.
Walkthrough: DataTemplatesAndConverters2010.pdf
Sample Code: DataTemplatesAndConverters2010.zip
Introduction to XAML - WPF 2010 / Silverlight 4
Understanding XAML (eXtensible Application Markup Language) is a key to creating the latest .NET user experiences in WPF and Silverlight. We will introduce the basic concepts around XAML and take a look at various features such as namespaces, elements, properties, events, attached properties and some basic layout. We’ll create a simple WPF or Silverlight application that covers these fundamentals. Although you will probably end up doing most of your UI design with a drag-and-drop tool such as Expression Blend, knowing the internals gives you a leg up in making the final tweaks to ensure an excellent user experience.
This session has been updated to include both WPF and Silverlight versions. The same core XAML features are covered in each environment.
Walkthrough (WPF): IntroToXAML-WPF2010.pdf
Sample Code (WPF): IntroToXAML-WPF2010.zip
Walkthrough (Silverlight): IntroToXAML-Silverlight4.pdf
Sample Code (Silverlight): IntroToXAML-Silverlight4.zip
As always, your feedback/questions on any of these sessions is appreciated: feedback@jeremybytes.com.
Happy Coding!
Introduction to the BackgroundWorker Component with WPF
Long running processes are a user experience killer. How many times have you had an application "lock up" while trying to do some function? The BackgroundWorker component in .NET allows you to spawn those long running processes in the background and keep your WPF, Silverlight, or WinForms user interface responsive. We'll take a look at the features of the BackgroundWorker in a WPF application including running a background process, updating the progress in the UI, and cancelling the process before it has completed.
This session has been expanded to include Exception Handling and additional error checking.
Walkthrough: BackgroundWorker-WPF2010.pdf
Sample Code: BackgroundWorker-WPF2010.zip
Introduction to Data Templates and Value Converters in Silverlight
Business applications are all about data, and laying out that data is critical to creating a good user experience. Silverlight has several tools, including Data Templates and Value Converters, that make this easier for the business developer to manage. By the time we're done, you will have a good understanding of the basics of both of these valuable tools.
This session has been updated for Silverlight 4.
Walkthrough: DataTemplatesAndConverters2010.pdf
Sample Code: DataTemplatesAndConverters2010.zip
Introduction to XAML - WPF 2010 / Silverlight 4
Understanding XAML (eXtensible Application Markup Language) is a key to creating the latest .NET user experiences in WPF and Silverlight. We will introduce the basic concepts around XAML and take a look at various features such as namespaces, elements, properties, events, attached properties and some basic layout. We’ll create a simple WPF or Silverlight application that covers these fundamentals. Although you will probably end up doing most of your UI design with a drag-and-drop tool such as Expression Blend, knowing the internals gives you a leg up in making the final tweaks to ensure an excellent user experience.
This session has been updated to include both WPF and Silverlight versions. The same core XAML features are covered in each environment.
Walkthrough (WPF): IntroToXAML-WPF2010.pdf
Sample Code (WPF): IntroToXAML-WPF2010.zip
Walkthrough (Silverlight): IntroToXAML-Silverlight4.pdf
Sample Code (Silverlight): IntroToXAML-Silverlight4.zip
As always, your feedback/questions on any of these sessions is appreciated: feedback@jeremybytes.com.
Happy Coding!
Labels:
.NET,
BackgroundWorker,
Data Template,
Silverlight,
Threading,
Value Converter
Saturday, May 15, 2010
So Cal Code Camp - San Diego Coming in June
The So Cal Code Camp is coming to San Diego June 26th & 27th. As always, Code Camp is FREE! It's a great chance to get some training and hook up with other developers / coders / hackers in your area. I'll be presenting a few sessions, so it's your chance to see me, too.
Hope to see you there!
Hope to see you there!
Thursday, April 29, 2010
More Thoughts on ASP.NET MVC
I've had two months to work with ASP.NET MVC since my last post on the topic. Since then, I've worked through two projects and have picked up some good experience. There are plenty of pros and cons (more pros in my opinion). Let's take a look at how it differs from other .NET web technologies.
Routing
ASP.NET MVC is more than just Model-View-Controller pattern (the MVC which lends its name). One of the key features is routing. With routing, a URL does not point to a physical resource on the server. Instead, it contains information that allows the Controller to instantiate the appropriate Model and send the data to a specific View. You're probably familiar with the pattern. Let's take a look at the URL for my previous post: http://jeremybytes.blogspot.com/2010/02/new-to-me-aspnet-mvc.html.
The first part is (http://jeremybytes.blogspot.com) points to the server. The next part (2010) would normally be parsed as a physical path (file folder) on the server. But instead, it is a parameter that references the year of the post. The same is true of the "02" portion (the original post is from February 2010). The final part is the name of the article. Now, I can't tell you what lies behind the blogspot link or how it is parsed, but I'm pretty sure that there are no physical directories that refer to the year and month of my posts.
You use this same type of routing in the ASP.NET MVC world. The default is for a URL to take the form of {controller}/{action}/{id}, but you can alter this default implementation however you like. As an example: http://www.example.com/sales/customer/217. This would call the "Sales" controller and ask for Customer #217.
As mentioned previously, this is an "action-first" or "resource-first" model (as opposed to WebForms "page-first" model). I say "action" or "resource" because that will depend on what you are doing. In the above example, we are requesting a specific Customer resource. But we could just as well be requesting an action, such as "UpdateCustomer".
This strikes me as very REST-ful, although that is a topic for another time. The good news for those who like the idea of routing but aren't ready to dive into the rest of ASP.NET MVC: Routing is included in ASP.NET 4.0 (it's actually also available somewhat in 3.5 but requires some extra work).
ASP.NET MVC vs. WebForms: Repeaters
I spent 3 years developing WebForms apps, so I've tried quite a few different techniques for displaying data. The control I ended up liking best is the Repeater. This gives me the most flexibility in laying out my data. But it does have one severe limitation: you cannot nest Repeaters.
The idea of a Repeater is that it will loop through your data set and "repeat" a specified section for each record. This is fine for single level lists, but it gets more complex when you have parent-child relationships.
Let's say that I have data that includes Category, Sub-Category, and Details. I only want to display the Category label at the top of each Category (not on each record). The same is true for Sub-Category. But since I can't nest Repeaters, that means that I must include Category, Sub-Category, and Detail in every single one of my records (flattened data rather than a hierarchy). Then, to get the display that I want, I hook into the Event that runs before displaying each record. In that event handler, I check to see if the current Category is the same as the Category of the previous record. If so, then I suppress (hide) the Category display. Same for Sub-Category. This creates quite a bit of messy, conditional code.
ASP.NET MVC handles this situation entirely different. You are much closer to the metal. So, if I wanted to implement the above scenario, it's quite a bit more elegant. In the View, I simply have a foreach loop that goes through all of the Categories and displays the Category header. Inside there, I have a nested loop that goes through the Sub-Categories and displays that. And inside there, I have a nested loop that goes through the details. This means that I can have a much more natural structure to my data (Model) with a parent-child-grandchild relationship. Add some LINQy goodness, and you have an easily understandable solution without the messy conditionals.
ASP.NET MVC vs. WebForms: File Size
Yes, file size is still important -- just take a look at how prominent smart phones and other mobile devices are becoming. I took an existing WebForms application and converted it to ASP.NET MVC. This was a proof-of-concept so I could try out the technologies. Since the existing application had a well-defined business layer and clear separation from the UI, it was easy to put the ASP.NET MVC front end in place.
Here's what I found: a particular page on the WebForms apps that was 24KB was only 9KB in the ASP.NET MVC version!
I know your initial reaction: just turn off ViewState, moron. But ViewState was turned off. The WebForms page is so much bigger because it uses server-generated names for all of the controls. This can look like "ctl00_mainRepeater_headerLabel_001". When you multiply this by the number of controls for each record and the number of records in the data set, it all adds up.
Conversely, the majority of the ASP.NET MVC output is text -- the equivalent of using a Response.Write instead of using a server-side control. When you look at the output (view source in the browser), it looks like hand-coded HTML rather than machine-generated code. This will vary depending on how you code up your Views, of course. My experience is that the output is pretty straight forward compared to WebForms output.
ASP.NET MVC vs. Silverlight
I won't really get into this debate. Both technologies have their uses and benefits. I was recently listening to .NET Rocks! and heard about a "challenge" that took place at the Visual Studio 2010 Launch Event. Apparently Phil Haack (and team) and Rocky Lhotka (and team) were tasked with creating an application in ASP.NET MVC and Silverlight, respectively. I have a great deal of respect for both of these guys, so I'll just leave that discussion there.
After using Silverlight myself, I was determined that I would never create another WebForms app again (the programming style is just so much more natural). But there is a problem (mentioned above): mobile users.
The reason that I started using ASP.NET MVC is because I needed to create a solution for Blackberry users. And I'm not talking about the shiny-new Blackberry Bolds. I'm talking about (relatively) old devices with browsers that are a step above WAP. Obviously, Silverlight was not an option. ASP.NET MVC, however, allowed me to put together a clean and efficient application.
One Last Thing: Parameters
There are a number of things I like about ASP.NET MVC, but I'll wrap up with one item: Action parameters. The ASP.NET MVC framework does everything it can to automatically pull in the parameters for you.
Let's say that I have an Action (method) like this: UpdateCustomer(int Id, string firstName, string lastName). When this method gets called, the framework tries to populate the parameters from the following locations:
Wrap Up
I've grown to like ASP.NET MVC. At a later date, I'll put together a case study with my actual code to give you a better idea of exactly how the technology works. For now, we'll just stay with what we've discussed so far.
ASP.NET MVC 2 is now shipping as part of Visual Studio 2010. I've only taken a cursory look at it, but it seems to have added some good features to make views even easier and cleaner to generate. Plus, having it included in Visual Studio means that other members of your team will also have it available without having to install the bits separately. If you're doing web programming, this is definitely something to look into.
Happy Coding!
Routing
ASP.NET MVC is more than just Model-View-Controller pattern (the MVC which lends its name). One of the key features is routing. With routing, a URL does not point to a physical resource on the server. Instead, it contains information that allows the Controller to instantiate the appropriate Model and send the data to a specific View. You're probably familiar with the pattern. Let's take a look at the URL for my previous post: http://jeremybytes.blogspot.com/2010/02/new-to-me-aspnet-mvc.html.
The first part is (http://jeremybytes.blogspot.com) points to the server. The next part (2010) would normally be parsed as a physical path (file folder) on the server. But instead, it is a parameter that references the year of the post. The same is true of the "02" portion (the original post is from February 2010). The final part is the name of the article. Now, I can't tell you what lies behind the blogspot link or how it is parsed, but I'm pretty sure that there are no physical directories that refer to the year and month of my posts.
You use this same type of routing in the ASP.NET MVC world. The default is for a URL to take the form of {controller}/{action}/{id}, but you can alter this default implementation however you like. As an example: http://www.example.com/sales/customer/217. This would call the "Sales" controller and ask for Customer #217.
As mentioned previously, this is an "action-first" or "resource-first" model (as opposed to WebForms "page-first" model). I say "action" or "resource" because that will depend on what you are doing. In the above example, we are requesting a specific Customer resource. But we could just as well be requesting an action, such as "UpdateCustomer".
This strikes me as very REST-ful, although that is a topic for another time. The good news for those who like the idea of routing but aren't ready to dive into the rest of ASP.NET MVC: Routing is included in ASP.NET 4.0 (it's actually also available somewhat in 3.5 but requires some extra work).
ASP.NET MVC vs. WebForms: Repeaters
I spent 3 years developing WebForms apps, so I've tried quite a few different techniques for displaying data. The control I ended up liking best is the Repeater. This gives me the most flexibility in laying out my data. But it does have one severe limitation: you cannot nest Repeaters.
The idea of a Repeater is that it will loop through your data set and "repeat" a specified section for each record. This is fine for single level lists, but it gets more complex when you have parent-child relationships.
Let's say that I have data that includes Category, Sub-Category, and Details. I only want to display the Category label at the top of each Category (not on each record). The same is true for Sub-Category. But since I can't nest Repeaters, that means that I must include Category, Sub-Category, and Detail in every single one of my records (flattened data rather than a hierarchy). Then, to get the display that I want, I hook into the Event that runs before displaying each record. In that event handler, I check to see if the current Category is the same as the Category of the previous record. If so, then I suppress (hide) the Category display. Same for Sub-Category. This creates quite a bit of messy, conditional code.
ASP.NET MVC handles this situation entirely different. You are much closer to the metal. So, if I wanted to implement the above scenario, it's quite a bit more elegant. In the View, I simply have a foreach loop that goes through all of the Categories and displays the Category header. Inside there, I have a nested loop that goes through the Sub-Categories and displays that. And inside there, I have a nested loop that goes through the details. This means that I can have a much more natural structure to my data (Model) with a parent-child-grandchild relationship. Add some LINQy goodness, and you have an easily understandable solution without the messy conditionals.
ASP.NET MVC vs. WebForms: File Size
Yes, file size is still important -- just take a look at how prominent smart phones and other mobile devices are becoming. I took an existing WebForms application and converted it to ASP.NET MVC. This was a proof-of-concept so I could try out the technologies. Since the existing application had a well-defined business layer and clear separation from the UI, it was easy to put the ASP.NET MVC front end in place.
Here's what I found: a particular page on the WebForms apps that was 24KB was only 9KB in the ASP.NET MVC version!
I know your initial reaction: just turn off ViewState, moron. But ViewState was turned off. The WebForms page is so much bigger because it uses server-generated names for all of the controls. This can look like "ctl00_mainRepeater_headerLabel_001". When you multiply this by the number of controls for each record and the number of records in the data set, it all adds up.
Conversely, the majority of the ASP.NET MVC output is text -- the equivalent of using a Response.Write instead of using a server-side control. When you look at the output (view source in the browser), it looks like hand-coded HTML rather than machine-generated code. This will vary depending on how you code up your Views, of course. My experience is that the output is pretty straight forward compared to WebForms output.
ASP.NET MVC vs. Silverlight
I won't really get into this debate. Both technologies have their uses and benefits. I was recently listening to .NET Rocks! and heard about a "challenge" that took place at the Visual Studio 2010 Launch Event. Apparently Phil Haack (and team) and Rocky Lhotka (and team) were tasked with creating an application in ASP.NET MVC and Silverlight, respectively. I have a great deal of respect for both of these guys, so I'll just leave that discussion there.
After using Silverlight myself, I was determined that I would never create another WebForms app again (the programming style is just so much more natural). But there is a problem (mentioned above): mobile users.
The reason that I started using ASP.NET MVC is because I needed to create a solution for Blackberry users. And I'm not talking about the shiny-new Blackberry Bolds. I'm talking about (relatively) old devices with browsers that are a step above WAP. Obviously, Silverlight was not an option. ASP.NET MVC, however, allowed me to put together a clean and efficient application.
One Last Thing: Parameters
There are a number of things I like about ASP.NET MVC, but I'll wrap up with one item: Action parameters. The ASP.NET MVC framework does everything it can to automatically pull in the parameters for you.
Let's say that I have an Action (method) like this: UpdateCustomer(int Id, string firstName, string lastName). When this method gets called, the framework tries to populate the parameters from the following locations:
- Routing Parameters: These are the parameters that appear as part of the URL "path", such as the "217" in the Customer example above.
- Query String: These are additional parameters that are part of the URL query string. These are separated from the rest of the URL with a question mark and take the form name=value (separated by ampersands).
- Form Data: These are pulled from fields that are posted back in a form.
- Post Parameters: These are the parameters provided as part of a POST (not necessarily part of a form).
- Header Information: These items can be pulled from the request header.
Wrap Up
I've grown to like ASP.NET MVC. At a later date, I'll put together a case study with my actual code to give you a better idea of exactly how the technology works. For now, we'll just stay with what we've discussed so far.
ASP.NET MVC 2 is now shipping as part of Visual Studio 2010. I've only taken a cursory look at it, but it seems to have added some good features to make views even easier and cleaner to generate. Plus, having it included in Visual Studio means that other members of your team will also have it available without having to install the bits separately. If you're doing web programming, this is definitely something to look into.
Happy Coding!
Subscribe to:
Posts (Atom)