PROWAREtech

articles » archived » asp-net » tips-and-tricks

ASP.NET: Tips and Tricks

Useful tips for ASP.NET (.NET Framework).
  1. The web_site\App_Code folder is meant for classes (.vb and .cs files), .wsdl files and typed datasets. Items stored in this folder are automatically available to the site's pages. The web_site\Bin folder is meant for compiled assemblies (.dll files). Assemblies in the Bin folder do not need to be registered. The presence of a .dll file in the Bin folder is sufficient for ASP.NET to recognize it.
  2. The web_site\App_Data folder is meant for storing databases and other data stores, like XML files, used by the website. This folder's contents are secure and browsers cannot directly access their contents.
  3. The web_site\App_Browsers folder holds .browser files used to identify the browsers making requests.
  4. The first time .ASPX pages are accessed after changes have been made to them, they have to be compiled into a DLL. Compiling takes time and the browser experiences a lag. To precompile large websites, open a command window (cmd.exe) navigate to:
    C:\Windows\Microsoft.NET\Framework\v.2.0.50727\
    and enter:
    aspnet_compiler -p "C:\Inetpub\web_site"
  5. The compiled assemblies for website pages are be located in:
    C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
    .
  6. The Global.asax file as generated by Visual Studio:
    <%@ Application Language="VB" %>
    
    <script runat="server">
    
    	Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    		' Code that runs on application startup
    	End Sub
    	
    	Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
    		' Code that runs on application shutdown
    	End Sub
    		
    	Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    		' Code that runs when an unhandled error occurs
    	End Sub
    
    	Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    		' Code that runs when a new session is started
    	End Sub
    
    	Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
    		' Code that runs when a session ends. 
    		' Note: The Session_End event is raised only when the sessionstate mode
    		' is set to InProc in the Web.config file. If session mode is set to StateServer 
    		' or SQLServer, the event is not raised.
    	End Sub
    
    </script>
    
    • Application_Start is called when the application receives its first request. This is where to setup application-level variables that must be maintained across all users.
    • Session_Start is called each time a new user accesses the website for the first time.
    • Application_BeginRequest (not listed above) is called before every request made by the user.
    • Application_AuthenticateRequest (not listed above) is called for each request and allows the setting up of custom authentication.
    • Application_Error is called when there is an unhandled error.
    • Session_End is called when a user leaves the website application. Must be running in InProc (In-process) mode which is the default.
    • Application_End is called when the website application ends.
  7. Output Caching is done to increase performance on pages that don't change frequently. For example, to enable 60 second caching for a page specify the following page directive:
    <%@ OutputCache Duration="60" VaryByParam="None" %>
  8. This will enable caching and will ignore the QueryString parameters, so one page will be cached regardless of parameters. To create new versions of the cached page by parameter, specify the QueryString parameters in VaryByParam:
    <%@ OutputCache Duration="60" VaryByParam="ID;USER" %>
  9. This will create the number of ID parameters times the number of USER parameters of cached pages. The amount of server memory will become a factor for large websites. To cache a new version of the page for all the QueryString variations change VaryByParam to an asterisk:
    <%@ OutputCache Duration="60" VaryByParam="*" %>
  10. Common system classes used by ASP.NET applications as entered in web.config:
    <system.web>
    	<pages>
    		<namespaces>
    		<clear/>
    			<add namespace="System"/>
    			<add namespace="System.IO"/>
    			<add namespace="System.Collections"/>
    			<add namespace="System.Collections.Specialized"/>
    			<add namespace="System.Configuration"/>
    			<add namespace="System.Text"/>
    			<add namespace="System.Text.RegularExpressions"/>
    			<add namespace="System.Web"/>
    			<add namespace="System.Web.Caching"/>
    			<add namespace="System.Web.SessionState"/>
    			<add namespace="System.Web.Security"/>
    			<add namespace="System.Web.Profile"/>
    			<add namespace="System.Web.UI"/>
    			<add namespace="System.Web.UI.WebControls"/>
    			<add namespace="System.Web.UI.WebControls.WebParts"/>
    			<add namespace="System.Web.UI.HtmlControls"/>
    			<add namespace="System.Xml"/>
    			<add namespace="System.Data"/>
    			<add namespace="System.Data.Common"/>
    			<add namespace="System.Data.OleDb"/>
    			<add namespace="System.Data.SqlClient"/>
    			<add namespace="System.Data.SqlTypes"/>
    			<add namespace="System.Configuration"/>
    		</namespaces>
    	</pages>
    </system.web>
  11. To re-use a web form in other website application pages, convert it into a user control by:
    • changing the file extension to .ascx
    • removing the <html>, <head>, <title>, <body> and <form> tags
    • removing all attributes from the @ Page directive except Language, AutoEventWireup, CodeFile and Inherits
    • changing the @ Page directive to the @ Control directive
    • including a className attribute in the @ Control directive
    • renaming the code-behind file to have the file name extension .ascx.vb or .ascx.cs
    • opening the code-behind file and changing the class from which it inherits from Page to UserControl
    When development is done and it is time to deploy the website application, set debug="false" in web.config.
    <compilation debug="false"/>
    Alternatively, <compilation debug="false"/> can be enabled for all website applications on a machine by setting the following in machine.config.
    <system.web>
    	<deployment retail="true"/> 
    </system.web>
  12. Set the @ Page attribute AspCompat="true" to use components developed with Visual Basic 6.0 requiring access to the ASP built-in objects. Use Server.CreateObject() to create a late-bound instance of a COM component. Late-bound means it uses the IDispatch interface. If AspCompat="true" then Server.CreateObject() creates the COM object regardless of its threading model. If AspCompat="false" then Server.CreateObject() checks if the threading model is apartment or if no threading model is specified and throws an exception. Setting AspCompat="true" makes ASP intrinsic objects available to the COM component. ASP.NET creates unmanaged ASP intrinsic objects (Request, Response, etc.) and passes them to the COM component used in the page.
    Dim objCOM As Object = Server.CreateObject("PROGRAM.ID")
  13. Browsers can cache ASP.NET page output. To disable them from caching pages set:
    	Response.AddHeader("Pragma", "no-cache")
    	Response.CacheControl = "no-cache"
    	Response.Cache.SetAllowResponseInBrowserHistory(False)
    	Response.Cache.SetCacheability(HttpCacheability.NoCache)
    	Response.Cache.SetNoStore()
    	Response.Expires = -1
  14. Set @ Page attribute ValidateRequest="false" to prevent ASP.NET from checking for HTML tags in request input data (form data and querystring data).
  15. Set @ Page attribute SmartNavigation="true" to enable Internet Explorer 5.01 or later to use its smart navigation feature. Smart navigation allows a page to be refreshed without losing element focus and scroll position. On an Intranet, where everyone could be using Internet Explorer, navigation could be made easier for the user.
  16. To enable server-side validation, add the EnableClientScript="false" attribute to each validator control then call Page.Validate() after checking that the request is a post back (with Page.IsPostBack property) and then check the Page.IsValid property to see that all validations check. It's good practice to always run server-side validation checks just incase the client doesn't support it or ASP.NET doesn't recognize the browser.
    	If Page.IsPostBack Then
    	Page.Validate()
    	If Page.IsValid Then
    		'Save the form here
    	End If
    End If
  17. Set the control focus using server-side code by calling control_name.Focus().
    <%@ Page Language="VB" %>
    <script runat="server">
    	Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    		If Not Page.IsPostBack Then
    			Textbox1.Focus()
    		End If
    	End Sub
    </script>
    <html>
    <head>
    	<title></title>
    </head>
    <body>
    	<form id="form1" runat="server">
    	<div>
    	<input type="text" id="Textbox1" runat="server" />
    	</div>
    	</form>
    </body>
    </html>
  18. One way to check if a page is processing a POST request is by checking the REQUEST_METHOD server variable for a value of "POST". Use this method when not using Web Forms.
    If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
    	'block of code
    End If
  19. Don't connect to SQL Servers as 'sa'. This leaves a database open to the bugs in the ASP.NET application. Setup a login and user with only read and write access to the database. The user doesn't need to alter a table or drop a database like 'sa' can!
  20. Make a database unicode friendly and allow an application to support non-European languages. First, make sure the database is using datatypes that support unicode, like nchar, nvarchar and ntext. Second, use the N prefix before strings using these datatypes. For example, an INSERT statement would look like this:
    INSERT INTO TABLE (identifier,full_name) VALUES (1909,N'name here')
  21. Always use the StringBuilder class because of its efficiency in working with strings; your server will be able to handle more traffic.
  22. Do not forget to include the 'Content-Type' header when submitting a POST body with XMLHttpRequest() (This is not required for "multipart/form-data").
    var x = XMLHttpRequest();
    x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    
  23. Instead of InnerHtml, use InnerText. Unlike the InnerHtml property, InnerText provides automatic HTML encoding and decoding.
  24. Use System.DBNull.Value.Equals(value) to check for nulls when using OLEDB or SQL client. When using LINQ, just check for the value of null.
  25. Use String.IsNullOrEmpty(str) or String.IsNullOrWhiteSpace(str) to detect the presence of a value in a string.
  26. For database connections, use connectionStrings:
    System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString()
    to access in web.config:
    <configuration>
    	<connectionStrings>
    		<add name="conn" providerName="System.Data.OleDb" connectionString="Provider=SQLOLEDB;Data Source=SQLSERVER;Initial Catalog=DatabaseName;User ID=UserName;password=pwd;"/>
    	</connectionStrings>
    </configuration>
  27. For application settings, use appSettings:
    System.Configuration.ConfigurationManager.AppSettings["ContactEmail"]
    to access in web.config:
    <configuration>
    	<appSettings>
    		<add key="ContactEmail" value="mailbox@domain.com"/>
    	</appSettings>
    </configuration>
  28. Include the text from a file. This included text is not processed by ASP.NET. It is dead text.
    <!-- #include virtual="privacy_policy.inc" -->
  29. Specify the ClientIDMode="Static" attribute to prevent ASP.NET from changing the assigned ID values of controls. This way one can use client-side JavaScript to access the elements.

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE