Today, I spent some time trying to debug an error I was getting with some of my ASP .Net 2.0 pages.

All of sudden IIS wouldn’t load my pages saying that they did not extend System.Web.UI.Page, when on inspection of the codebehind file I was sure they did.

The problem was that I ran a Resharper 2.0 – Reformat Code (ctrl-alt-f) on my web application with the shorten references item checked. This changed the way in which the page directive worked on the aspx page.

Following is an example that illustrates what the file was originally defined as and what the reformat did to it to cause the application to blow up.

Original syntax


<%@ Page language="c#"
               Codebehind="default.aspx.cs"
               AutoEventWireup="True"
               Inherits="Com.CompanyName.Default"
               EnableSessionState="False"
               EnableViewState="False"%>


  
    Don't use reformat code with shorten references checked.
  
		


Resharper Reformat


Resharper Reformat Code Syntax


<%@ Page language="c#"
        Codebehind="default.aspx.cs"
        AutoEventWireup="True"
        Inherits="Default"
        EnableSessionState="False"
        EnableViewState="False"%>
<%@ Import namespace="System.Web.UI.WebControls"%>
<%@ Import namespace="Com.CompanyName"%>


  
    Don't use reformat code with shorten references checked.
  
				


The reformatted syntax takes the namespace of the Inherits attribute in the Page directive shortening it to “Default” from “Com.CompanyName.Default”. To do this, it has imported the “Com.CompanyName” namespace into the aspx page.

Now because .Net 2.0 defaults non-namespaced elements to the global namespace, the designer file, no longer belongs to the Com.CompanyName namespace however the codebehind page still does.

This causes the conflict throwing the error.

The error message

A trap for young players.

Sometimes it’s necessary to access a method/property on a Page from the UserControl code.

Eg.

We have a Page that has a label on it. A UserControl is embedded in that page. The UserControl has a DropDownList of values. When the value in the DropDownList is changed, we want the UserControl to change the value of Page’s label to reflect the selected value of the drop down list.

Now because the UserControl is associated with the Page using aggregation and there is no reference back to the Page instance it becomes a little tricky to do this.

We could pass a reference to the label in the UserControl but once we do that, we are creating a tighter coupling between the Page and UserControl thus making it difficult to re-use the UserControl for Pages that don’t have a label that needs modification.

Don’t worry though! The Event Handler (or Observer) pattern is very handy and comes into play to enable a communication mechanism that gets around the coupling problem.

In the UserControl declare a public property that accepts and returns an EventHandler delegate.

Eg.



public class ExampleUserControl : UserControl {

	protected DropDownList automobileTypes;
	private EventHandler automobileChangeHandler;

	public EventHandler AutomobileChangeHandler {
		get { return automobileChangeHandler; }
		set { automobileChangeHandler = value; }
	}

Now call the declared EventHandler at the appropriate execution point.

Eg.



	...
        ...

	private void InitializeComponent() {
 	     this.Load += new System.EventHandler(this.Page_Load);
             automobileTypes.SelectedIndexChanged += new EventHandler(automobileTypes_SelectedIndexChanged);
	}

	private void automobileTypes_SelectedIndexChanged(object sender, EventArgs e) {
		if (AutomobileChangeHandler != null) {
			AutomobileChangeHandler(automobileTypes.SelectedValue, e);
		}

	}

In the Page class create a method to be executed by the UserControl’s event handler. Define the logic that the UserControl’s event is to trigger on the Page object.

Eg.



public class ExamplePage : Page {

	protected Label name;
	protected ExampleUserControl euc; 

	private void ExampleUserControl_Changed(object sender, EventArgs e) {
		name.Text = String.Format("You have selected - {0}", sender as string);
	}

        override protected void OnInit(EventArgs e) {
		InitializeComponent();
		base.OnInit(e);
	}

	private void InitializeComponent() {
		this.Load += new System.EventHandler(this.Page_Load);
		euc.AutomobileChangeHandler += new EventHandler(ExampleUserControl_Changed);
	}

	#endregion
}

Thus allowing a UserControl to trigger events in the page object, without explicitly knowing about the class in which the UserControl resides.

0

Formatting using Eval

Posted in Asp.Net, C# at November 20th, 2006 by Gerrod / No Comments »

I can never remember the syntax to format a string when using the Eval statement, so once and for all I decided to try and commit it to memory by writing it down here.

In a DataBound control, you can use Eval to evaluate a public property on the DataItem that is being bound to the control. For example, if your DataItem has a public property called Name, you may use this statement to output the value of the property:

<%# Eval("Name") %>

The Eval method also has an overload which takes a format string. So far as I can figure, this format string is used in a similar vain to String.Format, whereby you supply the formatting string by numbered parameters. (Aside: The numbering system seems pretty pointless to me, since you’d almost always have only a single parameter to pass, wouldn’t you?).

Anyway – to get to the point – you can use the format string as follows: Presuming your DataItem has a property called “StartDate” which returns a DateTime, you can format the DateTime in the format “1 Nov 2006″ using the following code:

<%# Eval("StartDate", "{0:dd MMM yyyy}") %>

1

function $

Posted in Asp.Net, Javascript at November 16th, 2006 by Gerrod / 1 Comment »

A while back, Bender sent me a link to a prototype.js file that pretty much claimed to be a web developers best friend. It certainly has some interesting features, and one that I really liked was the “$” function. Basically, the developer had written the function to return you an array of the elements that you asked for by id. So in effect, if you wrote -

var elements = $("txtName", "txtPhone", "txtCountry");

- then you would be returned an array containing a reference to each of those form elements (presuming that they exist, of course ;-) )

Well that’s all fine and dandy, but more often than not I find myself trying to find elements in that are declared as: runat=”server”. And if those elements are nested in a UserControl, then you have to know how their id will be transformed at runtime by ASP.NET (for example, “txtName” may become “ctl00_main_sidebar_txtName”). So, with this in mind, I wrote my own version of the $ function which took care of this situation for me:


/*
 * Find an element based on the provided strings
 *
 * elementId:   Server-side id of the element to find (e.g. "txtName")
 * tagName:     The runtime tag of the element (e.g. "input")
 * elementType: The runtime value of the "type" attribute for the element,
 *              if it exists (e.g. "text")
 */
function $(elementId, tagName, elementType) {
    if (!tagName || tagName == "") {
        return document.getElementById(elementId);

    } else if (tagName) {
        var elements = document.getElementsByTagName(tagName, "gi");
        var typeRegex = elementType && elementType != "" ? new RegExp(elementType) : null;

        for (var i = 0; i < elements.length; i++) {
            if (typeRegex) {
                if (!elements[i].type || !typeRegex.exec(elements[i].type)) {
                    continue;
                }
            }

            if (elements[i].id && elements[i].id.indexOf(elementId) >= 0) {
                return elements[i];
            }
        }
    }

    return null;
}

It’s possibly not the most efficient piece of code that you’ll ever come across, but it does the job perfectly.