Sunday, February 28, 2010

How to get Fiddler to work under Windows 7

If you try to trace your web applications using Fiddler with default settings under Windows 7, you will get the following error in your browser:


[Fiddler] Connection to localhost. failed.
Exception Text: No connection could be made because the target machine actively refused it ::1:80

This can be fixed by disabling IPv6 in Fiddler:


1. Go to Fiddler, then Tools > Fiddler Options.
2. Uncheck "Enable IPv6 (if available)".

Tracing should now work.

How to get Fiddler to trace localhost traffic

Fiddler is a great tool for tracing the HTTP traffic for your web applications. However, if you try to trace http://localhost/ you will see that it does not work. This can be fixed by either using the machine name or adding a dot at the end of the localhost address:

http://mycomputername/

or

http://localhost./

Wednesday, February 10, 2010

A generic FindControl extension method

In order to clean up and make our code more readable, generics and extension methods comes in very handy. In ASP.NET, the Control class has a FindControl method which is used as follows:


((TextBox) Page.FindControl("TxtName")).Text = "Some name";

Since this method returns a Control type, we must cast it to it's actual type before we can access any of it's members. A way to improve this code, is to create a new generic FindControl method. Since all the controls in ASP.NET such as Page, Button, TextBox, inherits from the Control class, we can make this method an extension method. By doing this, our method can be accessed the same way as the non-generic FindControl method:


Page.FindControl("TxtName").Text = "Some name";

This code is tidier and easier to read. Here is the code for the extension method:


public static class ControlExtensions
{
 public static T FindControl(this System.Web.UI.Control control, string id)
  where T : System.Web.UI.Control
 {
  return (T) control.FindControl(id);
 }
}

Always wire your events in the code behind, NOT in the aspx/ascx template file

With ASP.NET you can wire your events in the aspx/ascx template file or in the code behind file. If you wire your events in the template file, you will not get compile time support. This means that if a method is renamed or removed without updating the template file, the compiler will not throw an error. However, if the event is wired in the code behind, an error will be thrown. Events should therefore always be wired in the code behind.
Template file event wiring - not recommended:
<asp:Button runat="server" ID="BtnSave" OnClick="Save" Text="Save" />
Code behind event wiring - recommended:
protected override void OnInit(EventArgs e)
{
 base.OnInit(e);

 BtnSave.Click += new EventHandler(Save);
}