using System; using System.Configuration; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using ChadSoft.Web.ResponseFilters; namespace ChadSoft.Web.Modules { public class PluggableNavigationModule : IHttpModule { private static Control _NavigationControl; public static Control NavigationControl { get { if (_NavigationControl == null) _NavigationControl = createNavigationControl(); return _NavigationControl; } } public void Init(HttpApplication context) { context.PostReleaseRequestState += context_PostReleaseRequestState; } public void Dispose() { } static void context_PostReleaseRequestState(object sender, EventArgs e) { RenderNavigation((HttpApplication)sender); } private static void RenderNavigation(HttpApplication app) { app.Response.Filter = new PluggableNavigationResponseFilter( app.Response.Filter, NavigationControl); } private static Control createNavigationControl() { var controlTypeName = ConfigurationManager. AppSettings["PluggableNavigation.NavigationControlType"]; if (string.IsNullOrEmpty(controlTypeName)) return new ErrorMessage(ErrorType.EmptyTypeName); var controlType = Type.GetType(controlTypeName, false); if (controlType == null) return new ErrorMessage(ErrorType.InvalidTypeName); var control = Activator.CreateInstance(controlType) as Control; return control ?? new ErrorMessage(ErrorType.CouldNotCreateInstance); } enum ErrorType { EmptyTypeName, InvalidTypeName, CouldNotCreateInstance } private class ErrorMessage : Label { private readonly ErrorType _error; public ErrorMessage(ErrorType error) { _error = error; Style["color"] = "red"; Style["font-size"] = "large"; Style["font-weight"] = "bold"; } public override string Text { get { var text = string.Empty; // TODO: It'd probably be nice if these messages were resources... switch (_error) { case (ErrorType.EmptyTypeName): text = "The PluggableNavigationModule has been activated, however you did not specify a control type to be used as the navigation control. Please specify the type name in the 'PluggableNavigation.NavigationControlType' AppSetting or remove this module."; break; case (ErrorType.InvalidTypeName): text = "The PluggableNavigation.NavigationControlType you specified is invalid or cannot be found."; break; case (ErrorType.CouldNotCreateInstance): text = "Unable to create an instance of the PluggableNavigation.NavigationControlType you specified (however we were able to find its Type)."; break; } return text; } set { } } } } }