ASP Code Formatter

CodeMorph

CodeToHtml

Coding Standards

Coding Standards for Microsoft ASP .Net


You can read and download this Coding Standards for Microsoft ASP.Net coding style guide, code convention, code guideline and reference from here for free at your own risk. All trademarks, registered trademarks, product names and company names or logos mentioned herein are the property of their respective owners.

Coding Standards for Microsoft ASP .Net

Table of Contents

1. Introduction

1.1 Why Coding Standards are needed?

2. ASP .Net

2.1 Languages used in ASP .Net

3. File Organization

3.1 ASP .Net Web Form page

3.2 Code behind page

4. Implementation Guidelines

4.1 User Interface Implementation

4.2 Functionality Implementation

5. Session State

6. Caching

6.1 Output Caching

6.2 Fragment Caching

6.3 Cache API

7. Error Handling

8. Data Access

9. Layouts

9.1 Web Form page Layout

9.2 Code Behind page Layout


1. Introduction

This document is prepared for the Microsoft .Net Web Developers, who develop web applications using ASP .Net. These conventions help the developers to code effectively and to use server resources efficiently and in a consistent style.

1.1 Why Coding Standards are needed?

Complete source code would reflect as harmonized style, as if a single developer wrote the code in one session.

When the software project incorporates existing source code, or when performing maintenance on an existing software system, the coding standard would state how to deal with the existing code base.

The readability of source code has a direct impact on how well a developer comprehends a software system.Guidelines provide a framework upon which we can all create better code.

2. ASP.Net

2.1 Languages used in ASP .Net

Microsoft .Net Platform provides the developer to choose a programming language for developing a web based application. The two languages that are supported in the latest ASP .Net are VB .Net and C#(Sharp).

