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 » (29 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

  11. I got this web page from my pal who shared with me on the topic of this
    site and now this time I am browsing this site and reading very informative articles or reviews at
    this place.

  12. Barbra says:

    I delight in, lead to I found just what I used to
    be taking a look for. You have ended my four day
    long hunt! God Bless you man. Have a nice day. Bye

  13. Enjoy the thrill of games you need to travel to a great range of 25 letters a
    5 mega pixel camera, radio, newspapers, and an covet fashion cheats
    ink pad that doesn t surprise me. Free apps and mobile hand helds that are offered at no
    cost thus making you die however your speed limit. The same as
    instream videos. What you require is to locate my personality walking covet fashion cheats instantly
    towards NPC’s and finishing missions alone at the same demographics as though we never stop.

  14. Undeniably believe that which you said. Your favorite justification appeared to
    be on the net the simplest thing to be aware of. I say to you, I definitely get annoyed while people think about
    worries that they just do not know about. You managed
    to hit the nail upon the top and also defined out the whole thing without having
    side effect , people could take a signal. Will likely be back to
    get more. Thanks

  15. Bo Staff, Sword, Nunchakus, Sai, Tonfas, Kamas, and Escrima Stick are just some
    of the many weapons a student of the martial arts might use.
    If the cooked time is too long, the food will become hard and lose its
    flavor, color and taste. The weapons themselves can come
    in many sizes and forms: metal, wood, plastic, rubber, and foam.

    My weblog taekwondo kamas

  16. If you are planning an expansion to your property its simple that you need to acquire and then install additional
    security sensors in order to protect an extended section of your own house.
    Wireless alarm systems keep off the thieves and burglaries, making your home more secure when you are out.
    In addition, you get a Walkie Talkie that can be used for
    effective supervision of the house or business property.

  17. No matter if some one searches for his necessary thing, so he/she needs
    to be available that in detail, so that thing is maintained over here.

  18. Howdy! This is my first visit to your blog! We are a group
    of volunteers and starting a new initiative in a community in the same niche.

    Your blog provided us useful information to work on. You have done a
    wonderful job!

    Stop by my site: lose weight safely (http://www.dietformula.Info)

  19. Admiring the commitment you put into your blog and detailed information you provide.
    It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed information. Wonderful read!

    I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.

  20. Aw, this was an extremely good post. Taking a few minutes and
    actual effort to produce a very good article…
    but what can I say… I put things off a lot and don’t manage to get nearly anything done.

  21. Link exchange is nothing else but it is simply placing the other person’s website link on your page at proper place and other person will also do similar in support of you.

  22. Cool blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple tweeks would really make my blog stand
    out. Please let me know where you got your theme.
    Many thanks

    My web page corporate Meetings,

  23. If you want to get a good deal from this paragraph then you
    have to apply such strategies to your won blog.

  24. In Iron Force you can buy anything at all with
    the assets this hack helps make. Please verify if
    you have put in Iron Force recreation.

  25. An outstanding share! I’ve just forwarded
    this onto a co-worker who was conducting a littlee research on this.
    And he actually ordered me lunch because I stumbled upon it for him…
    lol. So allow me to reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to discuss this issue here on your web page.

  26. Really when someone doesn’t understand afterward its
    up to other visitors that they will assist, so here it
    happens.

  27. You are so interesting! I do not believe I’ve read through
    something like that before. So good to discover somebody with a few genuine
    thoughts on this topic. Really.. thanks for starting this up.
    This website is something that is needed on the web, someone with some originality!

  28. Cara says:

    You can certainly see your enthusiasm within the article you write.
    The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe.
    At all times follow your heart.

  29. If you wish for to increase your experience only keep visiting this web page and be updated with the most recent news
    update posted here.

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 » 131
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About



    No Child Pages.