13 Dec 2009 @ 5:00 PM 
Bookmark and Share

Over time while using ASP.NET I’ve collected a pretty good handful of best practices that I try to employ on my projects – most of them are things that will simplify the ASP.NET development experience, solutions to common problems, or tips that will just make your life easier.  Most of the best practices are only applicable to WebForms, but some are applicable to ASP.NET MVC as well.

  • Don’t write .NET code directly in your ASPX markup (unless it is for databinding, i.e. Eval statements). If you also have a code behind, this will put your code for a page in more than one place and makes the code less manageable. Put all .NET code in your code-behind.  Things can get complex and difficult to debug very quickly when you’re looking at code executing in two different places.
  • 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.  This will make your pages smaller and download faster if you have a lot of ViewState data for some reason, however it will increase your memory usage on the server – so tread carefully.  See example below for how to use SessionPageStatePersister.
public override PageStatePersister GetStatePersister() {
return new SessionPageStatePersister(this);
}
  • Create a BasePage that your pages can inherit from in order to reuse common code between pages.  Simple object oriented design principles – if you have common functions between pages, like security for example – put it in a base class that inherits from System.Web.Page, and have your pages inherit from that base page.
  • Create a MasterPage for your pages for visual inheritance.  Don’t use ASP server-side includes.  Pages with vastly different visual styles should use a different MasterPage.  Don’t use a Master page for code inheritance.
  • Make use of the ASP.NET Cache in order to cache frequently used information from your database.  Build (or reuse) a generic caching layer that will wrap the ASP.NET Cache.  If you’re loading the same list from the database into a drop down every time a page loads, you should be pulling that list from the cache based on how dynamic it needs to be.
  • Wrap ViewState objects with Properties on your Pages to avoid development mistakes in spelling, etc. when referencing items from the ViewState collection.  For example, you should only have ViewState["key"] once in your page per property.  See example below.
private int SampleId
{
get { return ViewState["SampleId"] == null ? 0 : (int)ViewState["SampleId"]; }

set { ViewState["SampleId"] = value; }
}

  • Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects.  This is the reason people always complain about huge viewstate – they’re storing something like DataSets in ViewState (terrible idea).  If you stick to small objects with a limited number of properties or just integer IDs, your ViewState data will not be unmanageably large and ViewState is totally usable.
  • Wrap the ASP.NET Session with a SessionManager class to avoid development mistakes in spelling, etc. when referencing items from Session.  Just another way to cut down simple development mistakes.
  • 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 strongly-typed configuration settings without having to remember the keys from the web.config.  If you have settings, behaviors, etc. that need to change between different deployments of your application, those should be control via settings in the web.config.  For example, we’ll often get requests like ‘We want feature X to go live at the end of the month” – so build, test, and deploy the update ahead of time.  But, add a web.config value that controls whether or not the feature appears i.e. FeatureXEnabled=”False”, on the day of go live just flip it to “True”.
  • Avoid the easiness of setting display properties on your UI controls, instead use CSS styles and classes – this will make your styles more manageable.  Just a general web development best practice.
  • 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.  This is my #1 time-saving best practice, yet I’m always surprised how often I see the same drop down list with the same data getting used the same way on 20 different pages – yet the same type-unsafe databinding logic is duplicated 20 times!
  • 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.  This is a great way to get even more mileage out of reusing your UserControls – watch out for increased complexity of your UserControl logic though.
  • Make use of the ASP.NET validation controls to perform simple validations, or use the CustomValidator to perform complex validations.
  • Create an user-friendly error handling page that can be redirected to when an unhandled exception occurs within your website.  Log any exceptions that come to this page.  The redirection can occur via the Page_Error event in your Base Page, the Application_Error event in your Global.asax, or within the error handling section in the web.config.  Basically, whichever method you pick – make sure you’re not letting any exceptions go unhandled or unlogged!
  • When working with pages that use a highly dynamic data driven display, use the 3rd party (free) DynamicControlsPlaceholder control created by Denis Bauer to simplify the code needed to save the state of dynamically added controls between postbacks.  This little control has saved me countless hours of pain in creating pages with highly dynamic UserControls.  One gotcha – if you use event handling delegates in a UserControl, you have to hook them up on every postback, little messy but not a big deal though usually.  Event handlers are the only “state” that isn’t saved between postbacks if you use this control.
  • Turn ViewState off on controls and UserControls that don’t need it.
Posted By: admin
Last Edit: 14 Dec 2009 @ 06:21 PM

EmailPermalink
Tags
Tags: ,
Categories: Uncategorized


 

Responses to this post » (10 Total)

 
  1. ASP.NET WebForms Best Practices…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  2. [...] ASP.NET WebForms Best Practices – John Sprunger shares a number of best practices for ASP.NET Web Forms Development, some of which are also applicable beyond the WebForms world. [...]

  3. Adam says:

    “Avoid the easiness of setting display properties on your UI controls, instead use CSS styles and classes – this will make your styles more manageable. Just a general web development best practice.”

    Number 1 way to annoy any designer. I can’t stand it when I create common classes in css only to find they have been overwritten by stupid .net inline properties.

  4. [...] ASP.NET WebForms Best Practices Very good advice, things to keep in mind when working with WebForms. Some apply to ASP.NET MVC as well. [...]

  5. [...] ASP.NET WebForms best practices: Algunos consejos básicos, otros como el SessionPageStatePersister no muy conocidos, una lectura recomendada para todo programador de ASP.NET. [...]

  6. [...] ASP.NET WebForms Best Practices – System.Nerd.John.Blog + velmi zajímavý design webu [...]

  7. [...] de boas práticas de programação com ASP.net que achei muito interessante (http://jsprunger.com/asp-net-webforms-best-practices/).  O post tem quase 1 ano e meio e mesmo assim seu conteúdo é muito recente. [...]

  8. [...] de boas práticas de programação com ASP.net que achei muito interessante (http://jsprunger.com/asp-net-webforms-best-practices/).  O post tem quase 1 ano e meio e mesmo assim seu conteúdo é muito recente. [...]

  9. [...] de boas práticas de programação com ASP.net que achei muito interessante (http://jsprunger.com/asp-net-webforms-best-practices/).  O post tem quase 1 ano e meio e mesmo assim seu conteúdo é muito recente. [...]

  10. Aking Web Tech a leading IT company & Provides web services :- website Development in just 1,999 Rs/-, software development like {Billing software, School Management Software, Inventory Software, ERP, CRM}, Domain & Hosting , SEO
    software companies in indore

Post a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Change Theme...
  • Users » 3
  • Posts/Pages » 16
  • Comments » 68
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About



    No Child Pages.