views:

456

answers:

7

We are building an ASP.NET application and would like to follow the best practices. Some of the best practices are:


Server side Code:

  • Use catch blocks to trap & log low level errors too.
  • Use Cache objects to populate dropdowns etc. where we won’t expect the changes in the underlying data/database.
  • In case of error logging framework, provide emailing alerts along with logging the errors.


HTML code: - Don’t write inline CSS. - Place the JavaScript code (If needed by the page) at the end of the page unless the page needs it for load time actions.


Now coming to the point, Would you please share these best practice points if you have a comprehensive list of them already?

+2  A: 

Here are some similar questions that may help you.

http://stackoverflow.com/questions/528500/net-best-practices

http://stackoverflow.com/questions/293152/best-way-to-learn-net-oop-best-practices

This should probably be community wiki as well.

TheJuice
+4  A: 

I don't think try/catch blocks are always appropriate for low-level methods. You want to catch (and log/alert, even better!) any errors before they get to the user, of course. But it is often better for a low-level method to just lets its errors get raised up to a higher level. The problem I have seen with low-level error trapping is that it often lets a larger operation continue, but then a result that is not quite correct gets presented to the user or saved to the database, and in the long run it's much more difficult to fix. It's also just a lot of extra clutter in your code to put a try/catch at every level if you're not going to "do anything" with the error until it's raised up to a higher level.

Marc
+11  A: 
  1. Create a base page for all your asp.net pages. This page will derive from System.Web.UI.Page and you may put this in YourApp.Web.UI. Let all your asp.net pages dervice from YourApp.Web.UI.Page class. This can reduce lot of pain.

  2. Use Application_OnError handler to gracefully handle any error or exception. You should log the critical exception and send the details of the exception along with date-time and IP of client to the admin email id. Yes ELMAH is sure way to go.

  3. Use ASP.NET Themes. Many developers don't use it. Do use them - they are a great deal.

  4. Use MembershipProvider and RoleProvider. And Never use inbuilt ProfileProvider - They store everything in plain strings. It will drastically slow-down the performance while performing R/W

  5. Use Firebug for client-side debugging. Try to follow YSlow standards for web-applications. Use YSlow extension for FireBug.

  6. Use jQuery for client-scripting.

  7. Never store User Authentication information in session or don't use sessions to judge if user is logged on. Store only minimum necessary information in sessions.

  8. Have a look at PostSharp. Can improve maintainability of your code and make you more productive.

  9. Never ever Deploy asp.net application under debug configuration on production. Find out here what scottgu has to say about this.

  10. User Web Deployment projects. It can transform web.config sections and replace with production server setings. It will merge all compiled code-behind classes into one single assembly which is a great deal.

  11. Use Cookie-less domains to serve static resources like images, scripts, styles etc. Each client request is sent along with whole bunch of cookies, you don't need cookies while serving pictures or scripts. So host those resources on a cookie-less domain.

  12. Minify scripts, stylesheets and HTML response from the server. Removing unnecessary line-breaks and white-spaces can improve the time-to-load and bandwidth optimization.

this. __curious_geek
Change item 2, to ELMAH.
Zote
@curious_geek +1 for Firebug. Can't program without it (nor Resharper)
Kb
+12  A: 

