Friday, March 25, 2011

Performance - Using ViewState for dropdownlist and binding the first time vs Turning off viewstate and binding dropdownlist on each postback with a static data table

Static variables are stored in special area inside Heap known as High Frequency Heap.

***Incomplete***

Notes on Validation Controls

SetFocusOnError property on a validation control: This property, if set to True, causes the Web control the validation control is operating on to receive focus if the validation control is invalid. This is a nice little usability touch that your users will likely appreciate.



EnableClientScript property on validation control:Leaving the default value (true) of EnableClientScript is a first line of defense, good for 90% of situations. Leaving EnableClientScript as default or setting it to true avoids a postback. If you look at the page source with property setting EnableClientScript="false", you will see some javascript that does the client side validation without posting back. If you look at the page source with property setting EnableClientScript="true", you will see not see any javascript in the source.

You should also check the value of Page.IsVaild in your code behind to handle situations in which the client disabled JavaScript or otherwise circumvented your client-side validation


In Fritz Onion's Essential ASP.NET book:

"As soon as you place a validation control on a page, it is imperative that you check the IsValid flag of the Page class before using any of the data posted by the client. It is a common misconception that if validation fails on a page, the code for that page will not execute. On the contrary, the only thing that happens when server-side validation fails is that the IsValid flag of the Page class is set to false, and each validation control that failed renters itself as a visible span so that the error indicator shows up when the page is redisplayed to the user."

Wednesday, March 23, 2011

Improving performance

1. ScriptManager control has LoadScriptsBeforeUI property which you can set to “False” in order to postpone several script downloads after the content is downloaded. This adds the script references end of the tag. As a result, you see the content first and then the additional scripts, extenders, ACT scripts get downloaded and initialized.

< asp:ScriptManager ID =”ScriptManager1″ runat =”server” EnablePartialRendering =”true” LoadScriptsBeforeUI =”false”> … asp:ScriptManager >

http://omaralzabir.com/fast_page_loading_by_moving_asp_net_ajax_scripts_after_visible_content/

2. Configure Compression (IIS 6.0)
To more efficiently use available bandwidth, it is advisable to enable IIS's HTTP compression feature. HTTP compression provides faster transmission time between compression-enabled browsers and IIS regardless of whether your content is served from local storage or a UNC resource. You can compress static files only, application response files only, or both static files and application response files. Compressing application response files is usually called dynamic compression.
Read this msdn link on how to enable compression
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/92f627a8-4ec3-480c-b0be-59a561091597.mspx?mfr=true

3. Do Not Use the Sp_ Prefix for Custom Stored Procedures
SQL Server always looks in the master database for a stored procedure that begins with the sp_ prefix. SQL Server then uses any supplied qualifiers such as the database name or owner. Therefore, if you use the sp_ prefix for a user-created stored procedure, and you put it in the current database, the master database is still checked first. This occurs even if you qualify the stored procedure with the database name. To avoid this issue, use a custom naming convention, and do not use the sp_ prefix.

4. View state can impact web pages dramatically, not only in page size but also in server side performance. Moreover, pages with large view states can throw unexpected errors. Disable viewstate when there is no need to persist state across postbacks.
consider disabling view state in these cases:
If the controls value is hard-coded.
If the controls value is assigned on every page.

5. Avoid long control names; especially ones that are repeated in a DataGrid or Repeater control. Control names are used to generate unique HTML ID names. A 10-character control name can easily turn into 30 to 40 characters when it is used inside nested controls that are repeated.

6. Something very interesting I came across while reading msdn is to "remove characters such as tabs and spaces that create white space before you send a response to the client. Removing white spaces can dramatically reduce the size of your pages. The following sample table contains white spaces.
// with white space
<table>
   <tr>
    <td>hello<td>
    </td>world</td>
  </tr>
</table>
The following sample table does not contain white spaces.

// without white space
<table<<tr><td>hello</td><td\>world</td></tr></table>
Save these two tables in separate text files by using Notepad, and then view the size of each file. The second table saves several bytes simply by removing the white space. If you had a table with 1,000 rows, you could reduce the response time by just removing the white spaces. In intranet scenarios, removing white space may not represent a huge saving. However, in an Internet scenario that involves slow clients, removing white space can increase response times dramatically. You can also consider HTTP compression; however, HTTP compression affects CPU utilization.

You cannot always expect to design your pages in this way. Therefore, the most effective method for removing the white space is to use an Internet Server API (ISAPI) filter or an HttpModule object. An ISAPI filter is faster than an HttpModule; however, the ISAPI filter is more complex to develop and increases CPU utilization. "

Now I need to figure out how to write an ISAPI filter to remove white space.

