Welcome to Professional ASP.NET - Chris Love's Official Blog Sign in | Join | Help

Chris Love's Official ASP.NET Blog

Chris Love's Helpful tips, tricks and pragmatic development knowledge for the ASP.NET world.
Add to Technorati Favorites


ASP Insider Follow Me On Twitter
Things I Hate About .NET

I hate several things about programming in the .NET stack, well not really that they affect me now. But it is really some of the ways we teach new .NET programmers to program in the .NET stack. Primarily it relates to the way we teach newbies how to manager data access with the View and DataSource controls. Beyond that it is that far too often we teach by showing direct SQL calls instead of using more secure and optimized stored procedures. So here are some rules that .NET programmers need to learn to live by.

Never Use a View Control for Production

The GridView, ListView, FormView and DetailsView controls are not for production. They are for proof of concept and checking data during the early development cycle. Never let them go beyond that point. They not only produce a lot of useless code that take extra time to send across the wire, they are hard to customize. I have never met a client that wanted what any of these view controls produced on their sites.

By the time you customize the layout of these controls to meet the customer's desire, you could have easily used a repeater or just laid the markup out anyway. In fact it will be easier to maintain and still send much less across the wire.

Never Use a DataSource Control

While these can be a quick out to bind to a data control, they ultimately are completely unmaintainable and not very optimized. Think about it if you use a SQLDataSource on one page and then start copying and pasting it around your site for the same exact SQL statements, you will eventually make a nightmare. If you need to modify any of the SQL statements, you have to run through your entire site modifying each and every statement on each and every page. This is ultimately a production disaster that will happen very quickly in the development process if you rely on them.

Never Ever Make a Direct SQL Call

Stored Procedures should always be used for any SQL statements. First they are compiled and optimized for optimal performance. Second this will eliminate the chances of a SQL Injection attack. There is honestly no reason any ASP.NET site should ever be the victim of a SQL Injection attack. If you are, then you should fire your developers on the spot!

Using stored procedures also gives you a single place to maintain the interactions with your data. You also get great SQL tools like the SQL profiler and show plans to help you optimize the queries. On this topic, I am becoming less and less enamored with LINQ to SQL, because those queries just are not optimized, but that is another post for another day.

What Should You Do?

Well now that I have taken away the crutches how are you going to walk? Well first get comfortable with the Repeater control and making your own layouts for detail pages. You will quickly find this is very easy to work with. I use CodeSmith to generate my base layouts for both and I highly recommend using a code generator to help you be consistent.

Create a common data access layer to manage direct interactions with the database. I use the Data Access Application Blocks. I even have a wrapper class that I created to abstract away how to do direct SQL access. If I had to write code to retrieve a SQLDataReader I would fail, I have not done it in years!

Using these techniques will make you a much more efficient programmer, eliminate many long term maintenance issues and make your applications much more performant. It will also make customized layouts much easier to achieve. Ultimately your customer will be happier with you.

Share this post :
Posted: Sunday, March 30, 2008 6:41 PM

by Chris Love

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com
# March 30, 2008 8:01 PM

Bart Czernicki said:

Nice article (can't disagree with you...especially about the SQLDataSource and now LINQDataSource)...however when I clicked on the article I thought I would be taken to a rant about .NET not about ".NET is not tailored to teach new programmers correctly"
# March 30, 2008 8:22 PM

John S. said:

First two points, right on. "Stored Procedures should always be used for any SQL statements. First they are compiled and optimized for optimal performance. Second this will eliminate the chances of a SQL Injection attack." Two problems here. Your argument about optimization is based on out-dated information. Since SQL Server 7, all queries no matter their origin are cached. Second, using stored procedures in and of itself does not prevent SQL injection attacks. See http://bloggingabout.net/blogs/adelkhalil/archive/2008/01/06/the-myth-of-stored-procedures-preference.aspx
# March 31, 2008 12:11 AM

John S. said:

As a follow up to my previous comment...I'm not advocating ad hoc SQL sprinkled all over your app. Instead you should be using some sort of ORM in combo with a 2- or 3-tier architecture (for small projects, building a Data Access Layer in App_Code with something like SubSonic is usually plenty sufficient).
# March 31, 2008 12:20 AM

Onur Gumus said:

Unfortunately all your points are incorrect. I'll tell you why: Never Use a View Control for Production "they are hard to customize. " you said. Formview has no built in templates. You must customize Formview it has no other point. We have been using Gridview extensively for our production code. It really shines when you use custom templates. ListView also is a control that YOU MUST customize the control. "By the time you customize the layout of these controls to meet the customer's desire, you could have easily used a repeater or just laid the markup out anyway" Repeaters are good for certain tasks. But imagine you need paging and sorting with editable fields. It would be extremely hard to use repeaters there. A GridView will be a much better solution: "Never Use a DataSource Control" You know SQLDataSource is not the only DataSource available. There are 3 others built in by microsoft. ObjectDataSource, XmlDataSource and AccessDataSource. However you can also build yours. In our solution we use a modified object data source which is much better than current ObjectDataSource. And we are very happy with it. For SQLDataSource I agree it leads to bad design. But it is still nice to have for quick prototyping "Never Ever Make a Direct SQL Call" This is partially incorrect as well. Although inline sql is not good for me either, ther are other solutions like NHibernate, Subsonic, Castle Active Record which are much better than linq to sql as a well as stored procedures. Stored Procedures have 3 advantages. Protection for Sql Injections : Which is not a big deal for asp.net programming anyway. Speed: Inlinequeries are cached as well. So mostly performance difference is negiligable. Adding another layer: This is a 2 edged sword. You can modify your sp without modifying your code. However this in turn results your business code leaks into your SP's. My suggestion stay away from SP's unless you really have to use them.
# March 31, 2008 2:31 AM

Chris Love said:

Paging and sorting can be done with Repeaters, I do it all the time. I also strongly disagree with using a tabular control to edit records. This is another bad technique that I plan on covering in another post sometime in the near future.

I have no problem putting basic business logic in the database, it is often a good place to keep it, since it is at a low level and a good place to abstract some logic.

# March 31, 2008 7:38 AM

Onur Gumus said:

"I have no problem putting basic business logic in the database, it is often a good place to keep it, since it is at a low level and a good place to abstract some logic." This is a big problem actually. First , you cannot write unit tests for your code. 2nd SQL is a terrible language compared to C#. I would much prefer my business code to be in C# rather than SQL. Third , it would be very hard to debug your code if you leak business logic to your SP's. 4th, It is also harder to read and maintain the code since the business code would be sparsed among layers instead of residing it's own layer.
# March 31, 2008 8:34 AM

David said:

Well, I think this should be titled "Things I hate about ASP.NET". .NET alone refers to the whole framework, and I don't have any problems using the *View controls in a Winforms application. That said, I agree with John S.: stored procedures used to be cool a while ago, but nowadays it's just better to get a proper DAL (using EntitySpaces or CodeSmith, or NHibernate) than using stored procedures. Much more flexibility and SQL Injection protection for free. Cheers
# March 31, 2008 11:00 AM

tony petruzi said:

@chris, i'll agree with you that the database is a good place to keep some business logic, however i will strongly disagree with you that it should be thrown into stored procedures. personally i put most business logic into views and then use classes to mash up the views with table i'm retrieving. some don't like it, i do. i hate having a large amount of business logic within one large stored procedure that is hard to follow and individual parts would have to be extracted if you wanted to reuse them throughout your application. You can inner join a stored procedure to a table so you have to include the table within your stored procedure. also the fact that now you have to continually move to your database in order to modify a query is a PITA all itself. plus how do you know that modifying the stored procedure you want won't affect other's people's code? all and all using a good orm and views can get you the same results as using stored procedure, however it's more maintainable and portable. i really think that stored procedure are a thing of the past. they were great in the old days when you need to squeeze performance, but since every statement is cached now, there's no need for them. oh and about the sql injection thing... parameterized queries give you the same level of security.
# March 31, 2008 11:01 AM

Cihan Ucar said:

I agree with you except your point of view about creating the data access layer with template generators. I know that CodeSmith is a great toll but you should also know how to retrieve data using SqlDataReader etc. Except this, I totally aggree with you. @Onur Gumus I think some of your suggestions are obviously wrong. First of all, GridView, FormView etc. are heavy controls which prints lots of unnecessary markups. Personally I think they are for lazy programmers. They can be easily replaced by another controls such a Repeater which is relatively faster. Putting your business logic in database is considered to a good practice. Inline Sql is cached as well, but what is the point of writing your same inline queries in different pages aganist the same database? Using stored procedures is aways a better solution than inline queries. Not just sql injection protection or caching, you can also protect your database within its own authentication? ( Are you assigning dbo (or root, sys etc. ) access to your application? ) What if your application is leaked? Specially on enterprise applications, not to use stored procedures are just nothing more that self suicide.
# March 31, 2008 12:19 PM

Kevin Jensen said:

I pretty much disagree with everything you said as well. I have used gridview successfully in many production situations and performance is always rock solid. "Never use a DataSource Control". I don't use them but I have no problem with the ObjectDataSource. I agree, SQLDataSource is terrible. "Never Ever Make a Direct SQL Call". I could disagree with you more. There is no need to expand on this statement, as there are 40,000,000 blog entries where people battle back and forth.
# March 31, 2008 12:22 PM

Deane said:

What I hate about the non-repeater display controls is that all their commands are bound to POST requests, which makes the results un-bookmarkable. A point I lamented about in regards to Applebees menus: http://gadgetopia.com/post/6119
# March 31, 2008 12:57 PM

Thomas said:

Wow, as a web designer who worked in an ASP.NET environment for over a year (where I cut my teeth professionally) I completely agree about GridViews. They're hell to work with and I had to reverse-engineer my stylesheets to match the outputted code to get them to look anywhere near right.
# March 31, 2008 1:08 PM

Andrew Myhre said:

Hmmmmmmm... business logic in the database layer? That's usually mentioned as an argument in favour of stored procedures, but it's not a good idea. Bulk operations, yes. By all means perform nightly data transformations or whatever using stored procedures, but I'd strongly disagree with the assertion that it's a good place to abstract logic. Also, while Onur is basically correct, I'm really into repeaters in general simply because it forces you to consider what's going down the wire and what stylesheet developers will have to deal with. It wouldn't be difficult to write a simple base page class which handles querystring paging operations for me, and it's lightning fast. And I'm ORM all the way baby :)
# March 31, 2008 2:08 PM

Tim said:

Sorry Chris gotta disagree with you here 1) Gridviews can be customized to almost n extent, just gotta do it in the code behind and on the different events fired off. The viewstate size does suck but unless you are building a social type of site you should be ok (plus other stuff you can do to help the viewstate size, compression, moving it to the bottom). I do build more things in repeaters by hand but gridviews are ok most of the time 2) Not a fan of SP, they create an API to themselves, a little coding can prevent SQL injections.
# March 31, 2008 4:22 PM

