Building ASP.NET application - Best Practices - asp.net

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?

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.

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.
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.
Use ASP.NET Themes. Many developers don't use it. Do use them - they are a great deal.
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
Use Firebug for client-side debugging. Try to follow YSlow standards for web-applications. Use YSlow extension for FireBug.
Use jQuery for client-scripting.
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.
Have a look at PostSharp. Can improve maintainability of your code and make you more productive.
Never ever Deploy asp.net application under debug configuration on production. Find out here what scottgu has to say about this.
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.
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.
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.

Forms:
Set Page.Form.DefaultFocus and Page.Form.DefaultButton to improve user experience
Check Page.IsValid in your Save button handler before proceeding.
General:
Understand and implement the techniques found in the article "TRULY Understanding ViewState"
Use Page.IsPostBack in your page events to stop code from running unnecessarily.
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")
Use the Page Lifecycle properly.
Use the Per-Request cache (HttpContext.Items) instead of Cache where it makes sense.
Web.Config:
Deploy with <compilation debug="false">
Register your controls at the web.config level instead of the page level (i.e. #Register).
Themes:
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" />

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.

Here are some similar questions that may help you.
.NET best practices?
Best way to learn .NET/OOP best practices?
This should probably be community wiki as well.

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]

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)

Related

Allowing user-created templates in an ASP.NET site

