Web Resource, Solving JavaScript inclusion in your Web Part

Working with client side controls requires a lot of javascript, and I have often just written the javascript in the Render or RenderHTML functions of my web controls.  This works, but is NOT the best, or even a recommended method to do this.  So I began looking around and found this nice capability, but there are some major pitfalls to be aware of!
There are several other sites, blogs, etc which explain this information which I originally referenced, but I had several issues as many of them included only partial examples.  What I have tried to do is consolidate what I found on several other blogs.
This example is based on a current Mirolink development project for Virtual Earth 6.  The projects namespace is MicroLink.Applications.VirtualEarth.Core.  The javascript file is at the root level of the project and is Core.js.  The webpart is coded in the VirtualEarthControl.cs file also located at the root level of the project.  This information is critical to be aware of in the steps below!
ASP.NET 2.0 introducted the WebResource capability to include javascript, image, and other "resource" files within a DLL.  Using the WebResource is actually pretty simple, just follow these three steps.
Step 1
Add your resource (.js, .css, etc) to the project you want to bundle it with.  Set the Build Action property to Embedded Resource.
Step 2
In the AssemblyInfo.cs file, usually located in the Properties folder add the following line:

[assembly: WebResource("MicroLink.Applications.VirtualEarth.Core.Core.js", "application/x-javascript")]

Notice that the resource name is actually formed [Package] {.SubFolder}.[Filename].  This is not noted anywhere in the MSDN!

Step 3
In the web part class file (VirtualEarthControl.cs) add the following line for security

[AspNetHostingPermission(SecurityAction.Demand, Level= AspNetHostingPermissionLevel.Minimal)]

Finally to reference the resource:

string coreJS = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "MicroLink.Applications.VirtualEarth.Core.Core.js");


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s