7. Install Runtime Page Optimizer (RPO). Refer to http://www.iis.net/community/default.aspx?tabid=34&g=6&i=1716. There is a price to it.
Or Write your own optimizer. You can start by reading this blog http://www.darkside.co.za/archive/2008/03/03/web-page-optmisation-using-httpmodule.aspx.

Monday, November 8, 2010

Keeping The WinForm UI responsive while doing background processing using delegates.

This can be achieved with Threading in windows forms
1) Never invoke any method or property on a control created on another thread other than Invoke, BeginInvoke, EndInvoke or CreateGraphics, and InvokeRequired.
Each control is effectively bound to a thread which runs its message pump. If you try to access or change anything in the UI (for example changing the Text property) from a different thread, you run a risk of your program hanging or misbehaving in other ways. You may get away with it in some cases, but only by blind luck. Fortunately, the Invoke, BeginInvoke and EndInvoke methods have been provided so that you can ask the UI thread to call a method for you in a safe manner.
2) Never execute a long-running piece of code in the UI thread.
If your code is running in the UI thread, that means no other code is running in that thread. That means you won't receive events, your controls won't be repainted, etc. This is a very Bad Thing.

So, if you have a piece of long-running code which you need to execute, you need to create a new thread to execute it on, and make sure it doesn't directly try to update the UI with its results. The interesting bit is - invoking a method on the UI thread in order to update the UI.

Each control is effectively bound to a thread which runs its message pump. If you try to access or change anything in the UI (for example changing the Text property) from a different thread, you run a risk of your program hanging or misbehaving in other ways. You may get away with it in some cases, but only by blind luck. Fortunately, the Invoke, BeginInvoke and EndInvoke methods have been provided so that you can ask the UI thread to call a method for you in a safe manner.
There are two different ways of invoking a method on the UI thread, one synchronous (Invoke) and one asynchronous (BeginInvoke). They work in much the same way - you specify a delegate and (optionally) some arguments, and a message goes on the queue for the UI thread to process. If you use Invoke, the current thread will block until the delegate has been executed. If you use BeginInvoke, the call will return immediately. If you need to get the return value of a delegate invoked asynchronously, you can use EndInvoke with the IAsyncResult returned by BeginInvoke to wait until the delegate has completed and fetch the return value.
MethodInvoker is just a delegate which takes no parameters and returns no value (like ThreadStart),


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;

namespace DelegateUIResponsive
{
public class ClsDelegateUIResponsive : System.Windows.Forms.Form
{
delegate void UpdateStatusDelegate (string Msg);
private System.Windows.Forms.Label lblStatus; //Displays status on the window.

private System.ComponentModel.Container components = null;

private ClsDelegateUIResponsive()
{
InitializeComponent();
MethodInvoker mi = new MethodInvoker(StartThread); // New thread.
mi.BeginInvoke(null, null);
}

[STAThread]
static void Main()
{
Application.Run(new ClsDelegateUIResponsive());
}

private void StartThread()
{
for (int i = 0; i < 10; i++)
{
ShowProgress("The counter is : " + i.ToString());
Thread.Sleep(1000);
}
}

private void ShowProgress(string Msg)
{
// We're not in the UI thread, so we need to call BeginInvoke
if (InvokeRequired)
{
BeginInvoke(new UpdateStatusDelegate(ShowProgress), new Object[]{ Msg });
return;
}
this.lblStatus.Text = Msg;
}
}
}

Tuesday, October 12, 2010

Sorting Algorithms Compared

Time
Sort Average Best Worst Space Stability Remarks
Bubble
sort
O(n^2) O(n^2) O(n^2) Constant Stable Always use a modified bubble sort
Modified
Bubble sort
O(n^2) O(n) O(n^2) Constant Stable Stops after reaching a sorted array
Selection
Sort
O(n^2) O(n^2) O(n^2) Constant Stable Even a perfectly sorted input requires scanning the entire array
Insertion
Sort
O(n^2) O(n) O(n^2) Constant Stable In the best case (already sorted), every insert requires constant time
Heap
Sort
O(n*log(n)) O(n*log(n)) O(n*log(n)) Constant Instable By using input array as storage for the heap, it is possible to
achieve constant space
Merge
Sort
O(n*log(n)) O(n*log(n)) O(n*log(n)) Depends Stable On arrays, merge sort requires O(n) space; on linked lists, merge
sort requires constant space
Quicksort O(n*log(n)) O(n*log(n)) O(n^2) Constant Stable Randomly picking a pivot value (or shuffling the array prior to
sorting) can help avoid worst case scenarios such as a perfectly
sorted array.

Monday, October 11, 2010

GridView, Columns, BoundField, TemplateField, ItemTemplate

