May 13, 2008

Why WebResources

Before we digg into "HOW TO"s about this topic let's think of "WHY WebResources?" .

Have you ever developed a control that uses some JavaScript? or image?. If not then let's exmine a case where you need to have a TextBox (web custom control) that only accepts digits means you are looking for developing one numeric text box. The quickest thing you will do is you write a class that inherits System.Web.UI.WebControl.TextBox and in that control's life cycle event you will add an HTML attribute to your control like this.Attributes.Add("onkeypress","javascript : return NumericValidationFunction()") (think that you are developing this control not only for a single web application you are working with but to provide to others if anyone needs or to sell).

Now the JavaScript function mentioned above will be written and stored in a string variable and then registered as a javascript in the PreRender method as

protected override void OnPreRender(EventArgs e) {
string numericValidationJs = "<script type='text/javascript'>function NumericValidationFunction() { your custom logic ...}</script>";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "NumericValidationJs", numericValidationJs ,true);
One disadvantage (not to just supporting this topic but it really is) is that it will be rendered as part of your HTML, embedded in the page HTML itself. It increases your page size (HTML that is being rendered to the browser) and also is HeadAche for search engine spiders. Also if you have set of controls within a single library you, for maintainance purpose, need to have a single place to write this JavaScript instead of writing within each control.

Now, based on above reasons you decided to write a ".js" file. The question is to ship this file along with your control library. And if you might have used any image file, for indication that the user has not entered a number, you might also have thought of shipping that image file along with the ".js" file with this assembly.

ASP.NET 2.0 provides a very good way to achieve this and it's recognised as "WebResource handler". Where you can have your resources (like javascript and image and other resources) embedded within your assembly and then use a URL that calls a file with ".axd" extension which is being served by an HTTPHander that respond you with the resource within the assembly. So you need to ship just one ".dll" file that contains your resources within as embedded resource.

Good enough discussion on "WHY" now let's take a look into HOW TO EMBED RESOURCE AND USE IT WITH WEBRESOURCE HANDLER.

Submit this story to DotNetKicks