Click here to Skip to main content
15,885,365 members
Articles / Web Development / ASP.NET

Page events lifecycle simplified

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
20 Mar 2012CPOL 8.6K   66   2  
Custom baseclasses to simplify the page events lifecycle
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;

namespace Website.Core
{
	public static class Extensions
	{
		public static T FindControl<T>(this Control ctrl, string id)
			where T : Control {
			return FindControl<T>(ctrl, ctrl.Page, id);
		}
		public static T FindControl<T>(this Control ctrl, Control startControl, string id)
			where T : Control {
			T found = startControl.FindControl(id) as T ?? FindChildControl<T>(ctrl, startControl, id);
			return found;
		}
		public static T FindChildControl<T>(this Control ctrl, Control startControl, string id)
			where T : Control {
			T found;
			foreach (Control c in startControl.Controls) {
				found = c as T;
				if (found == null || (!String.IsNullOrEmpty(id) && (String.IsNullOrEmpty(found.ID) || !found.ID.Equals(id))))
					found = FindChildControl<T>(ctrl, c, id);
				if (found != null)
					return found;
			}
			return null;
		}
		public static T FindFirstControl<T>(this Control ctrl)
			where T : Control {
			return FindChildControl<T>(ctrl, ctrl.Page, null);
		}

		public static List<T> FindControls<T>(this Control ctrl)
			where T : Control {
			return FindControls<T>(ctrl, ctrl.Page);
		}
		public static List<T> FindControls<T>(this Control ctrl, Control startControl)
			where T : Control {
			var controls = new List<T>();
			foreach (Control c in startControl.Controls) {
				if (c is T)
					controls.Add(c as T);
				if (c.HasControls())
					controls.AddRange(FindControls<T>(ctrl, c));
			}
			return controls;
		}

		public static void Redirect301(this HttpResponse response, string url) {
			response.Clear();
			response.Status = "301 Moved Permanently";
			response.AddHeader("Location", url);
			response.End();
		}
		public static void Redirect404(this HttpResponse response) {
			response.Clear();
			HttpContext.Current.Server.Transfer("/404.aspx");
		}

		public static string GetIpAddress(this HttpRequest request) {
			return request.ServerVariables["REMOTE_ADDR"];
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Belgium Belgium
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions