Web Resources

Along with their assemblies, control developers often have to supply additional static files, such as stylesheets and images. With ASP.NET 2.0's new resources model, these static files can now be embedded into assemblies as resources. This is achieved through the addition of the Web ResourceAttribute (from System.Web.UI ), as shown in the following example:

 <assembly:WebResource("MyImage.gif", "image/gif")> Public Class MyControl   ' control code here End Class 

This simply enables the image to be available as a Web resource. Within the control code, the resource can be accessed like this:

 Protected Overrides Sub CreateChildControls()   Controls.Clear()   Dim img As New Image()   img.ImageUrl = GetWebResourceurl(/books/1/267/1/html/2/MyImage.gif)   Me.Controls.Add(img) End Sub 

At compile time the resource can be embedded into the assembly:

 vbc /t:library /out:MyControl.dll     /r:System.dll,System.web.dll     /res:MyImage.gif,MyImage.gif 

The Web resources feature is not limited just to images. For example, to embed JavaScript for client-side support, you could add:

 <assembly:WebResource("MyScript.js", "text/javascript", True)> Public Class MyControl   ' control code here End Class 

The third parameter for this attribute indicates that the Web resource parser should be invoked for the resource (which it isn't by default). This ensures that the embedded resource is parsed and will be correct when used by the client. You might notice that this technique is used for JavaScript by ASP.NET pages and certain controls, such as the TreeView .

Embedded Web resources can also be accessed from within ASP.NET pages. For example:

 <script runat="server">   Sub Page_Load()     img1.Image = Page.GetWebResourceUrl(GetType(MyControl), _                                            "MyImage.gif")   End Sub </script> 

Note that this example uses a second form of GetWebResourceUrl , which applies to the Page object. Here the type of control for which the Web resource is being fetched is also required. Notice that the control type is the custom control, not Image , as the resource is part of the custom control itself.



A First Look at ASP. NET v. 2.0 2003
A First Look at ASP. NET v. 2.0 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 90

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net