ASP.NET Best Practices

Not to mention that the buggers reorganizes themselves internally when you do SELECTs on them, which means that references can be screwed up in a concurrency situation.

Could you explain that? Do you mean to say that if I’m holding a reference to a DataRow it might me invalidated by a select?

As I have understood it, a DataView (or perhaps a Select) may trigger an index generation to speed up things. I’ve never heard that the public interface objects (like DataTables, DataViews, DataRows, DataColumns, …) were subject to nondeterministic changes…?

Well, kind of. It’s actually very wierd, and because of the extreme randomness that occurs in concurency situations, I have not been able to fully replicate it, but I can say with 100% certainty that you will have severe concurrecy problems if you don’t make sure that only one thread Selects from the dataset at once.

On

29) Thou shalt not use Response.Write. This includes the shorthand <%= somestuff %>.

Response.Write is bad when used in a page. And it’s always bad in a page. I’ve searched my mind for just one good exception. But there aren’t any. If you do custom controls you would use a HtmlWriter. If you want to output binary content you would be better off using a handler (Generic Handler).

But I have come to realize that the shorthand <%= somestuff %> is not half bad. For one, it has well-defined semantics, i.e. it is evaluated during the rendering phase. And used correctly it will actually promote the “passive” model-view-controller pattern. Instead of the codebehind “setting” the values of the controls, they can fetch the values from the model.

So I would suggest

29) Thou shalt not use Response.Write. Not in pages nor in usercontrols. Not in markup nor in codebehind. (You may consider it when writing custom handlers, in which there’s no page lifecycle to disturb).

Time to bring this puppy back to life.

35. Thou shalt use parameterized sql. Thou shalt never use string concatenation to create sql statements.

[DISCLAIMER: this should not sink into the dynamic sql vs. stored procs debate going on for the 57th time in the blogoshpere at the moment. It can be said that both sides do agree that you should be using parameters, whatever sort of statement you are feeding the server]

There are a number of reasons for this. First is secuity–parameterized sql should be correctly declared with the proper sql datatype. And the database server will properly escape the values contained within the queries.

The second reason is speed. Sql server especially, but most database engines in general, are very good at caching execution plans for queries if they fed to them properly. In Sql’s case, the “proper” format is parameterized.

Finally, it is much, much cleaner to bind to parameters rather than manually crafting SQL. Especially when one starts to do things like build data access into a generic layer. So, do it for yourself and the guy who has to maintain this app behind you.

36. Thou Shalt Not use sp_exec in your database. If you must use dynamic sql within database calls, use sp_executesql instead.

I was reviewing an application today where the devs decided that they were going to use reasonably good practices in the .NET end of things. Typed Data Sets, parameterized Sql, etc. Then I got into the sql and it got real ugly real fast as they built the command strings in sql and then used the sp_exec to run them.

This is bad because there is no caching of execution plans. Nevermind the ease of creating errors as Sql string formatting/clensing is limited at best.

There are some situations where one must get a bit dynamic with the Sql. But you should use sp_executesql rather than sp_exec. The former procedure is much better as the sql it executes is a “first class citizen” so to speak and can take parameters as well as have its execution plan cached.

PS: 95% of the places one sees bad dynamic sql is where someone wants to do something like “SELECT * FROM foo WHERE id in List (@List)”–which does not work in T-SQL. And there are all kinds of ugly hacks and workarounds to get around this. In any case, a SQL MVP named Erland Sommarskog posted a really awesome guide to how one should do this properly.

PPS: Also see his article on the Curses and blessings of dynamic sql.

Hi why not data sets

^^^^Read page 2.

Basically because in many places they are highly inefficent and encourage a 2.5 tier design.

Here’s an article I like to keep handy for that very question: http://aspnet.4guysfromrolla.com/articles/050405-1.aspx

:slight_smile:

Thanks for enlightning :cool:

As a person who has an entire eCommerce site built on datasets, I can safely say that thea are tehpenis.

not sure what the date of the previous article in the above link is but the link below is a tutorial by the same author that creates a data access layer using typed datasets in asp.net 2.0.

http://asp.net/learn/dataaccess/tutorial01vb.aspx?tabid=63

Yeah… All my asp.net 2.0 sites have been based on this asp.net tutorial by Scott Mitchell. In it, he uses Visual Studio to create a “DataSet” in the AppCode folder. It makes a neat GUI copy of the database as some sort of XML file thingy. I finally felt like I could face life after reading this tutorial.

So… That’s the wrong way to do it? Really? Aw, Crap…

Typed datasets can generate method wrappers (table adapters) for SQL queries which can be used without using a dataset instance. If you are concerned about the performance of the dataset, but like the GUI approach (and the wizards to generate the SQL); then you can simply generate a typed dataset, generate table adapters for the tables, and simply use the latter in “direct mode”, i.e. DataReaders.

What I’ve been doing is using the GUI to make both the dataset and the table adapters, and using an ObjectDataSource to talk to the tableadapters. Then my controls are bound to the ObjectDataSource. I hope this means I am off the hook, and not breaking one of the thirty something commandments.

I think that is perfectly ok. The objectdatasource separates the sql from the page; the sql goes into the table adapters. If you changed the database, you merely had to change the table adapter (hence the name). You are doing what most MS asp.net people demonstrates at conferences, in demos etc. It does provide a measure of de-coupling and it performs and scales as good as any hand-coded SQL.

When VS2008 is released you can use LinqDataSource and a DataContext instead, and it will be almost plug-compatible with what you are doing; LinqDataSource can replace ObjectDataSource and the DataContext takes the place of the table adapters.

Personally I’m looking forward to EDM, Entity Data Model which - sadly – will not make it into VS2008.

One question: how to connect SQL database with any project in ASP.NET?

First use name space system.data.sqlclient

then create connnection

using

sqlconnection conn = new sqlconnection(‘your connection string’
then open this connection
conn.open();

Thanks for good question.

Wow-- this is a very big thread. I wonder if it is actually useful to anyone. Speaking to the original topic of “.NET Best Practices”, I have found David Hayden’s http://www.pnpguidance.net site to be very useful for getting up to speed on newer .NET patterns such as ASP.NET MVC, DI, IoC and T4.

x. Don’t use error handlanding inside asp net pages
Rather use Page or application error event and redirect of the error type of page within web.config.
y. Never leave the debug flag to true in web config when deploy
z. If you use Ajax script manager add ScriptMode=“Release” tag. That will srink the js file a lot and help with the speed (no debuging will be done)

The tips I am going to demonstrate here is very useful and tested one. In order to save viewstate and speed up your web page performance to greater extend then always try to load data into control in Init event. We make a common mistake of loading data in dropdownlist,radiobuttonlist and checkboxlist in page_load event. In page_load event we tend to generate viewstate again and again even we support it with Ispostback constraint.

So BEST practice to overcome the bandwidth leakage is to call data loading in dropdownlist control in init event of dropdown itself
< asp:DropDownList ID=“dll” OnInit=“dll_Init” DataTextField=“value”
DataValueField=“key” runat=“server” ></asp:DropDownList>//