Add Custom Application Settings to web.config

ASP.NET provides for adding and then accessing configuration info specific to your app to the web.config file by using the <appSettings> element. Application configuration information is added by adding an child element to each parameter. Set the key attribute to the configuration parameter name, and then set the value attribute to the configuration parameter value:

 <appSettings> 
<add key="allowDataAccess" value="1" />
<add key="defaultDataOrder" value="Ascending" />
</appSettings>

When the ASP.NET app is started, ASP.NET creates a NameValueCollection from the key/value pairs in the  <appSettings> section. You can access the NameValueCollection anywhere in your app by using  the ConfigurationSettings object. Any data which can be represented as a string can be stored in the <appSettings> section, but note that data type other than a string will first need to be cast to from a string to that data type before being used  your app, for this reason your code should also incorporate exception handling for invalid data casts when the data is being accessed.


The below code demonstrates how to access the allowDataAccess configuration setting for the app. This is a boolean type (which is saved as a string):

Try

Dim allowDataBool as Boolean = ConfigurationSettings.AppSettings("allowDataAccess")

  If  allowDataBool Then
  '//Perform Data Access tasks
  End If

Catch ex As Exception

'//Perform error handling in the event that the allowDataAccess setting cannot be cast to a Boolean

End Try

Note that these settings are application wide and should not be used to set user specific settings, for this task consider either the Profile setting of ASP.NET Membership (for persistent information storage) or the Session object to store temporary information. Also be aware that changing the configuration settings in the web.config file will cause a restart of the application which will log out any current users.

Using RegisterStartupScript in ASP.NET

The RegisterStartupScript method is similar to the RegisterClientScriptBlock method. The major difference is that the RegisterStartupScript puts the script at the foot of the ASP.NET page as opposed to the top. The RegisterStartupScript method uses the same constructors as the RegisterClientScriptBlock method:

  • RegisterStartupScript (type, key, script)
  • RegisterStartupScript (type, key, script, script tag specification)

So what difference does it make to register the script at the foot of the page as opposed to the top? A lot, is the answer!
If you have JavaScript working with one of the controls on your page, you will not want your Javascript function to fire before the control is placed on the screen if it requires that control, therefore you should use the RegisterStartupScript method instead of RegisterClientScriptBlock.


For example, the below code listing creates a page that includes a simple control which contains a default value of    ASP.NET 101.

 <asp:TextBox ID="txtBox1" Runat="server">Hello ASP.NET</asp:TextBox>

Therefore use RegisterStartupScript to place a script on the page which uses the value in the txtBox1 control, as shown below:

protected void Page_Load(object sender, EventArgs e)
{
string myScript = @"alert(document.forms[0][’txtBox1’].value);";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"MyScript", myScript, true);
}

This puts the JavaScript function at the foot of the ASP.NET page, so when the JavaScript actually starts, it can find the txtBox1 control and works as planned.

Using RegisterClientScriptInclude in ASP.NET

The final method for registering Javascript in an ASP.NET page is the RegisterClientScriptInclude method. Most developers place JavaScript inside a .js file, which is considered best practice because it makes it simple to make global JavaScript changes to the app and .js pages are cached. You can register the script files on your ASP.NET pages using the ClientScriptInclude method as shown below:

string myJavaScript = "myJsCode.js";
Page.ClientScript.RegisterClientScriptInclude("myKey", myJavaScript);

This creates the following tag in your ASP.NET page:

Using RegisterClientScriptBlock in ASP.NET

The RegisterClientScriptBlock method enables you to put a JavaScript function at the top of a page. Thus, the script is in place for the startup of the page in the browser. Its use is illustrated
in the below listing.

