Turning an ascx user control into a redistributable custom control


[Update 1/31/2011: I just attached a zip that demonstrates the files you’ll get at each step. In the process, I verified that the steps still work well with VS 2010]

 

This article applies to ASP.NET 2.0 and Visual Studio 2005.

Background

Since its early days, ASP.NET has always supported two different ways of authoring server controls:

  1. Custom Controls: these are controls written from scratch exclusively using code.  Essentially, you write a class which extends Control (directly or indirectly), and you take care of everything.  You need to write logic to create child controls that you want to use, and you override the Render method to perform rendering.  Typically, you build this control into a redistributable assembly (i.e. a DLL), which can then be used by any ASP.NET applications, simply by placing the assembly in the ‘bin’ directory of the app (or in the Global Assembly Cache).
  2. User Controls: these control are written using an ascx file, which looks much like an aspx page.  i.e. you can simply drag and drop the UI elements that you want to use into the design surface.  You don’t need to worry about control creation, nor about overriding the Render method.

Looking at those two methods, they are very different, and each has a number of advantages and disadvantages.  I won’t discuss them all, but will focus on those that are relevant to this article:

  • Custom Controls require a lot of development expertise to be written, while User Controls are authored using an advanced designer, and are much more approachable.  For this reason, User Controls typically take a lot less time to write.
  • Custom Controls can easily be redistributed without having to give away their sources.  On the other hand, User Controls are always used based on an ascx text file, making it less ideal for reuse across applications.

The goal of this article is to show how you can have the best of both world by turning an ascx user control into a redistributable custom control, by making use of ASP.NET 2.0’s new precompilation features.

 

Brief outline of the steps

The basic steps to make this happen are as follows:

  1. Write your User Control as you normally would, typically using the Visual Studio designer.
  2. Test it using a simple page before trying to deploy it.
  3. Deploy the app to precompile it.
  4. Grab the user control’s assembly produced by the deployment step, and you’re essentially done: you have your Custom Control.
  5. Finally, use your Custom Control in other apps the same way as you always use Custom Control’s.

We will look at those steps in more detail in the rest of the article.

 

Step 1: Authoring the User Control

To author the User Control, it is best to start with an empty site (not web app!) that contains nothing other than the ascx.  While the authoring of the User Control uses ‘standard’ techniques, there are some restrictions that you need to be aware of in order for it to be successfully turned into a standalone Custom Control.

The main restriction is that the User Control needs to be self contained.  That is, it cannot be dependent on app global things like App_Code or global.asax.  The reason for this is that since the goal is to turn the UserControl into a standalone DLL, it would break in other apps if it relied on code that is not part of that DLL.

One exception to this rule is that the UserControl can be dependent on assemblies that live in the bin directory (or in the GAC).  You just have to make sure that the other assemblies are always available when you use your Custom Control in other apps.