Some of the best practices that I've learned over time and written up for use at my company...many are mainly applicable to WebForms and not MVC.

  • Don't write .NET code directly in your ASPX markup (unless it is for databinding, i.e. Evals). If you have a code behind, this puts code for a page in more than one place and makes the code less manageable. Put all .NET code in your code-behind.
  • SessionPageStatePersister can be used in conjunction with ViewState to make ViewState useful without increasing page sizes. Overriding the Page's PageStatePersister with a new SessionPageStatePersister will store all ViewState data in memory, and will only store an encrypted key on the client side.
  • Create a BasePage that your pages can inherit from in order to reuse common code between pages. Create a MasterPage for your pages for visual inheritance. Pages with vastly different visual styles should use a different MasterPage.
  • Create an enum of page parameter key names on each WebForm that are passed in via the URL, to setup strongly-typed page parameters. This prevents the need for hard-coded page parameter key strings and their probable mis-typing, as well as allowing strongly-typed parameter access from other pages.
  • Make use of the ASP.NET Cache in order to cache frequently used information from your database. Build (or reuse from another project) a generic caching layer that will wrap the ASP.NET Cache.
  • Wrap ViewState objects with Properties on your Pages to avoid development mistakes in spelling, etc. when referencing items from the ViewState collection.
  • Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects.
  • Wrap the ASP.NET Session with a SessionManager to avoid development mistakes in spelling, etc. when referencing items from Session.
  • Make extensive use of the applicationSettings key/value configuration values in the web.config - wrap the Configuration.ApplicationSettings with a class that can be used to easily retrieve configuration settings without having to remember the keys from the web.config.
  • Avoid the easiness of setting display properties on your UI controls, instead use CSS styles and classes - this will make your styles more manageable.
  • Create UserControls in your application in order to reuse common UI functionality throughout your pages. For example, if a drop down list containing a collection of categories will be used in many places in the site - create a CategoryPicker control that will data bind itself when the page is loaded.
  • Use Properties on your UserControls to setup things like default values, different displays between pages, etc. Value type properties can be defined on your UserControls and then be set in your ASP.NET markup by using class level properties on UserControls.
  • Make use of the ASP.NET validation controls to perform simple validations, or use the CustomValidator to perform complex validations.
  • Create an Error handling page that can be redirected to when an unhandled exception occurs within your website. The redirection can occur via the Page_Error event in your Page, the Application_Error event in your Global.asax, or within the section within the web.config.
  • When working with pages that use a highly dynamic data driven display, use the 3rd party (free) DynamicControlsPlaceholder control to simplify the code needed to save the state of dynamically added controls between postbacks.
jspru
+1  A: 

I would recommend a couple of books if you are interested in pursuing a journey to become a better, more productive developer. These books are language agnostic and as you can see by the user reviews, very very helpful.

Code Complete 2

Pragmatic Programmer

If you are looking for a .NET specific book, you may appreciate the following book:

Microsoft Application Architecture Guide [available online for free outside of print format]

Kyle B.
+4  A: 

Forms:

  1. Set Page.Form.DefaultFocus and Page.Form.DefaultButton to improve user experience

  2. Check Page.IsValid in your Save button handler before proceeding.

General:

  1. Understand and implement the techniques found in the article "TRULY Understanding ViewState"

  2. Use Page.IsPostBack in your page events to stop code from running unnecessarily.

  3. Use hyperlinks instead of posting and using Response.Redirect whenever possible.

    a. Understand and use the second parameter of Response.Redirect (it "Indicates whether execution of the current page should terminate")

  4. Use the Page Lifecycle properly.

  5. Use the Per-Request cache (HttpContext.Items) instead of Cache where it makes sense.

Web.Config:

  1. Deploy with <compilation debug="false">

  2. Register your controls at the web.config level instead of the page level (i.e. @Register).

Themes:

  1. When using Themes, put your static images in the Theme as well.

    a. Don't link to the images directly from your markup, link to them from a skin file or css file in your Theme instead.

    ex: <asp:Image SkinID="MyImage" runat="server" ImageUrl="Images/myImage.gif" />

Greg
+1 for the seldom(yet extremely useful) used `Context.Items`
Earlz
A: 

ASP.NET

  • If you don't use Session state, don't forget to turn off it.
  • Use Server.Transfer instead of Response.Redirect if possible.
  • Set expiration parameter in IIS.
  • Use GZip to compress the text files.
  • Use Server-Side and Client-Side validation together.
  • Use Url Rewriter or Routing to make friendly url for SEO.


Design

  • Write each class and its properties of your CSS file in the same line. (To decrease the file size)
  • Use CSS Sprites. (To decrease request)
Mehdi Golchin