AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=335&pId=-1
Sharing a User Control across Web Applications
page
by Thomas Z.
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 35439/ 77

Introduction
One of the major critics against the user controls is that everyone thinks that it is not possible to share them across multiple web applications and that you need to do some cut and paste to reuse them. Well, we will see in this article that this critic is wrong and that it is possible to share user controls across multiple applications. Lets see how and the steps to achieve this.

UserControls Library

First let's create a web project in visual studio.net that will contain all user controls that we need to share.

For our demo, we add a new usercontrol named "DateBox.ascx" to the project and add a calendar and two labels to it.

UserControl's Code Behind

In order to demonstrate that it is also possible to reuse the code behind along with the user control we will add some custom code to the page_load event.

public string Company
{
    get { return _company; }
   
set { _company = value; }
}

public string Year
{
   
get { return _year; }
   
set { _year = value; }
}

protected void Page_Load(object sender, System.EventArgs e)
{
    Response.Write("DateBox Page Load Event successfully called!");
    lblDate.Text = Year;
    lblCompany.Text = Company;
}

private string _company,
                        _year;

Note : It is also possible to use the ascx files as a single file and write directly the custom code in it.

Sharing the Code Behind Assembly of Our User Controls Library

As we want to share our library across multiple web applications we must register the assembly that holds the code behind of our user control in the GAC (Global Assembly Cache). In order to register our assembly in the GAC we must follow several steps.

First, generate a strong name key for it and set the "AssemblyKeyFile" attribute in the "assemblyInfo.cs" of our project with the keys filename and path. We can generate a key using the DOS sn.exe utility.

sn.exe -k ControlsLibraryKeys.snk

Next, we build our solution and to register our assembly in the gac we choose to either drag and drop it directly in the \WINNT\assembly folder or use the following DOS command.

Gacutil.exe -i yourassemblypath

We must also inform the ASPX compiler that we want him to check for our new shared assembly. To do that we need to edit the machine.config. This file contains most .Net configuration of our local machine. You can find it in the following directory:

\WINNT\Microsoft.net\FrameWork\YourVersion\CONFIG

Load the file in a plain text editor and search for the <assemblies> element, add the following child element to it :

<add assembly="UserControlsLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=29f4c43ca2dde360"/>

These values might change depending on your current settings. You can get the current publicKeyToken of your assembly from the \WINNT\assembly folder.

Setting up Our User Control Library

To use our library we will create another web project in visual studio that will consume our library. In order to use the assembly that contains the code behind code we must add a reference to it in our project.


We can access the assembly as we registered it in the GAC but how can we have access to the .ascx file from our aspx page ? IIS will answer to this question for us. IIS has a neat feature called virtual directories, virtual directories allow us to add to a website root a sub-directory that maps to a different physical path.

We will use this fonctionality to map a new virtual directory called "controls" to the path where our .ascx file reside. We can add a new virtual directory to the root of our web project using the Internet Service Manager.

Note : By default IIS associates an application to the virtual directory, as we don't need it we clicked the "remove" button to remove it.

Rise of the Controls

Now that we have the full setup lets test our controls using the default "webform1.aspx" page.

In order to use any usercontrol we must first add the register directive in the html part of our page.

<%@ Register TagPrefix="DNG" TagName="DateBox" Src="~/Controls/DateBox.ascx" %>

And here is the trick, watch carefully the SRC. We are tricking the asp.net engine by using an App-Based path with the ~ prefix instead of a classic virtual path. If we had used a virtual path asp.net would have thrown the following error "maps to another application, which is not allowed". Using and App-Based path asp.net doesn't notice that the file comes from a different application and we can use our ascx files, great !

Lets move on and add our user controls to our page and compile the project.

<DNG:DateBox id="DateBox1" Company="DNG" Year="1984" runat="server" />

If we did everything correctly our shared user control should appear on our test page.



Looks nice ;)

Using the Controls from the Code Behind

We can also use and set the user control properties directly from the code behind of our aspx page

public class WebForm1 : System.Web.UI.Page
{
   protected DateBox DateBox1;
  
   private void Page_Load(object sender, System.EventArgs e)
   {
      DateBox1.Company = "Amiga";
      DateBox1.Year = "1985";
   }
}
 
Using the Controls Dynamically

For people who love using the dynamic features of ASP.net you can also use this solution to add dynamicaly a shared user control from our library.

 public class WebForm1 : System.Web.UI.Page
{
   private void Page_Load(object sender, System.EventArgs e)
   {
      DateBox dynDateBox = (DateBox) LoadControl("~/Controls/DateBox.ascx");
      dynDateBox.Company = "Commodore";
      dynDateBox.Year = "1980";
      PlaceHolder1.Controls.Add(dynDateBox);
   }
}
 

Conclusion

In this article, we saw how to break the web applications barrier by using an app-based path and how to create and share a user control library across multiple web application. For demo purposes we only created one consumer (web application) but you can of course create as many consumers as you want, the only thing you need to do is to repeat the steps above for each new consumer.

Thomas is the founder of Votations.com and the .NetPolls web control. He's holding an MCDBA / MCSD .NET in C# and can be reached through this url : http://www.votations.com/contacts.asp.

Visual studio .net 2003 sources : usercontrolreuse.zip

This article was orginally published in French at dotnetguru.org


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 1:56:01 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search