Another tricky thing is the use of static resources, like images.  After you turn it into a Custom Control in a standalone assembly, it becomes hard for it to keep such references, and avoiding them simplifies deployment.  If you really must have such references, one option is to use absolute URL’s if you can guarantee that the resource will always be available on a certain site.  Or you can look into machine wide resources (e.g. src=”http://blogs.msdn.com/MyImages/welcome.jpg”), though you will then need to make sure the resources are installed on the server machine (e.g. as part of some setup).

Ok, so let’s start and actually author the User Control.  Visual Studio 2005 gives you the choice to place the code in a separate file, or use inline code.  This is a matter of personal preference, and either one will work to create a Custom Control.  For this article, we will use inline code.  When you create the User Control (say MyTestUC.ascx), VS creates it with the a @control directive that looks like this:

<%@ Control Language=”C#” ClassName=”MyTestUC” %>

This is fine, except for one thing: we want the class to live within a namespace of our choice (instead of ‘ASP’, which is what’s used by default).  To do this, we simply modify the ClassName attribute to include the namespace (this is a new feature in 2.0).  e.g.

<%@ Control Language=”C#” ClassName=”Acme.MyTestUC” %>

That’s really the only ‘special’ thing you need to do.  Now you can go ahead and implement your User Control as you always would: add some server control, some client HTML, server script, client script, etc…

 

Step 2: Testing your User Control

Before trying to turn the User Control into a Custom Control, it is a good idea to test it in the source app using a simple page.  To do this, simply create a new Page in Visual Studio, go to design View, and drag and drop your User Control into it.

The two notable pieces of your page are the Register directive:

 

<%@ Register Src=”MyTestUC.ascx” TagName=”MyTestUC” TagPrefix=”uc1″ %>

 

and the User Control declaration:

 

        <uc1:MyTestUC ID=”MyTestUC1″ runat=”server” />

 

Note that at this point, the Register directive uses the User Control syntax (Src/TagName/TagPrefix) and not the Custom Control syntax (TagPrefix/Namespace/Assembly).  This will change after we turn the User Control into a Custom Control.

Run your page (Ctrl-F5) and make sure the User Control works the way you want before moving to the next step.

Step 3: Use the Publish command to precompile the site

The next step is to use the new Publish command to precompile your site and turn your User Control into a potential Custom Control.  You’ll find the command under Build / Publish Web Site.  In the Publish dialog, do the following:

  • Pick a Target Location.  This is the location on your hard drive that your site will be precompiled to.
  • Uncheck ‘Allow this precompiled site to be updatable’.  In updatable mode, only the code behing file (if any) would get compiled, and the ascx would be left unprocessed.  This is useful in some scenarios, but is not what you want here since you want the resulting DLL to be self contained.
  • Check ‘Use fixed naming and single page assemblies’.  This will guarantee that your User Control will be compiled into a single assembly, which will have a name based on the ascx file.  If you don’t check this, your User Control could be compiled together with other pages and User Controls (if you had some), and the assembly would get a random name that would be more difficult to work with.

Though it is entirely optional, note that the Publish Web Site dialog lets you strong name the generated assemblies.  This allows you to sign the assembly so that it cannot be tempered with.  Additionally, it allows you to place the assemblies in the Global Assembly Cache (GAC), which makes it easier to use machine wide.  More on this in Step 5.

Go ahead and complete the dialog, which will perform the precompilation.

Note: This same step can also be accomplished without using Visual Studio by using the new aspnet_compiler.exe command line tool.  The options it supports are basically the same as what you see in the Publish dialog.  So if you are more command line inclined, you might prefer that route.  e.g. you would invoke it using the command: ‘aspnet_compiler -p c:\SourceApp -v myapp -fixednames c:\PrecompiledApp’.

 

Step 4: finding the resulting Custom Control

Now, using the Windows Explorer or a command line window, let’s go to the directory you specified as the target so we can see what was generated.  You will see a number of files in there, but let’s focus on the one that is relevant to our goal of turning the User Control into a Custom Control.

In the ‘bin’ directory, you will find a file named something like App_Web_MyTestUC.ascx.cdcab7d2.dll.  You are basically done, as this file is your User Control transformed into a Custom Control!  The only thing that’s left to do is to actually use it.

Note: In case you’re curious, the hex number within the file name (here ‘cdcab7d2’) is a hash code that represents the directory that the original file was in.  So all files at the root of your source app will use ‘cdcab7d2’, while files in other folders will use different numbers.  This is used to avoid naming conflicts in case you have files with the same name in different directories (which is very common for default.aspx!).

 

Step 5: Using your new Custom Control

Now that we have created our Custom Control, let’s go ahead and use it in an app!  To do this, let’s create a new Web application in Visual Studio.  We then need to make our Custom Control available to this application:

  • In the solution explorer, right click on your application, and choose Add Reference.
  • In the Add Reference dialog, choose the Browse tab.
  • Navigate to the location of your Custom Control (App_Web_MyTestUC.ascx.cdcab7d2.dll) and select it.  It will be copied to the bin directory of your new app.

Note: as an alternative, you can choose to place the assembly in the GAC instead of the ‘bin’ directory.  In order to do this, you need to choose the Strong Name option in Step 3.  You then need to add your assembly in the <assemblies> section of web.config in the Web application that wants to use it (or in machine.config to make to globally usable).

Now let’s create a test page that uses the Custom Control.  This is similar to Step 2, except that you are now dealing with a Custom Control instead of a User Control.

First, add a Register directive to your page.  It should look something like this:

 

<%@ Register TagPrefix=”Acme” Namespace=”Acme” Assembly=”App_Web_mytestuc.ascx.cdcab7d2″ %>

 

Note how we are using a different set of attributes compared to Step 2.  Recall that in Step 1, we made sure that the ClassName attribute included a namespace.  This is where it becomes useful, as Custom Control registration is namespace based.  Also, you need to specify the assembly name, which is why having a name that is easily recognizable is useful, as discussed in Step 3.

Now, let’s declare a tag for the Custom Control.  e.g.

 

    <Acme:MyTestUC id=”MyUC” runat=”server” />

That’s it, you can now run your app (Ctrl-F5), and you are using your new Custom Control!

This shows how to use your Custom Control declaratively, but note that it can also be used dynamically, just like any other control.  To do this, just create the control using ‘new’.  Here is what the previous sample would look like using dynamic instantiation:

 

<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<script runat=”server”>
    
protected void Page_Load(object sender, EventArgs e) {
        Label1.Controls.Add(
new Acme.MyTestUC());
    
}
</script>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<body>
    
<form id=”form1″ runat=”server”>
    
<div>
        
<asp:Label ID=”Label1″ runat=”server”></asp:Label></div>
    
</form>
</body>
</html>

 

 

Note: instantiating your Custom Control dynamically as above is basically the equivalent of instantiating your original User Control using the LoadControl API.  Note that you can no longer use the standard LoadControl API after converting it to a Custom Control, since Custom Controls don’t have a virtual path.  However, ASP.NET 2.0 has a new LoadControl override which takes a Type, and that you could use in this case.  The one reason I can think of that you might choose to call LoadControl instead of just using ‘new’ is to take advantage of fragment caching (aka partial caching).  If you use ‘new’, any OutputCache directive in your ascx will be ignored.

 

Conclusion

This article outlines how to turn a User Control into a Custom Control, in order to take advantage of the strength of each model.  While there are some limitations with this hybrid model (see Restrictions in Step 1), there are many scenarios for which it can be useful.

In the future, the ASP.NET team is looking at simplifying this scenario and make it more powerful with some new tools that are in the work.  For example, you would be able to take an entire application containing an App_Code directory and multiple User Control, and turn it all into a single assembly that can easily be dropped into the ‘bin’ directory of other apps.  Though it will allow some more powerful scenarios, note that the basic idea behind it is essentially the same as what is shown in this article.

UserControlToCustomControl.zip

Comments (67)

  1. Steinar Herland says:

    Thanks for the nice article. K. Scott Allen wrote something similar at

    http://odetocode.com/Blogs/scott/archive/2005/10/06/2326.aspx

    He also enhanced the msbuild-file to use ilmerge to merge all the dll’s.

    Maybe the tool released by the ASP.NET team will be even more powerful?

  2. davidebb says:

    Steinar, the tool I was referring to is actually available now in beta form, and is called "Visual Studio 2005 Web Deployment Projects". More specifically, it contains a tool named aspnet_merge.exe. Here is the link:

    http://msdn.microsoft.com/asp.net/reference/infrastructure/wdp/default.aspx

    It’s probably the same general idea as the link your comment points to.

  3. Michel says:

    Hi,

    Just made a UserControl with three objects (calendar, textbox, button),

    a public method and property. Nothing fancy; just a ‘stupid’ User

    Control. The control appears on my test aspx page.

    Compiled it in such a way that Visual Studio 2005 generates an assembly

    for the User Control, as described in your article.

    After that I added a reference to this assembly in another solution.

    There I can reference to my User Control without any problems.

    After running the page with this UserControl the control is not

    appearing. Method and property of the User Control work fine.

    However the values for the three child objects are null. For that

    reason of course I can’t see the control.

    But why are these controls null?

    Any idea?

    Kind regards,

    Michel

  4. Maahee says:

    Hi Michel,

    I am facing the same problem as u described.

    Did u find any work around? If yes then Please post here.

    Thanks and Regards,

    Maahee

  5. Richard Cresswell says:

    Having the same problem, please let me know if a fix is found!

  6. Swati says:

    I have created the same.

    Created a user control and generated its dll -the assembly after using Publish Web Site command.

    Then I am using this dll and its user control.

    I have used the register tag in My test project as given in this article but that gives me the error as User control not found inspite of adding reference of the dll .

    Thanks

    Swati

  7. Bryant says:

    Hi David,

    I know you posted this a while back but I have just started playing with this (it solves a problem we have quite nicely).

    One issue that I have come across is that if you place the compiled UserControl into another UserControl (rather than onto a web page), when you view the web page (that contains the second, uncompiled, user control)at design-time, the UserControl is rendered with an error ("Object Reference not set to an instance of an object").

    This doesn’t affect the runtime behaviour (which renders/runs everything correctly) but it does look a little messy at design-time.

    This is nothing I can’t live with (just means the uncompiled UserControl is basically rendered how it used to be – no UI) but I wondered if the team is planning on improving the design-time experience of a compiled usercontrol (both this as well as the fact that the compiled UserControl doesn’t render it’s UI when placed onto a page and you can’t put a compiled usercontrol into the Toolbox)?

  8. Orlin Georgiev says:

    Hi! This post is specially for Michel, Maahee and Swati, in case they haven’t figured their problem out meanwhile. I too created an user control with some basic server controls in it (a textbox, a label and a button) and it didn’t show up. So I dissasembled the asembly of the custom controls to see what’s wrong. As weird as it may sound but it seems that even in .NET 2.0 the inline code actually becomes a derived class of the code-behind (as was the case in 1.1) and NOT a single class comprised of two partial classes. So by registering the custom control with a <%@ Register TagPrefix="Acme" Namespace="Acme" Assembly="App_Web_mytestuc.ascx.cdcab7d2" %> and a <Acme:MyTestUC id="MyUC" runat="server" /> directive you actually invoke the base and not the derived class. To really invoke the rendering (derived) class ypu should. The solution is to use <%@ Register TagPrefix="Acme" Namespace="ASP" Assembly="App_Web_mytestuc.ascx.cdcab7d2" %> and <Acme:mytestuc_ascx id="MyUC" runat="server" /> or something like that, depending on the name of your UC. If you still don’t get it, dissasemble the custom control and you’ll see what I mean.

    Kind regards,

    Orlin

  9. Ian Nelson says:

    It’s over a month now since Visual Studio 2005 officially RTM’d, and during that time I’ve been fortunate…

  10. Anuj says:

    Hi ! Thanks Orlin the soluation you told its working cool I have another question while I am compiling my program it is given me this error :

    : CS0115: ‘ASP.default_aspx.GetTypeHashCode()’: no suitable method found to override

    Source Error:

    [No Relevant source lines]

    DO u have any idea why it is so…

    Thanks

    Anuj

  11. davidebb says:

    Anuj,

    Have you tried following the steps exactly as outlines in the article?  Orlin’s comment only applies if you are doing something different from the steps.  Specifically, make sure you are properly setting the classname attribute as explained in Step 1.

    thanks,

    David

  12. Phcyso says:

    Hi David,

      Thanks for this great article. I was facing the same problem as described by Michel. I made sure that I am properly setting the classname attribute as explained in Step 1, and everything worked fine, BUT ONLY IF I USE INLINE CODE.

      I want to use code-behind model, but I am not able to get that to work. When I add the "ClassName" attribute, I get the following error; –

     "Missing partial modifier on declaration of type ‘Acme.MyTestUC’; another partial declaration of this type exists….c:WINDOWSMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET Filesuia00a88f8c67bcb51App_Web_nuzxcasf.0.cs 138"

     Kindly help. I am stuck :(

    Thanks.

  13. davidebb says:

    Phcyso,

    This hsould work fine with the code behind model.  Make sure your code behind ascx looks something like this:

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="CodeBesideControl.ascx.cs"

    Inherits="Acme.CodeBesideControl" ClassName="Acme.MyCodeBesideControl" %>

    and that the ascx.cs defines the matching partial class in the same namespace.

    David

  14. Dave says:

    I’ve been trying this method. No success yet. Can you guys post a sample here?

    Thanks.

  15. David Ebbo has written an article about Turning an ascx user control into a redistributable custom control.The

  16. David Ebbo has written an article about Turning an ascx user control into a redistributable custom control.The

  17. I have a control: App_Web_simplecontrol.ascx.cdcab7d2.dll

    I like to distribute it as simplecontrol.dll. but simpley renaming and replacing App_Web_simplecontrol.ascx.cdcab7d2 with simplecontrol on code doesn’t work.

    Any suggestions?

  18. davidebb says:

    Jared, I think you should be able to use ILMerge (available on MSDN) to do this. You could also use it to package multiple controls into one DLL.

    David

  19. I got the web deployment project to do it for me. This also lets me have multiple asxc files.

    Now I have a new issue:

    I can add the dll reference and manually add the register command and controls to the html. I would like to add this dll to the toolbox so that I can simply drag my controls to the form and have the reference, register, and html auto added, like other custom controls do. However the toolbox tells me that "there are no components that it can place in the toolbox".

    Once this works then I will be golden!

  20. Toni Bailon says:

    Has anyone been able to drag and drop the created control from the toolbox?

  21. Toni says:

    It’s very useful, but is it possible to see the control inserted in a form?

    Is it possible to see it at design time, like any other web control?

  22. Ian Nelson says:

    It’s over a month now since Visual Studio 2005 officially RTM’d, and during that time I’ve been fortunate

  23. Ricardo Gomes says:

    Hi there, I’m having some problems. I’ve done a web user control with a textbox wich i’ll want to access from a page.

    (Code .ascx)

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MFComment.ascx.cs" Inherits="MF.MFComment" %>

    …(my code)….

    (Code .ascx.cs)

    namespace MF

    {

       public partial class MFComment : System.Web.UI.UserControl

       {

    …(my code)…

       }

    }

    – If I use the attribute ClassName inside the Control directive I get the following error:

    Missing partial modifier on declaration of type ‘MF.MFComment’; another partial declaration of this type exists c:WINDOWSMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET Filesdistributeascxcontrol29b825f5aaee677fApp_Web_wgindfuh.0.cs 138

    When I publish the control (without the ClassName) everything goes well.

    The problem begins when I want to use the published assembly.

    I register the control and declare it on my page but i’m cannot see it when i run the page. I can access the control and it’s properties from the page code behind but when I test my page the control does not appear.

    (Code Page .aspx)

    <%@ Register TagPrefix="MF" Namespace="MF" Assembly="App_Web_mfcomment.ascx.cdcab7d2" %>

    <MF:MFComment ID="myctl" runat="server" />

    Can anyone explain me what can be the problem and how to solve it?

    Thanks in advance!

  24. Mark Kamoski says:

    This works great.

    I had some trouble getting the compile-and-deploy to work using the 2-file method (code-infront and code-behind). The problem was that the control was not showing up on the page at all. It might have been a issue with the namepaces, casing, or something like that. I switched to the 1-file method and it worked fine. GEFN. I will refactor later if necessary.

    Thank you VERY much.

    — Mark Kamoski

  25. sheirali@hotmail.com says:

    Hello David,

    I followed the steps that were shown, and for the most part, it is working.

    In my usercontrol (example, NumericTextBoxControl) which wraps a normal TextBox web control, I exposed the embedded TextBox as a property (only Get).

    I am now able to use the dlls that the Publish website created within another web site project’s ascx files by registering the dll and using the control within the HTML of my ascx pages.

    However I want to create an instance of this control in a code-behind.

    For example:

       NumericTextBoxControl txtNum = new NumericTextBoxControl();

    But when I tried to reference the embedded TextBox via the exposed Get Property, the property is returning Null.

    If using the control in an html page (.aspx), it works and from the code-behind, I can access the Get Property to get to the embedded TextBox.

    How can I do a "new" in code-behind and have the Get Property not return Null???

    Do you have any advice? Or solution?

    Thanks

    Sheir

  26. David Ebbo says:

    Hi Sheir,

    Instead of directly instantiating your control, try calling page.LoadControl(typeof(YourControlType), null).  This should do the proper initialization that will make it work.

    David

  27. Mark Kamoski says:

    David — Please help. I have been using this technique and it works just fine as long as the User Control is a 1-file control, with inline code. As soon as I try to use a 2-file control (with both code-infront and code-behind) it does not work– the UI cannot be seen at all when the resulting server control is used on an ASPX page. I have tried stating both classname="MyNamespace.MyClassName" and inherits="MyNamespace.MyClassName" in the <@control directive (as you mentioned in a post above) but when I do that I get a compile-time-error of "Missing partial modifier on declaration of type ‘MyNamespace.MyClassName’; another partial declaration of this type exists". Can you give any more advice concerning how to make this work with the code-behind coding method in the User Control?

  28. davidebb says:

    Hi Mark,

    You need to use a different class name for the inherits (which is the base class), and the classname attribute (which becomes a derived class).  Then make sure you always use the ‘classname’ class when you use it (just like in the inline mode).

    David

  29. Mark Kamoski says:

    David — I appreciate the extra assistance regarding using the classname and inherits attributes of the @Control directive. Your advice works like a charm. BTW, I have been using this method to create stand alone Server Controls. After than, I create a wrapper around those Server Controls to make them into WebPart Controls for use in SharePoint 2007 and plain old ASP.NET sites. The whole process is now VERY simple and fast thanks to your great tip here. Thank you very much. — Mark Kamoski

  30. Jon A says:

    Anybody having problems with Namespace?

  31. Jonathan Langley says:

    David — Thanks for your post, the inheritance issues is blindingly obvious once you realise it. Great catch.

  32. David Neely says:

    Has anyone been able to get these controls to be accessible from the toolbox? If we could do that this would be a 100% solution. Thanks much–

  33. David Neely says:

    One more issue. When I reference the dll as a private assembly, intellisense works fine. However, if I register the assembly in the GAC and reference it from there, the code still works fine however I get no intellisense and I get compiler warnings for the control name (i.e. the red squiggly with a message saying that this is not a known element). Any thoughts?

  34. Darryl says:

    I would like to use a custom control built with this method in another user control. No problem adding my custom control to a page. No problem adding my custom control to a new user control BUT when I add that new user control to a page I get "error rendering control – object not set to an instance of an object". Anyone seen this? Any ideers how to resolve?

    tia

    Darryl

  35. davidebb says:

    Hi Darryl,

    Is this an error that you see at design time in VS, or at runtime in the browser?  I would think that it should work fine at runtime, though there may be design time issues (some previous comments refer to this).

    David

  36. Anand says:

    Hi Darryl,

    I too got the error ‘Object reference not set to an object". I used 2 separate files for code and design. But when I remove the code inside Page_Load event of user control, it worked fine. If I put any code to access any control inside user control, I got the above error.

    Later I fixed the problem. As it was discussed by David, I need to specify a different name for our user control. But I do not have clear knowledge. David, Can you please explain us a bit on this? Thanks for an interesting and useful article.

  37. DarylR says:

    Can someone post a complete working sample USING CODE_BEHIND (source, VS solutions, test app, EVERYTHING!)? I’m trying various combinations (starting with instructions in the orginal post) and I am still getting NULL references exceptions for the child controls of the UserControl (.ascx) when I reference them in the Page_Load event of the UserControl. I’m missing something. Could the language have anything to do with it? I’m using VB iso C#.

    HELP!

  38. GaneshThennavan says:

    Hi david,

    Is there a way to put the usercontrol into the toolbox and make it developer world easy ??

    pls do let me know.

    and has anyone tried it refrencing it to toolbox????

  39. Song Yuan says:

    I think user option 1 + Web Deployment project is the best way

  40. NAIDU says:

    Is there any way to convert the usercontrol in a Web Application project into redistributable custom control

  41. davidebb says:

    Yes, it should work essentially the same way in a Web Application Project.  The only difference is that the app’s DLL (the one VS puts in ‘bin’) will need to be included as well.

  42. Mike Jones says:

    Does anybody know how to turn of the render of a user control in the parent page. It is a pain when using lots of user controls and you are unsure what is on what page.  So in other words to make it like it was in VS 2003 with a little grey box.

  43. WebServices says:

    Tip/Trick:HowtoRegisterUserControlsandCustomControlsinWeb.config I’vebeen

  44. Panchams says:

    Hi david,

    After converting the user control to custom control,is there any way to include this into toolbox?

    Any help will be appreciated.

  45. Panchams says:

    Is there any body who can help me in below.

    After converting the user control to custom control,is there any way to include this into toolbox and drag and drop on any asp.net page?

    Any help will be appreciated.

  46. Preethi says:

    Can anyone helpme,

    I tried this procedure for creating custom control.But while complation,i am getting the follwing error:

    Could not load file or assembly ‘App_Web_webusercontrol.ascx.cdcab7d2.dll’ or one of its dependencies. The system cannot find the file specified.

    Thanks and Regards

    Preethi

  47. Damos inicio a la serie de post, basados en los temas de preparación para el examen 70-547 . Si eres

  48. tools says:

    Anyone get this working in VS2010 and in .Net 3.5 or 4?

  49. davidebb says:

    @tools: It should work the same in VS2010. Are you running into a prticular issue? Make sure that you use a Web Site and not a Web App to build the user control.

  50. davidebb says:

    I think I'm having the same problem as @tools. In VS2010 I can't figure out how to include the compiled .ascx into the .dll

  51. tools says:

    Got this working in VS2010 now having issues with localization. I used IL merge to merge in the resources dll together. Any idea how to get the references to work? I tried this…

    Resources.SharedStrings.strSite

    This works when running the website on its own but doesn't work when compiled in a dll. I always get the english text and no other language.

    I have tried this to set the culture but nothing works…

    strCADISOLanguageName = "fr-CA"

    CultureInfo _currentUICulture = new CultureInfo(strCADISOLanguageName);

    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(strCADISOLanguageName);

    Thread.CurrentThread.CurrentUICulture = _currentUICulture;

    Resources.SharedStrings.Culture = Thread.CurrentThread.CurrentCulture;

    any ideas?

  52. Chris says:

    Dave forgive me but when you talk about setting the Control declaration in the ascx so that ClassName and Inherits are such that this works, im a little lost on the context as there is no working example.

    If we have a user control in the project, called; RemoteUserLogin.ascx

    It simply has two textboxes and a button.

    The namespace of the RemoteUserLogin.ascx.cs and RemoteUserLogin.ascx.designer.cs is;

    "UI.Controls.Security"

    The ascx declaration by visual studio 2008 defaults to;

    <%@

    Control Language="C#"

    AutoEventWireup="true"

    CodeBehind="RemoteUserLogin.ascx.cs"

    Inherits="UI.Controls.Security.RemoteUserLogin"

    %>

    A separate project references the complied dll and references it in the page like so;

    <%@ Register TagPrefix="uc1" Namespace="UI.Controls.Security" Assembly="UI.Controls" %>

    <html xmlns="http://www.w3.org/…/xhtml&quot; >

    <head runat="server">

    </head>

    <body>

       <form id="form1" runat="server">

       <div>

       <uc1:RemoteUserLogin runat="server" ID="uc1"/>

       </div>

       </form>

    </body>

    </html>

    The control appears to be accepted as the properties are available in code, however on debug-run no control appears in the browser, nor did it appear within the Design view.

    You say this is resolved by some changes needed in the original ascx declaration;

    <%@

    Control Language="C#"

    AutoEventWireup="true"

    CodeBehind="RemoteUserLogin.ascx.cs"

    Inherits="UI.Controls.Security.RemoteUserLogin"

    %>

    what would i have to change in this declaration in my example to make the ctl visible in the browser.

    cheers

  53. davidebb says:

    @Chris: I just attached a zip to the post which should remove any ambiguities about the steps.

  54. Koen Willemse says:

    Hi David,

    I used your attached zip as guidance and got it working. However, I notice that it only works with user controls with inline code, not with controls with a code behind. Is this correct, or am I missing something?

    Thanks

  55. davidebb says:

    @Koen: it should work fine with code behind. Make sure you use the Web Site style of code behind (i.e. with a CodeFile attribute). If that doesn't work, please give more details about what you're seeing.

  56. Ruben Fontijn says:

    Hi David,

    Used your latest zip. It works! But when the aspx page is opened in designer mode, the control isn't visible in VS2010. I saw more post about this problem. Can you confirm that this is a problem or am I doing something wrong?

  57. davidebb says:

    @Ruben: indeed, I think this has never worked too well designer wise, and I don't think we ever investigated exactly what it would take to make it work.

  58. pravin v naicker says:

    the  Article is really good but with a limitation of the using the  stylesheet(.css) meaning if the custom control dll is being used the style sheet for the control has to be explicitly given in the page and an embedded stylesheet is not possible to be given with the dll

  59. Shyam says:

    I'm using code behind for the user control with CodeFile attribute but I don't see anything on the page that is using this control i.e. the user control is not rendered and the page is blank.

    I'm using .NET 4.0.

  60. Shyam says:

    It works if I specify ClassName attribute for the user control in Control directive with a namespace, for e.g.

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="TestUC.ascx.cs" Inherits="TestUC" ClassName="CC.TestUC"%>

    But if I put the class in the code behind explicitly inside a namespace like below, it does not work:

    namespace CC

    {

       public partial class TestUC : System.Web.UI.UserControl

       {

       }

    }

  61. Ashlesh Wazkar says:

    Towards the end of the article you mention "In the future, the ASP.NET team will …. and turn it all into a single assembly that can easily be dropped into the "bin" directory ….". Has this happened by now as we are in 2012 and the article was written waaaay back so it would be nice to know if support has been added in this area by MS. Comments?

  62. davidebb says:

    @Ashlesh: you can take a look at aspnet_merge (msdn.microsoft.com/…/bb397866.aspx). But this has actually been around for almost as long as this post :)

  63. Michal Kliment says:

    Hi David,

    i am still trying make it in VS 2013, but there are little differences with publishing. I already have the assemblies but they aren´t working in another project in same solution . Could you please (if Is it possible) make a little example with more up to date version?

  64. davidebb says:

    @Michal: I just tried it with VS2013, and it still worked as before. The only difference is that the Publish dialog looks a bit different:

    – Check Precompile during publishing

    – Click 'Configure' link

    – Uncheck Updatable, and click 'Do not merge'