GridView class displays the values of a data source in a table where each column represents a field and each row represents a record. The GridView control enables you to select, sort, and edit these items.
When the AutoGenerateEditButton property is set to true, a column (represented by a CommandField object) with an Edit button for each data row is automatically added to the GridView control. Clicking an Edit button for a row puts that row in edit mode. When a row is in edit mode, each column field in the row that is not read-only displays the appropriate input control, such as a TextBox control, for the field's data type. This allows the user to modify the field's value.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
    DataKeyNames="SalesOrderID,SalesDetailID" DataSourceID="DataSource1">

BoundField: Displays the value of a field in a data source. This is the default column type of the GridView control. To specify the field to display in a BoundField object, set the DataField property to the field's name.
Use the DataFormatString property to specify a custom display format for the values that are displayed in the BoundField object. If the DataFormatString property is not set, the field's value is displayed without any special formatting.


<columns>
 <asp:boundfield datafield="CustomerID" readonly="true" headertext="CustID"/>
 <asp:boundfield datafield="CompanyName" convertemptystringtonull="true"
   headertext="Customer Name"/>
<asp:BoundField DataField="ListPrice" HeaderText="ListPrice" 
   SortExpression="ListPrice" DataFormatString="{0:C}" />
</columns>


TemplateField: Displays user-defined content for each item in the GridView control according to a specified template. This column field type enables you to create a custom column field.



<Columns>   
<asp:TemplateField>
     <ItemTemplate>
            <img src='<%# Eval("pic_square") %>' alt="" />
     </ItemTemplate>
</asp:TemplateField>
       <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                 <%# Eval("name") %>
            </ItemTemplate>
      </asp:TemplateField>
<asp:TemplateField>
     <ItemTemplate>
         <asp:LinkButton ID="lnbSend" runat="server" CommandArgument='<%# Eval("uid") %>' OnCommand="lnbSend_Command">Send Message</asp:LinkButton>
     </ItemTemplate>
</asp:TemplateField>
</Columns>

Why use TemplateField instead of BoundField?

The GridView is composed of a set of fields that indicate what properties from the DataSource are to be included in the rendered output along with how the data will be displayed. The simplest field type is the BoundField, which displays a data value as text. Other field types display the data using alternate HTML elements. The CheckBoxField, for example, renders as a check box whose checked state depends on the value of a specified data field; the ImageField renders an image whose image source is based upon a specified data field. Hyperlinks and buttons whose state depends on an underlying data-field value can be rendered using the HyperLinkField and ButtonField field types, respectively.
While the CheckBoxField, ImageField, HyperLinkField, and ButtonField field types allow for an alternate view of the data, they still are fairly limited with respect to formatting. A CheckBoxField can only display a single check box, whereas an ImageField can display only a single image. What if a particular field must display some text, a check box, and an image, all based upon different data-field values? Or what if we wanted to display the data using a Web control other than the CheckBox, Image, HyperLink, or Button? Furthermore, the BoundField limits its display to a single data field. What if we wanted to show two or more data-field values in a single GridView column?
To accommodate this level of flexibility, the GridView offers the TemplateField, which renders using a template. A template can include a mix of static HTML, Web controls, and data-binding syntax. Furthermore, the TemplateField has a variety of templates that can be used to customize the rendering for different situations. For example, the ItemTemplate is used by default to render the cell for each row, but the EditItemTemplate template can be used to customize the interface when editing data.
To summarize here are the applications of TemplateFields
1. Combining two or more data-field values into one column
2. Expressing a data-field value using a Web control instead of text. Example: Displaying hire date using calendar control by setting the VisibleDate and SelectedDate properties to hiredate data field.
3. Used in displaying metadata about the GridView's underlying data. In addition to showing the employees' hire dates, for example, we might also want to have a column that displays how many total days they've been on the job.
4. Another use of TemplateFields arises in scenarios in which the underlying data must be displayed differently in the Web page report from the format in which it's stored in the database. Imagine that the Employees table had a Gender field that stored the character M or F to indicate the sex of the employee. When displaying this information in a web page we might want to show the gender as either "Male" or "Female", as opposed to just "M" or "F".

Sunday, October 10, 2010

Multi threading and Semaphores in C#

using System;
using System.Threading;

class SemaphoreDemo
{
static Sempahore semaphore = new Semaphore(3,3);
public static void Main()
{
for(int i=0; i<10; i++)
{
new Thread(SemaphoreDemo.DoSomething).Start(i);
}
}
static void DoSomething(object id)
{
Console.WriteLine(id+" wants to access the semaphore");
semaphore.WaitOne();
Console.WriteLine(id+" has succeeded to access the semaphore");
Thread.Sleep(1000);
Console.WriteLine(id+" is about to leave the semaphore");
semaphore.Release();
}
}