Al-Shagra said:

so thats why I had to go through hell to learn it myself...makes sense
# March 31, 2008 6:31 PM

joeo said:

Good article...though I may be biased because you described exactly how I do things! Almost anyway, I hand-write my html and build my own custom grid controls, based on client needs. Minor nit: don't put dynamic sql in your stored procedures, and splice in a varchar parameter....then you've got sql injection all over again.
# March 31, 2008 6:39 PM

mausch said:

I agree with David about this being ASP.NET Webforms, not .NET, problems. Webforms is pretty much becoming legacy... (http://graysmatter.codivation.com/MSMVCBombshell2TheNextGreatReligiousWarStartsRIGHTNOWBecause.aspx) Besides the new ASP.NET MVC, there's also Castle Monorail, which has been providing an MVC alternative to Webforms for many years.
# March 31, 2008 7:30 PM

TrackBack said:

# April 1, 2008 6:08 PM

Will said:

Oh, crap. You just opened up a bag of worms with that SP statement. Personally, I'm not a fan of SP's. They're harder to maintain and version, imo. Plus, the benefits you list aren't true anymore. SP's have little to no speed advantage over adhoc queries. Yes, if you need to squeeze every last millisecond out of your execution time you will probably have to use an SP. But premature optimization is still not a good thing. And you can (and of course should always) use parameters in adhoc queries. So SP's aren't the only type of query that can benefit from this anti-Sql injection measure. As for having a single location for maintaining queries, adhoc's beat SP's here hands down. If you (properly) keep a single object that "generates" all your queries, you have your single location where you go to maintain them. Whenever your code changes, your queries are right there. You don't have to use some separate mechanism to examine installed queries and upgrade them if necessary (no built in way to do this in sql server, anyhow, other than overwriting them blindly). Also, with adhoc queries, you can break queries into parts that are assembled on demand, removing the need to copy-paste the same sql into different SP's. Edit once, change everywhere. You can also use #ifdefs to include debugging information in queries, or strip out formatting and comments. And its easy to combine multiple queries into one adhoc query for retrieving multiple result sets per database call. Anyhow, that's why I use 'em. And until it becomes as effortless to install, version, edit, maintain and update SP's, I won't use 'em.
# April 2, 2008 11:12 AM

gmagana said:

Disagree completely with the argument for stored procedures. Use prepared SQL statements, use parameters, and you get all possible benefits from database server-side optimization and injection attacks. People don't realize that injection attacks can be prevented from doing a call to string.Replace("'", "''"), but that's ok... It's easier to say "just use parameters in your queries." Also I find it kind of funny that you rant about generated code and then proceed to recommend generating code.
# April 2, 2008 12:17 PM

Philip said:

I dont have any problems with asp.net. I use asp classic. It takes less code, its logical, its understandable, its easier and can do anything asp.net can do in less time. I dont know the fuss about sql injection either. Make a good function that can check this.
# April 2, 2008 12:27 PM

Scott said:

I strongly agree with what Onur Gumus had to say. Girdviews are amazing for showing large amounts of Data and get the job done. Yes they are a little bulky, but the server and data connection can handle it. Since SQL Server 7, every statement is cached and I don't about you, but I am starting to love Linq over Stored Procedures. It allows for all code to be developed in c# of VB.NET and leave SQL just for Data. This is an awesome thought that are going through and if you can see that, then Start working with Linq and you will see what I mean.
# April 2, 2008 12:29 PM

Alex said:

I totally disagree. http://mattberseth.com/blog/2008/04/building_a_vs2008_styled_grid.html There's no "never" everything depends.
# April 2, 2008 12:53 PM

iputer said:

I love it when people kick their own posts. Also, great job making blanket statements.
# April 2, 2008 1:11 PM

Chris Brandsma said:

I agree with the DataSource, even the ObjectDataSource is still evil. The others are just more evil. But the thing is, I still use it from time to time. As for the GridView, I use that all the time with excellent results. But, I don't use it for everything. The real key is knowing when to, and when not to, use a particular technology. And that isn't very well understood, and your post isn't helping that either (and I'm guilty of that as well). Also, the ListView is vastly better than the Repeater. The Repeater still produces extra html, while the ListView does not. For the ObjectDataSource and GridView, they are great with small amounts of data. If your form is only going to display 20 rows, you want it sortable, and have minor data formatting concerns, then use it. If you are displaying 10,000 records then stay away. And with many others, I disagree with the stored procedures for everything approach. First abstract all database calls into a separate layer and use an ORM for the calls. Use parameterized queries when you have to. And use a stored procedure when nothing else will work. But, in SQL Server and Oracle, parameterized queries are just as fast as stored procedures. This has absolutely been the case since 2000. Multiple tests have proven this out over the years.
# April 2, 2008 1:21 PM