I have a website I’m converting from Classic ASP to ASP.NET. The old site allowed users to edit the website template to create their own design for their section of the website (think MySpace, only LESS professional.)
I’ve been racking my brain trying to figure out how to do this with .NET. My sites generally use master pages, but obviously that won’t work for end-users.
I’ve tried loading the HTML templates as a regular text file and parsing it to ‘fit around’ the content place holders. It is as ugly as it sounds.
There’s got a be something generally regarded as the best practice here, but I sure can’t find it.
Any suggestions?
How much control do you want your users to have?
There are a few ways to implement this. I'll give you a quick summary of all the ideas I can think of:
Static HTML with predefined fields.
With this approach you get full control and you minimize the risk of any security vulnerabilities. You would store per-user HTML in a database table somewhere. This HTML would have predefined fields with some markup, like using {fieldName}. You would then use a simple parser to identify curly brackets and replace fieldName with a string value pulled from a Dictionary<String,String> somewhere.
This approach can be fast if you're smart with string processing (i.e. using a state-machine parser to find the curley brackets, sending the rebuilt string either directly to the output or into a StringBuilder, etc, and importantly not using String.Replace). The downside is it isn't a real templating system: there's no provision for looping over result-sets (assuming you want to allow that), expression evaluation, but it works for simple "insert this content into this space"-type designs.
Allow users to edit their own ASPX or ASCX files.
Why build your own templating system if you can use ASP.NET's? Well, this approach is the simplest if you want to build a quick 'n' dirty reporting system, but it fails terribly for security. Unfortunately you cannot secure any <% %> / <script runat="server"> code in ASPX files in a sandbox or use CAS owing to how ASP.NET works (I looked into this myself earlier: Code Access Security on a per-view ASP.NET MVC basis ).
You don't need to store the actual ASPX and ASCX files in the website's filesystem, you can store the files in your database using a VirtualPathProvider implementation, but getting it to work right can be a bit of a pain (especially as the ASP.NET runtime compiles ASPX files, so you'd need to inform it if an ASPX file was modified by the user). You also need to be aware that ASPX loading is tied into the user's request path (unless you're using Routing or MVC) so you're better off using ASCX, not that it matters really.
A custom ASP.NET handler that runs in its own CAS sandbox that implements a fully-fledged templating engine
This is the most painful option, and it exists between the two: you get the flexibility of a first-class templating engine (loops, fields, evaluation if necessary) without needing to open your application up to gaping security flaws. The downside is you need to build pretty much everything by yourself. I won't go into detail here.
Which option you go for depends on what your requirements are. MySpace's system was more "skinning" than "templating", in that the users were free to set a stylesheet and define some arbitrary common HTML rather than modify their page's general template directly.
You can easily implement a MySpace-like system in ASP.NET assuming that each skinnable feature is implemented as a Control subclass, just extend your Render method to allow for the insertion of said arbitrary HTML. Adding custom stylesheets is also easy: just add it inside a <style type="text/css"> element in your page's <head>.
When/if you do allow the user to enter HTML directly, I strongly recommend you parse it and filter out any dangerous elements (such as <script>, <style>, <object>, etc). If you want to allow for the embedding of YouTube videos and related then you should analyse <object> elements to ensure they actually are of YouTube videos, extract the video ID, then recreate the element from a known, trusted template. It is important that any custom HTML is "tag-balanced" (you can verify this by passing it through a strict XML parser instead of a more forgiving HTML parser, as XHTML is (technically) a subset of HTML anyway), that way any custom markup won't break the page.
Have fun.

creating an ajax application

I have several pages of my web application done. They all use the same master page so they all all look very similar, except of course for the content. It's technically possible to put a larger update panel and have all the pages in one big update panel so that instead of jumping from page to page, the user always stays on the same page and the links trigger __doPostback call-backs to update with the appropriate panel.
What could be the problem(s) with building my site like this?
Well, "pages" provide what is known as the "Service Interface layer" between your business layer and the http aspect of the web application. That is all of the http, session and related aspects are "converted" into regular C# types (string, int, custom types etc.) and the page then calls methods in the business layer using regular C# calling conventions.
So if you have only one update panel in your whole application, what you're effectively saying is that one page (the code behind portion) will have to handle all of the translations between the http "ness" and the business layer. That'll just be a mess from a maintainable perspective and a debugging perspective.
If you're in a team that each of you will be potentially modifying the same code behind. This could be a problem for some source control systems but one or more of you could define the same method name with the same signature and different implementations. That's won't be easy to merge.
From a design perspective, there is no separation of concerns. If you have a menu or hyper link on a business application, it most likely means a difference concern. Not a good design at all.
From a performance perspective you'll be loading all of your systems functionality no matter what function your user is actually doing.
You could still have the user experience such that they have the one page experience and redirect the callback to handlers for the specific areas on concern. But I'd think real hard about the UI and the actual user experience you'll be providing. It's possible that you'll have a clutter of menus and other functionality when you combine everything into one page.
Unless the system you are building a really simple and has no potential to grow beyond what it currently is and provide your users with a one page experience is truly provide value and an improved user experience and wouldn't go down this route.
When you have a hammer, everything looks like a nail.
It really depends on what you are trying to do. Certainly, if each page is very resource-intensive, you may have faster load times if you split them up. I'm all for simplicity, though, and if you have a clean and fast way of keeping users on one page and using AJAX to process data, you should definitely consider it.
It would be impossible to list too many downsides to an AJAX solution, though, without more details about the size and scope of the Web application you are using.

ASP.NET MVC State Management

I am working on a .net mvc web application that has a bunch of web parts on the homepage. I realize that a webpart is a .net forms terminology, but wasn't sure what to name those mini sections. So anyways, for now these sections are called when that page is rendered, but eventually I will plug in JQuery and call these sections using AJAX. These mini sections or widgets will need to keep state as the user navigates between the homepage and back. With .net forms, the page state info is kept in the viewstate, but with .net mvc, that is not available (thankfully).
So, is there a framework already created for such functionality for MVC? If not, what would be the best way to handle this situation? I was thinking to leverage the HttpContext object and store everything in there, but not sure if that object has any size limitations.
Just like with anything else in MVC you're going to need to store the state somewhere. As other users have pointed out, using Partial Views will reduce the complication of the design by allowing you to have controllers that handle just those small parts. They can then be responsible for saving/restoring/tracking the state or info for that part. (This could be using a database, in process memory, whatever.)
If you put the controls in the master page you can have the parts' implementation removed from your other logic so you don't need to worry about capturing and returning data related to those parts with the rest of your model meant for your view.
Having the parts separate like that will make it a lot easier to AJAXify them as well since they would already be operating independently of your view data even though they are rendered at the same time.
I think you want to check out Partial Views.
You can use output caching or data caching, both supported by MVC 1.0/2.0.
Not sure if you're after this but project Orchard has a notion of widgets: http://www.orchardproject.net/docs/Default.aspx?Page=widgets&NS=&AspxAutoDetectCookieSupport=1.

Strategic Advice: Upgrading the Design of a Web App

I have an ASP.NET web site dedicated to reporting on PBX extension stats. It comprises many report pages, with HTML generated almost purely by code-behind (setting a Label control's Text property instead of using Response.Write), using un-parameterised string literal SQL queries that populate By Reference DataTable parameters.
Maintenance pages at least comprise DataGrids and detail forms, but use the same DAL, on e thing for which can be said is that it supports multiple DB servers, with sub-classes each overriding these access methods with their own string literal queries.
What do I need to consider cleaning up this mess? I've already made an almost obvious decision to use a third party reporting solution, and move the queries to stored procs in their respective DB languages, narrowing the diversity of the different DAL classes, and to separate CSS out to shared files, as lots of it is very hidden in C# files!
For your back-end design, I suggest having a class to represent each main table of your database (i.e. a Report class and a User class, for example). Anything that's not an event handler should go in the back-end class files / namespace.
For your GUI, looks like you're on the right track using ASP.NET controls instead of just streaming your data out to the user. However, you may consider objectifying the areas of the page. For example, one of my favorite tricks is to open semitransparent "popup" panels when requiring user input or a something like the Information Bar when displaying a short message.
Consider AJAX and the AJAX Control Toolkit. It's easy to implement (especially in the case of a rewrite) and provides great flexibility. Specifically, I've found Accordions - sometimes even nested within other Accordions - are excellent at organizing overabundances of information.
Edit:
Note that if you were to use AJAX, you basically can't even consider using response.write anymore.
As far as having too much content on the screen, remember Panels have a "Scrollbar" property and DIVs don't without some heavy changes.
Also, I tend to separate my code files by Namespace; but the popular trend is to do so by Class. This is a better option if you have many Developers or if it's likely several classes within a namespace will be checked out or simultaneously modified by different people.
I would consider ditching any custom written DAL and use one of:
iBATIS.NET
NHibernate
SubSonic
You might even end up dropping sprocs entirely.
If you're daring you could try the redesign using Microsoft's MVC implementation.
Whatever approach you take, make sure you write unit tests prior to refactoring any code, verify the tests pass before and after refactoring.

Conditional Display in ASPX Pages on Sharepoint

I wonder what the best practice for this scenario is:
I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.
Two solutions:
Change the PageParserPath in web.config as per this site
<PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx"
CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
Create all the controls and Wire them up to Events in the .CS File, thus completely eliminating some of the benefits of ASP.net
I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible.
So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too.
You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.
What does the ASPX page do? What functionality does it add? How are you adding the page into the site? By the looks of it this is just a "Web Part Page" in a document library.
I would have to do a little research to be 100%, but my understanding is that inline code is ok, providing it's in a page that remains ghosted, and thereby trusted. Can you add your functionality into the site via a feature?
I would avoide option 1, seems like bad advice to me. Allowing server side code in your page is a security risk as it then becomes possible for someone to inject malicious code. Sure you can secure the page, but we are talking remote execution with likely some pretty serious permissions.
Thanks so far. I've successfully tried Andrew Connel's solution:
http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx
Wrapping it into a solution is part of that, but the main problem was how to get the code into that, and it's more leaning towards Option 2 without having to create the controls in code.
What I was missing:
In the .cs File, it is required to manually add the "protected Button Trigger;" stuff, because there is no automatically generated .designer.cs file when using a class library.
Well, it's a page that hosts user controls. It's a custom .aspx Page that will be created on the site, specially because I do not want to create WebParts.
It's essentially an application running within Sharepoint, utilizing Lists and other functions, but all the functionality is only useful within the application, so flooding the web part gallery with countless web parts that only work in one place is something i'd like to avoid.

Resources