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

Share your user control across multiple web applications

Rate me:
Please Sign up or sign in to vote.
4.89/5 (33 votes)
11 Sep 20034 min read 215.5K   1.4K   77   28
How to share a user control across multiple websites.

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.

Image 1

Image 2

For our demo, we add a new user control 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.

C#
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 usercontrols 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 :

XML
<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 usercontrols library consumer

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.

Image 3

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 functionality 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.

Image 4

Image 5

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 user control we must first add the register directive in the HTML part of our page.

ASP.NET
<%@ 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.

ASP.NET
<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.

Image 6

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.

C#
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 dynamically a shared user control from our library.

C#
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.

This article was originally published in French at dotnetguru.org

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Switzerland Switzerland
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.


Comments and Discussions

 
Questionhow to access create click event of a button in that user control Pin
Member 1163159827-Apr-15 1:40
Member 1163159827-Apr-15 1:40 
Generalshared usercontrol references other dlls Pin
priya.vjn15-Jul-09 9:29
priya.vjn15-Jul-09 9:29 
QuestionShare usercontrols across applications Pin
Pradosh Manerkar2-Jun-09 21:38
Pradosh Manerkar2-Jun-09 21:38 
GeneralI've tested this article, but come across some problems Pin
ivanxin14-Jan-08 18:53
ivanxin14-Jan-08 18:53 
GeneralServer Error in '/' Application. Pin
mohd faiz18-Nov-06 2:00
mohd faiz18-Nov-06 2:00 
GeneralA newer solution to the problem [modified] Pin
Skwirel Munkee26-Jul-06 1:23
Skwirel Munkee26-Jul-06 1:23 
GeneralASP.Net 2.0 Pin
ss_doug21-Oct-05 4:57
ss_doug21-Oct-05 4:57 
GeneralRe: ASP.Net 2.0 Pin
PChott24-Jan-06 21:31
PChott24-Jan-06 21:31 
GeneralRe: ASP.Net 2.0 Pin
ss_doug26-Jan-06 4:20
ss_doug26-Jan-06 4:20 
I just tried that and it works! Pretty neat. Thanks for the link.

The only real issue is that, at design time, the user control does not show up properly in the page designer. That is, rather than seeing something with all of the text boxes and buttons, etc... that are part of the user control, one sees a small grey box with the name of the control on it. (It looks fine at run time.)

This is pretty much the way all user controls looked in VS 2003 when they were on a host page. I guess VS2005's page designer depends on the presence of the ascx file in order to create the design time display.

Now, for the next step, we need to find a way to get these items into the toolbox, so people like me, who don't have trouble remembering how to spell "register" can drag 'n' drop 'em into the page, rather than having to write out those two tags. Poke tongue | ;-P Smile | :) FWIW, I tried the obvious steps of selecting "Choose items" from the toolbox's context menu, and attempting to add the dll for the user control. That didn't work.

thanks again,
Doug
GeneralRe: ASP.Net 2.0 Pin
enteng.kabisote5-Dec-06 22:29
enteng.kabisote5-Dec-06 22:29 
Questionhow can i set the property codebehind? Pin
huangsj13-Sep-05 22:34
huangsj13-Sep-05 22:34 
QuestionDebugging? Pin
EisenB23-Aug-05 13:08
EisenB23-Aug-05 13:08 
GeneralBuild WebSite In VS.Net Beta2 Pin
sharaabi23-Aug-05 5:35
sharaabi23-Aug-05 5:35 
GeneralRe: Improvement And Antother Imrpovement Pin
DotNetAppDeveloper28-Jul-05 12:58
DotNetAppDeveloper28-Jul-05 12:58 
GeneralRe: Improvement And Antother Imrpovement Pin
Steve Segarra4-Mar-05 3:59
sussSteve Segarra4-Mar-05 3:59 
Generalhi sorry Pin
ryanheaven16-Dec-04 4:15
ryanheaven16-Dec-04 4:15 
GeneralParser Error Message: allowDefinition='MachineToApplication' beyond application leve Pin
mallik n8-Nov-04 13:46
mallik n8-Nov-04 13:46 
GeneralRe: Parser Error Message: allowDefinition='MachineToApplication' beyond application leve Pin
dnbaj25-Aug-06 1:51
dnbaj25-Aug-06 1:51 
GeneralShare user control Pin
rimmabt6-Aug-04 7:02
rimmabt6-Aug-04 7:02 
GeneralIt works Great Pin
I Piscean7-Apr-04 6:32
I Piscean7-Apr-04 6:32 
GeneralExcellent Article Pin
rhinohere19-Dec-03 6:05
rhinohere19-Dec-03 6:05 
QuestionImprovement..? Pin
lluispi3-Oct-03 6:34
lluispi3-Oct-03 6:34 
AnswerRe: Improvement..? Pin
Cyinade28-Sep-04 3:35
Cyinade28-Sep-04 3:35 
AnswerRe: Improvement..? Pin
powiz21-Oct-04 23:55
powiz21-Oct-04 23:55 
AnswerRe: Improvement..? Pin
manjulakrishna9-Feb-05 5:37
manjulakrishna9-Feb-05 5:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.