.Net Standards

Option Matrix has compiled a list of engineering standards for asp.net programming in C# and this list is used for periodic code review during projects. Just as it is important that the application serves its intended purpose, it must be built correct with security, performance, scalability and readability in mind so that it is maintainable / durable. We ensure this balance between internal and external project quality.


# Category Best Practices
1 ASPX pages Title tags should be placed first in order, followed by Meta Tag (ex: Title, Meta: keyword, Meta: Description)
2 ASPX pages Link Tag and Script Tag should appear after Meta Tag within the head tag only. (ex: Title, Meta: keyword, Meta: Description, Link Tag, Script Tag)
3 ASPX pages Inline styles and internal styles should be eliminated. All styles must be written in external linked CSS style sheet.
4 ASPX pages Use heading tags in the initial html of the page as it helps SEO to find out your keywords easily. (ex: h1, h2, h3)
5 ASPX pages SRC, ALT and TITLE attributes must be placed in IMG tag
6 ASPX pages Title Attribute must be placed in the ANCHOR TAG
7 ASPX pages Page and Image names have to be separated by hyphens (-). Use “-” in links: Use always “-” hyphens in the URL Links and never use “_” underscores.
8 ASPX pages Lower Case URL’s : All URL’s should be in lower case, not in capital letters.
9 ASPX pages Spacers : Either in design or coding phase, don’t use Spacers.
10 ASPX pages The folder names should be 'images', 'style sheets' and 'java scripts'
11 ASPX pages Every tag has to close properly and for Unary/Empty tags one space gap should be there before closing tag ex: />
12 ASPX pages HTML construction should follow Nested DIV and usage of tables should be avoided in HTML as much as possible.
13 ASPX pages Comments to be removed from the ASPX mark-up. The tag ID and classes should indicate the purpose of each tag.
14 ASPX pages Use Crumb Trail or Breadcrumbs wherever necessary
15 ASPX pages Focus content pages for a few keywords and ensure adequate keyword density in the page content
16 ASPX pages Using Google XML Sitemaps makes it easier for the search engine crawlers to assess the site and increases the page rank
17 ASPX pages Ensure HTML 4 compliance and use lower CSS version as much as possible to ensure cross browser compatibility. The latest versions of desktop browsers such as Internet Explorer, Google Chrome, Firefox, Safari and Opera should be used to evaluate the cross browser compatibility. IE7 and IE8 should be included in cross browser testing. Mobile browsers may be included based on project needs.
18 ASPX pages W3C HTML Validation test must be OK
19 ASPX pages W3C XHTML Validation test must be OK
20 ASPX pages The DOCTYPE declaration should always be the first line. A DOCTYPE declaration is mandatory if the document is to be processed in a validating environment. To be valid, the DOCTYPE declaration must identify a DTD that corresponds to the document structure of the document. Eg:
21 ASPX pages Name of the main stylesheet must be default.css and other stylesheets has to be imported in default.css
22 CSS Maintaining Tabs Format in CSS, so as to reduce or minimize the file size of the CSS page.
23 CSS All comments in CSS and JS files should be removed. This reduces page weight and improves performance, gives cleaner look and also helps for search engines crawlers.
24 CSS Class Names has to be separated by Hyphens (-) eg:"inner-body-container" is more SEO friendly than "inner_body_container"
25 CSS W3C CSS Validation must be OK
26 CSS Use of image sprites is preferred when possible - An image sprite is a collection of images put into a single image. A web page with many images can take a long time to load and generates multiple server requests. Using image sprites will reduce the number of server requests and save bandwidth.
27 Maintenability Use .Net user controls and master pages for reusability
28 Maintenability Write the common logic in helper or related class files
29 Maintenability Use LINQ to SQL for connecting the server classes to database. The DBML files must be classified logically by modules
30 Maintenability ASPX files must be driven by resource files and there should be a separate folder for each page.
31 Maintenability Write the detailed comments in the code and stored procedures at header and inline levels
32 Maintenability Names of views or tables in database must always be in plural case e.g. employees or customers
33 Maintenability Use Pascal case for Class / Function Names and Camel case for identifier names / parameter names (Pascal Case: GetUserData(),Camel Case: firstName, lastName)
34 Maintenability Use all lower case characters for database object names like tables, stored procedures etc
35 Maintenability Indent the nested code blocks to improve readability
36 Maintenability Prefix primary key field with pk__id and foreignkey field with fk__id
37 Maintenability Prefix Boolean variables, properties and methods with “is”. Ex: isActive
38 Maintenability Use Hungarian notation - Always prefix variable names with the data type it holds such as strfirstName
39 Maintenability Do not use variable names that resemble programming keywords
40 Maintenability Do not give abbreviated function name or Identifier names as it makes the code unreadable
41 Maintenability Do not keep the unnecessary images or code files or CSS files in the application
42 Maintenability Do not use mis-leading names and function name should tell what it does - names should be self explanatory - by looking at the name we can easily understand what is going on in the function or file
43 Maintenability Do not use numbers or strings to indicate discrete values. Use enum wherever required
44 Maintenability Any CS class file must not exceed 1000 lines under any circumstances and this includes comments. The name of the class must be self explanatory and the functions in the class must be logically grouped.
45 Maintenability Follow the standard prefixes in the naming conventions (vcFirstName for varcahar, sdDate for smalldatetime, intWeight for integer) for fields in database tables
46 Maintenability Follow the standard format for stored procedure as per the enclosed tab in this sheet
47 Maintenability First part of the Stored Procedures name should start with 'f' or "usp" when calling from the front end and 'P' or "adm" for administration or batch job operations. Last part should follow the standard by using Get or Set at the end of the sp name. Use capital letters instead of underscores as delimiter in name. The correct sample name for a stored procedure is [staff].fXrayUserDetailsGet or [admin].PXrayEventDetailsUpdate. Schema name must be prefixed to stored procedures and tables.
48 Performance Use stored procedures and there should be no inline SQL queries in the data layer classes. Be sure to use CommandType.StoredProcedure instead of CommandType.Text
49 Performance Use Switch case over if..else ladder
50 Performance Deploy site with Release Mode in pre-compiled state and set debug=false as well as turn off tracing (trace=false)
51 Performance Return multiple result sets in a single database request, so that you can cut the total time spent communicating with the database
52 Performance Do not compare strings to String.Empty or “” to check for empty strings. Instead, compare by using String.Length == 0 because String.Length executes fast
53 Performance Use external style sheets and Javascript files and place the link tags for the CSS files in the head tag of the page in .aspx or master page
54 Performance Put Scripts to the end of Document - Unlike Style Sheets, it is better to place scripts to the end of the document. Progressive rendering is blocked until all Style Sheets have been downloaded. Scripts cause progressive rendering to stop for all content below the script until it is fully loaded. Moreover, while downloading a script, the browser does not start any other component downloads, even on different hostnames.
55 Performance Dispose the objects once they are in no use
56 Performance Use AJAX update panels as required to improve user experience and avoid unnecessary round trips to the server
57 Performance Do not use “string” type for concatenation in iterative loops, instead use String Builder
58 Performance Do not use select * in your select query, select only required fields
59 Performance Page weight must not exceed 100 KB. If required, the page functions should be split as tabs and each tab should be loaded separately.
60 Performance Make the EnableSessionState=false on page if you do not use any sessions
61 Performance Store all images of your site under the /images. Browsers cache the images or css files depending upon the path, so if we place images in static folder, image once loaded are always gets cached, they do not have to be downloaded every time.
62 Performance Include Return Statements within the Function/Method - Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function/method is given several local variables on stack to transparently support returning values without the keyword. Keeping these around makes it harder for the JIT to optimize, and can impact the performance of your code. Look through your functions/methods and insert return as needed. It doesn't change the semantics of the code at all, and it can help you get more speed from your application.
63 Performance Avoid making frequent calls across processes - If you are working with distributed applications, this involves additional overhead negotiating network and application level protocols. In this case, network speed can also be a bottleneck. Try to do as much work as possible in fewer calls over the network.
64 Performance Minimize the Use of Format () - When possible, use toString() instead of format(). In most cases, it will generally provide the functionality required, with much less overhead.
65 Performance Always avoid Nested Loops and Recursive functions, to improve performance
66 Performance Encode Using ASCII When You Don't Need UTF - By default, ASP.NET comes configured to encode requests and responses as UTF-8. If ASCII is all your application needs, eliminating the UTF overhead can give back a few cycles
67 Performance Minimize the number of web server controls - The use of web server controls increases the response time of your application because they need time to be processed on the server side before they are rendered on the client side
68 Performance Use low cost authentication - Authentication can also have an impact over the performance of your application. For example, passport authentication is slower than form-based authentication which in here turn is slower than Windows authentication.
69 Performance Avoid using unmanaged code - Calls to unmanaged code are a costly marshalling operation. Try to reduce the number calls between the managed and unmanaged code. Consider doing more work in each call rather than making frequent calls to do small tasks.
70 Performance Store your content by using caching - ASP.NET allows you to cache entire pages, fragment of pages or controls. You can also cache variable data by specifying the parameters on which the data depends. By using caching, you help ASP.NET engine to return data for repeated request for the same page much faster
71 Performance Use "ArrayLists" in place of arrays - An ArrayList has everything that is good about an array PLUS automatic sizing, Add, Insert, Remove, Sort, Binary Search. All these great helper methods are added when implementing the IList interface.
72 Performance Always make sure you check Page.IsValid before processing your forms when using Validator Controls
73 Performance Use Paging and only show small subsets of data at a time, allowing the page to load faster.
74 Performance Avoid un-necessary in-direction and do not use byRef, to pass pointers instead of the actual object, unless strictly needed
75 Performance Use Page.isPostBack - Make sure you don't execute code needlessly. Use Page.ISPostBack property to ensure that you only perform page initialization logic when a page is first time loaded and not in response to client post backs.
76 Performance Use Finally Method to kill resources - The finally method gets executed independent of the outcome of the Block. Always use the finally block to kill resources like closing database connection, closing files and other resources such that they get executed independent of whether the code worked in Try or went to Catch.
77 Performance Avoid writing very long methods. A method should typically have 1-25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods
78 Performance Use server.transfer in place of response.redirect to optimise the client-server traffic. Use “server.transfer” instead of “Response.redirect” to prevent cross site request forgery. Use POST method instead of GET method. If somewhere GET method is needed then use TOKENS.
79 Performance Keep Your Datasets Lean - Remember that the dataset stores all of its data in memory, and that the more data you request, the longer it will take to transmit across the wire. Therefore, only put the records you need into the dataset.
80 Performance Connection Pooling and Object Pooling - Connection pooling is a useful way to reuse connections for multiple requests, rather than paying the overhead of opening and closing a connection for each request. It's done implicitly, but you get one pool per unique connection string. Make sure you call Close or Dispose on a connection as soon as possible. When pooling is enabled, calling Close or Dispose returns the connection to the pool instead of closing the underlying database connection.
81 Performance Use SqlDataReader Instead of Dataset wherever it is possible - If you are reading a table sequentially, you should use the DataReader rather than DataSet. DataReader object creates a read only stream of data that will increase your application performance because only one row is in memory at a time.
82 Performance Avoid Inefficient queries in stored procedures - Queries that process and then return more columns or rows than necessary waste processing cycles that could best be used for servicing other requests. Too much data in your results is usually the result of inefficient queries. The SELECT * query often causes this problem. You do not usually need to return all the columns in a row. Also, analyze the WHERE clause in your queries to ensure that you are not returning too many rows. Try to make the WHERE clause as specific as possible to ensure that the least number of rows are returned. Queries that do not take advantage of indexes may also cause poor performance.
83 Performance Avoid too many open connections - Connections are an expensive and scarce resource, which should be shared between callers by using connection pooling. Opening a connection for each caller limits scalability. To ensure the efficient use of connection pooling, avoid keeping connections open and avoid varying connection strings.
84 Performance Avoid Transaction misuse - Transactions are necessary to ensure the integrity of your data, but you need to ensure that you use the appropriate type of transaction for the shortest duration possible and only where necessary.
85 Performance Avoid Over Normalized tables - Over Normalized tables may require excessive joins for simple operations. These additional steps may significantly affect the performance and scalability of your application, especially as the number of users and requests increases.
86 Performance Manually create stored procedures and do not use CommandBuilder at Run Time - CommandBuilder objects such as SqlCommandBuilder and OleDbCommandBuilder are useful when you are designing and prototyping your application. However, you should not use them in production applications.
87 Performance Avoid Auto-Generated Commands - When using a data adapter, avoid auto-generated commands. These require additional trips to the server to retrieve meta data, and give you a lower level of interaction control.
88 Performance Index the tables and choose the indexes as required.
89 Performance Precompile pages so that users do not have to experience the batch compile of the ASP.NET files; it will increase the performance that the users will experience
90 Performance Disable view state for the page and server controls as much as possible and use hidden fields to replace view state whenever possible. The ASP.NET view state is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks. The view state of a page is, by default, placed in a hidden form field named __VIEWSTATE. This hidden form field can easily get very large, on the order of tens of kilobytes. Not only do large view states cause slower downloads, they also lengthen postback request times because the contents of this hidden form field must be included in the HTTP post back request. Unlike most other features of ASP.NET, view state can impact web pages dramatically, not only be in page size but also in server side performance. Moreover, pages with large view states can throw unexpected errors.
91 Performance Use INNER JOIN in place of IN within stored procedures to improve performance
92 Practices Use String.Compare while comparing Strings and do not Use ToLower when comparing strings
93 Practices Use the ternary conditional operator only for trivial conditions. Avoid complex or compound ternary operations in conditional blocks
94 Practices Avoid evaluating Boolean conditions against true or false
95 Practices Use Null-Coalescing Operator to set Default Values
96 Practices Use ELMAH for error logging
97 Scalability Normalize the database up to 3rd normal form. All tables should have a primary key. All fields in tables should have atomic values. There should be no repeating group of fields in tables. The non-key fields in each table must be functionally dependant on primary key field. The non-key fields must not be calculated
98 Scalability Use SSL for pages that accept credit card or other confidential information from users.
99 Scalability Whenever you use data reader always close the datareader once the reading is completed. Otherwise it creates memory leakage.
100 Scalability Always create a web project and not web site in visual web developer / visual studio IDE
101 Scalability Remove duplicate Java script code in the Java Script files
102 Scalability Do not hard code any values in class (.cs) files; rather get those values from database tables
103 Scalability Do not store large objects in session. Storing large objects in session may consume lot of server memory depending on the number of users
104 Security Use type safe SQL parameters in stored procedures. Parameter collections such as SqlParameterCollection provide type checking and length validation. If you use a parameters collection, input is treated as a literal value, and SQL Server does not treat it as executable code. An additional benefit of using a parameters collection is that you can enforce type and length checks. Values outside of the range trigger an exception. This is a good example of defence in depth
105 Security Encrypt the connection strings in web.config
106 Security Validate the data before you save it into the database. For important validation logic write the validation code in both client side and server side (to account for JavaScript disabled scenarios)
107 Security With file upload control only allow a set of predefined extensions to restrict malicious files
108 Security Use CAPTCHA control on registration and enquiry pages if it is acceptable to client
109 Security Use keystroke validation to block entry of special characters (example - ", ', =, %, $, #, %, &, , etc) in data entry fields like text box or text area or rich text box.
110 Security Comprehensive exception handling use try-catch-finally blocks. Never show exception string to users. Do not show the database related error/exception information directly to the user. Handle the exception and show a relevant error message. Exception handling should not be used to control the logic flow in the application. System should NEVER display the exception error message to the user. Make various variations of custom error pages for different error categories. Error page must be in nice graphical and user friendly format.
111 Security Do not save sensitive data like passwords in plain text format; rather encrypt the password before you save it in database. Store all passwords in encrypted format with hashing. Algorithms like Rinjdael or SHA!, SHA2 can be considered
112 Security Do not pass important information like passwords in query strings. If we pass sensitive data in query string, it will show the value in browser address bar, which violates the user privacy. Important and sensitive information such as user passwords and Social Security numbers etc should be encrypted while storing in the Database.
113 Security Do not save user credit/bank information in database while dealing with payment transactions, save the transaction ID coming from the payment gateway in database
114 Security Use Page.Validate followed by If (Page.isValid) {} to ensure server side validation as a protection to ensure validation of user input against disabling of javascript in browser.
115 Security Stored Procedures must be within the Try...Catch block
116 Security The application should use using customized sessions and after authentication it should store the particular userid in session variable. Validate the session on each page and expire it on sign out.
117 Security The application must verify if a user is authorised to perform the transactions. The application authenticates the user by using login screen and permissions given by the administrator (these define the permission for transactions). Validate user's permissions on the target "OBJECT" which consists of "Operation" +
Resource on which operation will be performed".
118 Security Prevent cross site scripting by using ‘HTMLEncode’ methods before writing data to browser’s DOM. Please avoid using FCK editor as it has known issues related to cross site scripting.
119 Usability Use Maintain Scroll Position on Post Back in page directive
120 Usability Declare Default Focus and Default Button in form or panel tag or on page load event in data entry forms
121 Usability Display the link for deleting any entity only if the user has the permission. Double check before deleting by asking a confirmation from user such as "Are you sure you want delete? This operation cannot be undone later.