<%@ Page Language="C#" %> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { string customScript = @"function myalert() { alert(’ASP.NET 101’); }"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CustomScript", customScript, true); } </script>
<script type="text/javascript">
<!--
function myalert() { alert(’ASP.NET 101’); }// -->
</script>
<div>
<input type="submit" name="Button1" value="Button" onclick="myalert();"
id="Button1" />
</div>

From the above listing you can see that you create the JavaScript function myalert() as a string named customScript. Using Page.ClientScript.RegisterClientScriptBlock you then program the script to be placed on the page. The two possible constructions of the RegisterClientScriptBlock method are the following:
- RegisterClientScriptBlock (type, key, script)
- RegisterClientScriptBlock (type, key, script, script tag specification)

50 Tips to Boost ASP.NET Performance – Part II

Continuing from ASP.NET Performance Tips Part 1 we now conclude with Performance Tips 26-50.

26. Batched Queries:

Queries can be used in a batch and thus network traffic can be reduced: Here is an example:

“Select EmpNo, EmpName, EmpAddress from Employee”;
“Select DepNo, DeptName From Department”;

From the above two queries it seems that there will be database hit twice .

Both the above queries can be executed in batched form and a single database hit will occur as follows:

“Select EmpNo, EmpName, EmpAddress from Employee; Select DepNo, DeptName From Department”;
27. Use IIS Compression

Page size can also be reduced using Http compression in IIS. Compression tool can also be used to reduced the size of rendered content.

28. Normalization

We should follow normalization rules in database table design but over Normalized tables can cause  excessive joins for simple requirement. We should not make excessive joins for performance overhead and hence it is better to normalize only as much as required keeping in mind the performance issue.

29. Efficient Coding

While coding we should keep in mind the below issues which are potential performance drains:

1.       Avoid use of Finalize method unless it is absolutely necessary.
2.       Make a class sealed if inheritance is not required.
3.       Avoid calling GC.Collect();
4.       Use X+=1 instead X=X+1 to avoid evaluating X twice;
5.       Use overloaded methods instead of different method names where possible.

30. Define The Scope of An Object

Defining an object’s scope properly increases efficient memory management and thus improve performance. We should keep the object scope at a lower level instead of a global level if possible because the garbage collector works more frequently on short lived object .

31. Using Loops

We should keep in mind while using loops in our code:

1.       Better to use for a loop instead of foreach.
2.       Do not create objects inside loop if not required absolutely.
3.       Calling methods and properties inside loops is expensive.
4.       Evaluating count etc. before loop starts. For example:

for(int i=0;i<Grid.Rows.Count;i++) {}can be written as
int iCount= Grid.Rows.Count; for(int i=0;i< iCount;i++){}

5.       Never write exception handling code inside loop. Keep the exceptions handling code outside of the loop for better performance.

32. Dispose Instead of Finalize

Avoid using Finalize unless it is absolutely necessary. It is normally better to dispose of unmanaged resources if no longer required.

33. Minimize Thread Creation

Avoid creating threads on a per-request basis. Also avoid using Thread.Abort or Thread.Suspend.

34. Leave Connection pooling Enable

Connection Pooling is enabled by default. It boosts application performance as existing connections can be re-used from the pool rather than created . Leave this option enabled.

35. Using Blocks

Using blocks can be used as a short form of try..finally and it should be used only for those objects that implement the iDisposable interface. Here is a code snippet.

Using(SqlConnection con=new SqlConnection(connectionString)
{
try
{
con.Open();

//some code
}
catch(Exception e)
{

}

}

In the above example,there is no need to dispose of the connection object. The Connection object will be disposed automatically when it is out of scope.
Continues…

50 Tips to Boost ASP.NET Performance – Part I

When we are looking to optimize the performance of  web applications we should keep in mind about Memory Load, Processor Load and Network Bandwidth. Here are 50  best practices to improve the performance and scalability of ASP.NET applications.

1. Page.IsPostBack Property

Keep code which only needs to be loaded once inside an IsPostBack block.

if(!IsPostBack)
{
BindDropDownList();
LoadDynamicControls();
}

As a result there will be no unnecessary database hits and server processing.

2. Enable Buffering

A buffer is a region in main memory to store temporary data for input and output .Data retrival from memory is faster than data retrieval from disk. We should leave buffering on unless there is any specific reason to turn it off. By default buffering is enable.

3. Remove unused HttpModules

There may be lot of HttpModules in Machine.Config that are not actually required for a particular application. In this scenario we should remove those unused HttpModules from application specific web.config file.

4. Trim Page Sizes

Reduce page size by removing any unnecessary space and tab characters from the page. As a result network traffic will be reduced.

5. Use a CDN

Not a performance tip exclusive to ASP.NET but an important step in speeding up a site is to use a Content Delivery Network (CDN) . CDN’s minimize the latency site visitors experience when they request a larger file from a data center that is located geographically far away. CDN’s cache files at numerous edge locations around the world to minimize latency.
If you are using Azure consider using the Windows Azure CDN , Amazon’s CloudFront cheap and easy to integrate into a website (if you happen to have a WordPress blog you can  integrate S3 and CloudFront into WordPress)

6. Server.Transfer and Response.Redirect

“To perform client side redirection in ASP.NET, users can call Response.Redirect and pass the URL. When Response.Redirect is called, the server sends a command back to the browser telling it to request the page redirected to it.  An extra roundtrip happens, which hit the performance.  We can send information from the source page by using a query string.  There is a limitation on the length of a query string; it cannot be used to pass large amounts of data over the wire.

To perform server-side redirection, users can use Server.Transfer.  As the execution is transferred on the server, Server.Transfer does not require the client to request another page.  In Server.Transfer, by using HttpContext we can access the source page’s items collection in target page.  The drawback of using this method is that the browser does not know that a different page was returned to it.  It displays the first page’s URL in the browser’s address bar.  This can confuse the user and cause problems if the user tries to bookmark the page.  Transfer is not recommended since the operations typically flow through several different pages.”

7. Precompiling

Precompiling an ASP.NET Web site provides faster initial response time for users because pages do not have to be compiled the first time they are requested. This is particularly useful for large Web sites that are updated frequently. In order to achieve that we can use ASP.NET Compilation Tool (Aspnet_compiler.exe).

8. Session State Management

Efficient state management helps to boost the performance and scalability of application. It is not advisable to keep large objects in a session variable and it is optimal to make disable session state whenever it is not required. We can turn session state off either at the Page level or at the application level using the  config file.

9. ViewState

By default the viewstate is enabled for applications and we should disable it whenever it is not required. Otherwise it will increase the page size. Every byte added to a web page by enabling its viewstate causes two bytes of network traffic – one in each direction. Disable

view state in any of the following scenarios:

(i)  A readonly page where there is no user input.

(ii) A  page that does not postback to the server

(iii) A page which requires rebuilding server controls on each post back without checking the post back data.

It is best practice to turn ViewState off at the application level and then enable it as required at the page or even control level.

10. Caching

Probably the number one performance tip is to use caching. In order to store static data caching is ideal one. There are different types of caching: Page output caching, Page fragment caching data caching and we have to select the correct type as per requirement.
In almost all scenarios at least a part of a page can be cached.

11. Locking and Shared Resources

Acquire shared resources late and release them as early as possible.  Avoid locking unless absolutely necessary.  Do not set lock on the “this;” it is better to use a private object to lock on as follows:

public Class Test
{
private stativ readonly objLock=new Object();
public static Test Singleton
{
lock(ObjLock)
{
return new test();
}
}

Continues…

ScriptManagerProxy Control – AJAX

When using Master pages, instead of using a separate ScriptManager control on every Content page, add a script manager to your Master page. Then, if there are separate usages on a particular Content page, you can use the ScriptManagerProxy control, which will inherit from the ScriptManager control on the Master Page, and set your needed, different properties on that control.

Change Master Page Depending on Browser

Did you know that, in your content pages, you can specify a certain masterpage, depending on the browser that’s hittin your page (at least IE and FireFox).

All you need to do is to add a section for each specific browser to your content page’s Page Directive:

ie:MasterPageFile="~/MyIE.master" mozilla:MasterPageFile="~/MyFireFox.master"

Javascript to alternate colours for table rows

<html>
<head>

<script language=”JavaScript” type=”text/JavaScript”>
function alternate(id){
 if(document.getElementsByTagName){ 
   var table = document.getElementById(id);  
   var rows = table.getElementsByTagName(“tr”);  
   for(i = 1; i < rows.length; i++){          
 //manipulate rows
     if(i % 2 == 0){
       rows[i].className = “even”;
     }else{
       rows[i].className = “odd”;
     }      
   }
 }
}
</script>
</head>

<body onload=”alternate(‘thetable’)”>
<table width=”100%” id=”thetable”>

<tr><td>first colour</td></tr>

<tr><td>second colour</td></tr>

<tr><td>first colour</td></tr>

<tr><td>second colour</td></tr>

</table>

</body>

</html>