Mark Brackett said:

Counter points: 1. View controls are what you make of them. They give you a certain amount of builtin goodness, at the expense of some flexibility. Know when to use them, how far to go when customizing, and when you should throw them away and roll your own. 2. DataSource controls are just objects. You can stick them in a user control, assign the SQL programmatically, etc. There's nothing too magic about them. They're not the most abstracted way of dealing with data, but sometimes abstractions just get in the way. 3. Stored procs aren't the only way to get compiled and cached execution plans (not that a cached execution plan is necessarily optimal - it depends on the parameters). Nor are they a silver bullet against Sql injection (you can call stored procs as "EXEC storedproc " + Request.QueryString("EvilInput"), or take in a varchar(8000) and EXEC(@sql), etc.) - though SqlParameters are. They may help with security, since you can deny direct access to tables/views and only allow exec on the SPs. But, as with all things security, the more secure = the less flexible.
# April 2, 2008 2:22 PM

Rob Conery said:

Wow. Chris I have to admire you for stickin it out there and saying what's on your mind, but you're spreading the kind of "education" that is actually a detriment to the community. Your title is what many might consider link bait. No worries there but homey if you're gonna go there, you better have some rock-solid arguments presented. I don't see that here. I see a guy who's frustrated and venting. Moreover, I see a guy who perhaps needs to catch up on what's going on out there. >>>They not only produce a lot of useless code that take extra time to send across the wire, they are hard to customize. I have never met a client that wanted what any of these view controls produced on their sites.<<< Controls don't produce code - you do my friend. Your assertion that a Repeater will reduce code is contradictory to your assertion that "making it page" is easy - doesn't that take code? The client statement is puzzling. What do clients have to do with control selection? >>>Stored Procedures should always be used for any SQL statements. First they are compiled and optimized for optimal performance. Second this will eliminate the chances of a SQL Injection attack.<<< The SP mentality was popular 6 years ago, but not anymore. SPs were optimized in 6.5/7.0 in terms of precompilation steps. That's no longer the case with 2000 and 2005 and you as a developer need to know this. Using parameters is what prevents injection, and that should be your message, whether it's SQL or SP. Again, you should know this if you're going to write a post with this title. >>>If I had to write code to retrieve a SQLDataReader I would fail, I have not done it in years<<< This does not inspire my trust. You should know your framework if you're going to say you hate it. This one sentence tells me you hate something you don't know much about. >>>Using these techniques will make you a much more efficient programmer, eliminate many long term maintenance issues and make your applications much more performant<<< It's quite a statement and as I mention - good for you for having the nerve to write it. But it's a statement that you don't support and it's going to undermine you. For instance - it's pretty widely accepted that SPs are the epitome of a maintenance nightmare (logic bleeds, crufty routines, etc) - especially when the architect is an SP nut with an "SP for everything". I know the comment sounds negative, but please take it constructively - you suggest education is important and you drop some bombs.
# April 2, 2008 2:34 PM