File Name extension standards (c# (sharp))

.csproj ASP .Net (c# project extensions)
.aspx A form for creating Web applications.
.aspx.cs code behind page for c# or VB .net(sharp)
.cs C# class file
.html for straight HTML pages
.ascx Web User Control
.asmx Web Service

3. File Organization

A file should consist of sections that should be separated by blank lines and an optional comment identifying each section.

In ASP .Net a web form is used for user interface programming. This page is divided in two distinct pieces. The visual elements and the logic.

The visual element is reference as web form page. The logic page is reference as code behind page.
1. Web form page (aspx)
2. Code Behind Page (.aspx.cs or .aspx.vb)

3.1 ASP .Net Web Form page

All Web form pages should contain HTML elements, ASP .Net web server controls, user controls, custom controls explicitly. Directives must be declared only at the starting of the page in all the web form pages, which will convey to the system about its code behind page details and other resources involved with the current web form page. The extension of the web form page is .aspx. Only HTML or user defined elements (user control tags) will be used in all the web form pages, the coding logic should not be coded in these pages.

3.2 Code behind page.

The Code behind page encapsulates the business process logic. For reusability, the logic is coded in a .Net component or web services or serviced component, in code behind page these components instance must be created and consume its methods to accomplish a particular business task. Depending on a code behind language (C# or VB.NET) the extension would be aspx.cs or aspx.vb.

4. Implementation Guidelines

4.1 User Interface Implementation

HTML Controls

These controls should be used for simple static data capture functionality and not for complex functionalities. E.g. subscriber's First Name. The validation for these controls should be coded using client side java script, if necessary. Using these controls on an .aspx pages would increase the overall performance.

<Input type=textbox id=FirstName ></input>

Web Server controls

In ASP.NET; Web Form controls provides a powerful mechanism for generating web pages with HTML controls and processing posts. And as any generic framework, there are performance implications of using it.

There is an almost linear cost for using controls in a web page. This means the code path of a page tends to increase linearly with the number of controls in a page (more or less). Some controls may create more controls internally, which may appear to be more expensive than others. To see the true control tree, use the tracing feature to get a view of it, as well as timing and generated viewstate sizes for each subtree.

Thus, avoid gratuitous usage of controls where static content or simpler generation schemes would work. Example of this would be to use the Label web form control to output some text, even though none of the programmability features of using that control would be used later. In this situation, it may be simpler (and slightly more performance) to just write the HTML for the label in the page itself. As such, remember to balance the ease of use and programmability functionality of using web controls with the potential performance cost of using them.

  <asp:Label id="Label1"
  Text="label"
  runat="server"/>

or

  <asp:Label id="Label1"
  runat="server">

Validation controls

These controls should be used for validating the web server controls used in the application. If the application needs some complex validations, a custom validation control should be developed to perform the validation. E.g., Each subscribers IT Cost is validated based on there business profile.

User Controls

These controls should be created for reusable UI interfaces in the applications which can be used as a reusable UI components across the application. These controls contains of some web server controls and HTML controls. These controls can also be programmically loaded at runtime for better performance using PlaceHolder web server control and LoadControl method.

4.1 Functionality Implementation

All web form pages in ASP .Net have a corresponding class file through which the business logic is coded. This file should contain all the methods, events by which an particular task is accomplished.

For reusability these methods should not contain any business logic, by creating an instances of .Net components or serviced Components(COM+) or a web service which contain the business logic, to accomplish a particular ask. The advantages by doing this is, we can use the same component's logic in any other web form pages.

The code shown above contains, a method Login_Click(), in which an instance of a component class is created and a method LoginCheck(parameters) is used for checking the user is a valid user or not.

Data storage layer

All database interaction including fetching the data and updating or deleting the data is accomplished through stored procedures. Stored procedure improves the performance and security. It also removes the data access programming from component which makes all component independent of underneath database.

In turn, Components which are used as a reusable code should not contain any database related coding. Another Data access class should be created for an database driven tasks. These classes instances should be created in the respective components.

  Public bool LoginCheck(useremail,pwd)
  {
    STORM.UserDB objUserDB = new STORM.UserDB();
    bool results = objUserDB.Login(parameters);
  }

The above method is a method in one of the components in which a database access component's instance is created and a particular task is accomplished.

Over all each task should be accomplished using a .Net Component and a data access component. The advantages of doing this is at any point of time, these components can be reusable and also can be converted to web services with simple coding and changes in the configuration settings.

5. Session State

ASP.NET provides several session state providers - the In-process, the State Service, and a SQL Server-backed provider. Each fills a different niche and has different performance characteristics. If one uses session state, the choice of provider will have an impact on the performance of the web site:

In-proc - the default and the fastest. There is not serialization/deserialization of objects; any type of data can be stored; and is only limited by available memory. Unfortunately, it will not survive an app reset or worker process recycle.

State service - a separate, out-of-process state server. Since it is out-of-process to the worker process, it entails a serialization/deserialization of objects (a small hit, depending on the type of object). Since it is on a separate machine, may be used on web farms, though it is limited by the amount of memory in a process (~2 Gb).

SQL State - a SQL Server is used to store the session state. A table is used in SQL Server to store the session state for users. Best suited for higher scalability (only limited by SQL Server limitations), though has the biggest performance hit.

Also, be judicious on what is stored in a session state and try to minimize the amount and complexity of data stored in each. The larger or more complex the object stored the higher the cost of storing, serializing/deserializing (for the state or SQL server) them.

Finally, if a given page doesn't need session state, you can turn it off globally in the "machine.config" or on a per page basis by specific the "enableSessionState=false" attribute in the page. Also, if you only need to read the session state, specify the read- only flag for session state, since it'll then avoid the write-back of it.

6. Caching

6.1 Output Caching

Output caching should be used when a static result of a rendered page are to be cached. For better performance, pages can also cache with variations on parameters, headers and by a custom, user-specified code scheme, with a user-specified expiration period. Output caching, if well utilized, can give the biggest boost, since it has the fastest return path for your page.

6.1 Fragment Caching

In some circumstances when caching the entire page isn't possible (due to personalization, etc), fragment caching provides a way to cache the output of user controls, allowing the page to patch these together for the final output. As with the output caching, the user control output can be cached by variations of parameters, giving more flexibility than a simple cache.

6.3 Cache API

Developers can also write their own custom caching, a full cache object is available for the page. It allows caching of any object, with included dependencies (key, time, file), expiration and user call backs on expiration, etc.

Even though there is a very rich set of features, there are a few guidelines that should be followed when using the cache:

Do not cache too many items. It is easy to go overboard and try to cache everything. There is a cost for caching an item, especially in memory utilization, so avoid caching items that could be easily re-computed or any item that would rarely be used again.

Do not put items with fast expiration. Caches work best if items can live there for long periods of time. Fast expiring items often cause high churn rate of the cache, providing little benefit and often more work for the cache cleanup code (as well as the GC, etc.). The ASP.NET Applications, Cache Total Turnover Rate gives you the overall churn rate of the cache. A high rate could be something of concern, especially if it occurs due to memory pressure (i.e. items removed before their expiration).

7. Error Handling

A multi-layered application can detect errors at any level and pass them back through its various layers. For example, an error in the Data Access Layer (DAL) that occurs in response to a SQL query error may eventually be displayed to a user via an ASP.NET page at the User Services Layer (USL). To display error messages, any web application should use custom error-handling ASP.NET pages named error404.aspx for 404 (not found) errors and error.aspx for all other errors. The error.aspx file is specified in the <customErrors> section of the Web.Config file:

8. Data Access

Whenever doing data access, use Data Readers. They are very lean, forward-only, read-only data streams and the fastest way to retrieve data from a database. Also, use the SQLDataReader for SQL Server and the OleDb reader for other databases.

When faced with displaying data from multiple tables, running a more complex stored procedure is often cheaper than multiple data retrievals and coalescing on the server. Finally, there are tradeoffs in how to display the data.

When choosing a data-viewing scheme, the tradeoffs here are often convenience for performance. A component like the Data Grid can be a quick and dirty way of showing data - but it also tends to be the most expensive in terms of performance. Rendering the data yourself by generating the appropriate HTML may work in some simple cases, but customization and browser targeting can quickly offset the extra work involved. A repeater control is more of a "middle of the road" solution - it's light, efficient, customizable, and programmable.

9. Layouts

9.1 Web Form page Layout

  /*
   ************************************************************
   * Declaration of Directives
   ************************************************************

   ************************************************************
   * HTML elements
   ************************************************************

   ************************************************************
   * Head portion of the HTML layout
   ************************************************************

   ************************************************************
   * Body portion of the HTML layout contains all HTML
   * elements, Web Server Controls, User Controls.
   ************************************************************
   */

9.2 Code Behind page Layout

  /*
   ************************************************************
   *
   * Project YCO
   * Program/Module Name Authentication Module
   * Author Akhil
   * Creation Date mm/dd/yy
   *
   * Description
   * Modification History :
   *
   * Change Date Name
   * mm/dd/yy Akhil
   *
   */

  /*
   ************************************************************
   * Using existing Namespaces
   ************************************************************
   */


  /*
   ************************************************************

   * Declaration of Namespace
   ************************************************************
   */

  /*
   ************************************************************
   * Global variables and objects Declaration
   ************************************************************

   ************************************************************
   * Class Declaration
   ************************************************************

   ************************************************************
   * Method Declaration
   ************************************************************
   */

  Want to format ASP source code automatically?  Try SourceFormatX ASP Code Formatter to format all your ASP code files.