ASP.net Tip: Register User/Custom Controls globally



Generally when adding/dropping an user/custom control to a page, we use/used to use the @Register directive to reference our controls (or the IDE did it for you), like this:
 
...
<%@ Register Src="Controls/SomeControl.ascx" TagName="SomeControl" TagPrefix="cstruter" %>
<%@ Register Assembly="ServerControl" Namespace="ServerControl" TagPrefix="somevendor" %>
...
<body>
    <form id="form1" runat="server">
    <div>
        <cstruter:SomeControl ID="SomeControl1" runat="server" />
        <somevendor:ServerControl1 ID="ServerControl11" runat="server" />
    </div>
    </form>
...
 

Now this is bit of a dodgy situation, since whenever we want to use these controls we need to add the directive above each and every page - which obviously is a bit of a bad idea.

It would make a lot more sense to register these controls somewhere globally - which is exactly what we can do since ASP.net 2.0, observe:
 
<system.web>
...
    <pages>
      <controls>
	  ...
        <add src="~/Controls/SomeControl.ascx" tagName="SomeControl" tagPrefix="cstruter" />
        <add assembly="ServerControl" namespace="ServerControl" tagPrefix="somevendor" />
...
 

Which means we can simply remove the @Register directives from our pages, since the references to our controls are available via the web.config now.

Note: If you look closely you will notice I added the tilde sign infront of the path where the usercontrol in the example resides - which resolves the path to the root of the web application.




Post/View comments
 

ASP.net 2.0 (.net 3.5 SP1): URL Routing



In the previous post we had a quick look at the routing functionality in ASP.net 4.0. essentially means (for example) http://somehost/test.aspx?id=1 becomes http://somehost/tester/1

Routing was originally added via .net 3.5 SP1 for use with the Microsoft MVC framework, but with regards to Web Forms, Microsoft only added some real support in ASP.net 4.0.

It is however possible adding your own support for routing within ASP.net 2.0 & .net 3.5 SP1, lets have a quick look on how to achieve this.

Step 1: Add a reference to the System.Web.Routing assembly to your project.

Step 2: Make sure that you've got the required entries in your configuration file (e.g. web.config)
 
<system.web>
	<httpModules>
	...
		 <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
	</httpModules>
</system.web>
...
<system.webServer>
	<modules>
	...
		<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
	</modules>
	<handlers>
	...
		<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
	</handlers>	
</system.webServer>
...
 

Step 3: Next we're going to add some extension methods - which provides the same methods available within ASP.net 4.0.

RouteCollectionExtensions.cs
 
using System;
using System.Web.Routing;
 
public static class RouteCollectionExtensions
{
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile)
    {
        return MapPageRoute(route, routeName, routeUrl, physicalFile, null, null, null);
    }
 
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults)
    {
        return MapPageRoute(route, routeName, routeUrl, physicalFile, defaults, null, null);
    }
 
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults, RouteValueDictionary constraints)
    {
        return MapPageRoute(route, routeName, routeUrl, physicalFile, defaults, constraints, null);
    }
 
    public static Route MapPageRoute(this RouteCollection route, string routeName, string routeUrl, string physicalFile, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens)
    {
        if (routeUrl == null)
        {
            throw new ArgumentNullException("routeUrl");
        }
        Route item = new Route(routeUrl, defaults, constraints, dataTokens, new RouteHandler(physicalFile));
        route.Add(routeName, item);
        return item;
    }
}
 

We also need to define a handler for handling the request.

RouteHandler.cs
 
using System.Web;
using System.Web.Routing;
using System.Web.UI;
using System.Web.Compilation;
 
public class RouteHandler : IRouteHandler
{
    private string _physicalFile;
    public RouteHandler(string physicalFile)
    {
        _physicalFile = physicalFile;
    }
 
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        HttpContext.Current.Items["RouteData"] = requestContext.RouteData;
        return BuildManager.CreateInstanceFromVirtualPath(_physicalFile, typeof(Page)) as Page;
    }
}
 

Step 4: Next we need to add the routes to the global.asax.
 
void RegisterRoutes(RouteCollection routes)
{
	routes.MapPageRoute("testroute", "tester/{id}", "~/test.aspx",
		new RouteValueDictionary { { "id", "1" } }, 		// default value
		new RouteValueDictionary { { "id", @"^\d+$" } }); 	// constraint e.g. only numerals            
}
 
void Application_Start(object sender, EventArgs e)
{
	RegisterRoutes(RouteTable.Routes);
}
 

Within the page we're routing to, we access the routing data like this:
 
public System.Web.Routing.RouteData RouteData
{
	get
	{
		return HttpContext.Current.Items["RouteData"] as System.Web.Routing.RouteData;
	}
}
 
protected void Page_Load(object sender, EventArgs e)
{
	Response.Write(RouteData.Values["id"]);
}
 





Post/View comments
 
First 21 22 23 24 25 26 27 28 29 30 Last / 62 Pages (124 Entries)

Latest Posts

Be the best stalker you can be


2011-12-13 22:33:54

Syntactic sugar (C#): Enum


2011-08-04 16:50:18

Top 5 posts

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51