Tim B said:

Okay. I'm learning Asp.Net. I spent the last several months learning Asp.Net on the Asp.Net website. I've created a simple blog, a simple forum, etc. Now you tell me that most of what I learned is wrong. All that time I spent learning to work with the gridview is of no help in deploying a real website? Commenters, some of whom sound fairly reasonable, partially agree. You provided three exasperatingly short short paragraphs on how to code properly. Where does someone like me go to learn? I don't know anybody who does Asp.Net who can teach me face to face. Seriously, now I don't know where to go to learn to code Asp.Net.
# April 2, 2008 3:02 PM

John said:

Most of these points are so wrong I don't even know where to begin, so I'll just throw out a few tidbits... The view controls can be customized in almost every single way, including their rendered output via events or a control adapter. I would tell you to make a CSS driven control adapter for the GridView, but there's already one you can download. And several of the controls you mentioned _must_ be customized to even work. The SqlDataSource is for prototyping or very small applications and in this domain it excels. However, for larger applications there is the ObjectDataSource _and_ you can also write your own. The "fact" that dynamic sql is not optimized as much as a stored procedure has been false for a long long time. Also, SPs do _not_ remove the possibility of sql injection. Besides, your dynamic sql should be parameterized.
# April 2, 2008 4:25 PM

Chris Love's Official Blog - Professional ASP.NET said:

First, wow, I never ever dreamed pushing that publish button on something I wrote in about 20 minutes

# April 3, 2008 12:25 AM

Dejan said:

Wow, seeing some of the ideas expressed in the post it makes me wonder about how professional this .NET blog really is (as the title suggests). Others have already commented about some of the disagreements I have but i feel obliged to lay out few more About the SqlDataSource control... you mention that if you want to reuse it you have to copy/paste code around. Ever thought of something like GridView1.DataSource = MyDAL.GetXYZSqlDataSource You make a valid point about the greater control the Repeater gives you, but something tells me that you haven't tried out the ListView control from .NET 3
# April 3, 2008 5:55 AM

.NET Answers said:

Can't customize the view controls? Huh? I do it all the time! Don't use DataSource? Well, I can agree about not using the SQLDataSource, but the ObjectDataSource is my preferred method. (Even over LINQDataSource)
# April 3, 2008 8:42 AM

HoyaSaxa93 said:

I've gone from sp's for business logic to code (BLL) because I've had to support multiple lines of business (LOBs)... each with unique logic. The first iteration used just stored procedures and was a nightmare to maintain. The db was littered with hundreds of sp's and udf's... all implemented with "If LOB = xxx then ...". The alternative is splitting this call into separate sp's now the "If... else" logic is moved to the code or some directing sp. Now in the 2nd iteration we have moved the logic to code and have very few sp's. The code for each LOB is isolated within a LOB namespace and logic is organized and easy to maintain. Now the database is mainly used for persistence. Not sure how this would be accomplished in a sp only world.
# April 3, 2008 8:53 AM

RB said:

Interesting debate. When I go to work, the companies that I have worked for support using GridView (or other views) and as a good soldier I use them. However, when I do my own personal projects I do not use the *View objects. They are a bid rigid unless you want to go in and really start to override a lot of the events in an attempt to customize it. If you are looking for something that is not tabular in design it's like trying to make a car into a boat. You may be able to do it, but it takes a lot of effort. On top of that it is a very heavy object. I've seen posts saying the data connection and the web server can handle it, but when you start talking about the speed of connections many clients have, those extra bytes really add up. Personally, I stay away from the *Grids. As far as stored procedures go, I use them for simple data access (your basic CRUD). I have put some logic in a SP before, but it really is to support the database integrity and not necessarily the business logic of an application. I tend to write my own DAL to manage the SPs in the database and have a business layer make sure everything is right before saving to the database. I guess I am also biased about the article since I pretty much follow this myself. Lazy programmers love to drag and drop *Grid objects on their pages since it doesn't take long to develop the site. To me, it's a bit short sighted.
# April 3, 2008 8:53 AM

VidalSasoon said:

- You obviously don't userstand how to use the GridView to its full potential. - You don't understand how to use Collections properly (ObjectDataSource) - Do you know what a DAL and BLL is? Good reasons to avoid stored procs IMO. - I'll agree that SqlDataSource is no good for production.
# April 5, 2008 1:06 PM

Chris Love said:

I know how to use the GridView and Collections. I also know how to use the Repeater and a DAL. That is why know not to use the View and DataSource controls for anything beyond POC code.

# April 5, 2008 2:18 PM

Manu Parashar said:

Very good post ! U have been kicked twice for the same. I strongly agree with most of your points !
# May 16, 2008 5:35 PM

Martyn Lee said:

I completely agree with the OP. Form views are the devils work, get an error, the whole view disappears or if your lucky, you get a vague error message. Needless to say, I swear a lot when maintaining Form views and never use them myself.
# May 30, 2008 4:53 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS