Jaa


Walkthrough: Embedding a JavaScript File as a Resource in an Assembly

In this walkthrough, you will include a JavaScript file as an embedded resource in an assembly. You embed a JavaScript file when you have a client-script component that must be distributed with an assembly that you have created. For example, you might create a custom ASP.NET server control that uses JavaScript files to implement AJAX functionality for ASP.NET. You can embed the JavaScript files in the assembly, and they can then be referenced from a Web application that registers the assembly.

Prerequisites

To implement the procedures in this walkthrough you need:

  • Microsoft Visual Studio 2005.

    Note

    You cannot use Visual Web Developer 2005 Express Edition, because Visual Web Developer Express does not enable you to create the class library project required in the walkthrough.

Creating an Assembly that Contains an Embedded JavaScript File

To begin, you will create a file that contains the JavaScript code that you want to embed in the assembly.

To embed a client script file in an assembly

  1. In Visual Studio, create a new class library project named SampleControl.

  2. Add references to the System.Web, System.Drawing, and System.Web.Extensions assemblies to the project.

  3. Add a new JScript file named UpdatePanelAnimation.js to the project.

  4. Add the following code to the UpdatePanelAnimation.js file:

    BorderAnimation = function(color) {
        this._color = color;
    }
    
    BorderAnimation.prototype = {
        animate: function(panelElement) {
            var s = panelElement.style;
            s.borderWidth = '2px';
            s.borderColor = this._color;
            s.borderStyle = 'solid';
    
            window.setTimeout(
                function() {{
                    s.borderWidth = 0;
                }},
                500);
        }
    }
    
    
    BorderAnimation = function(color) {
        this._color = color;
    }
    
    BorderAnimation.prototype = {
        animate: function(panelElement) {
            var s = panelElement.style;
            s.borderWidth = '2px';
            s.borderColor = this._color;
            s.borderStyle = 'solid';
    
            window.setTimeout(
                function() {{
                    s.borderWidth = 0;
                }},
                500);
        }
    }
    
    

    The code contains a JavaScript function that temporarily displays a colored border around an UpdatePanel control.

  5. In the Properties window for the UpdatePanelAnimation.js file, set Build Action to Embedded Resource.

    Set script file to embedded resource

  6. Add a class file named CustomControl to the project.

  7. Replace any code in the CustomControl file with the following code:

    Imports System.Web.UI
    Imports System.Drawing
    Imports System.Globalization
    
    Public Class UpdatePanelAnimationWithClientResource
        Inherits Control
    
        Private _updatePanelID As String
        Private _borderColor As Color
        Private _animate As Boolean
    
        Public Property BorderColor() As Color
            Get
                Return _borderColor
            End Get
            Set(ByVal value As Color)
                _borderColor = value
            End Set
        End Property
    
        Public Property UpdatePanelID() As String
            Get
                Return _updatePanelID
            End Get
            Set(ByVal value As String)
                _updatePanelID = value
            End Set
        End Property
    
        Public Property Animate() As Boolean
            Get
                Return _animate
            End Get
            Set(ByVal value As Boolean)
                _animate = value
            End Set
        End Property
    
        Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
            MyBase.OnPreRender(e)
            If (Animate) Then
    
                Dim updatePanel As UpdatePanel = CType(Me.FindControl(UpdatePanelID), UpdatePanel)
    
                Dim script As String = String.Format( _
                       CultureInfo.InvariantCulture, _
                       "Sys.Application.add_load(function(sender, args) {{var {0}_borderAnimation = new BorderAnimation('{1}');var panelElement = document.getElementById('{0}');if (args.get_isPartialLoad()) {{{0}_borderAnimation.animate(panelElement);}}}});", _
                       updatePanel.ClientID, _
                       ColorTranslator.ToHtml(BorderColor))
    
    
                ScriptManager.RegisterStartupScript( _
                    Me, _
                    GetType(UpdatePanelAnimationWithClientResource), _
                    ClientID, _
                    script, _
                    True)
            End If
        End Sub
    End Class
    
    using System;
    using System.Drawing;
    using System.Web.UI;
    using System.Web;
    using System.Globalization;
    
    namespace SampleControl
    {
        public class UpdatePanelAnimationWithClientResource : Control
        {
            private string _updatePanelID;
            private Color _borderColor;
            private Boolean _animate;
            public Color BorderColor
            {
                get
                {
                    return _borderColor;
                }
                set
                {
                    _borderColor = value;
                }
            }
    
            public string UpdatePanelID
            {
                get
                {
                    return _updatePanelID;
                }
                set
                {
                    _updatePanelID = value;
                }
            }
    
            public Boolean Animate
            {
                get
                {
                    return _animate;
                }
                set
                {
                    _animate = value;
                }
            }
            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
                if (Animate)
                {
    
                    UpdatePanel updatePanel = (UpdatePanel)FindControl(UpdatePanelID);
    
                    string script = String.Format(
                       CultureInfo.InvariantCulture,
                       @"
    Sys.Application.add_load(function(sender, args) {{
    var {0}_borderAnimation = new BorderAnimation('{1}');    
    var panelElement = document.getElementById('{0}');
         if (args.get_isPartialLoad()) {{
            {0}_borderAnimation.animate(panelElement);
        }}
    }})
    ",
                       updatePanel.ClientID,
                       ColorTranslator.ToHtml(BorderColor));
    
    
                    ScriptManager.RegisterStartupScript(
                        this,
                        typeof(UpdatePanelAnimationWithClientResource),
                        ClientID,
                        script,
                        true);
                }
            }
        }
    }
    

    This class contains properties for customizing the border that is displayed around the UpdatePanel control. The code also registers JavaScript code to use in a Web page. The code creates a handler for the load event of the Sys.Application object. The animate function in the UpdatePanelAnimation.js file is called when a partial-page update is processed.

  8. Add the following line to the AssemblyInfo file.

    <Assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")> 
    
    [assembly: System.Web.UI.WebResource("SampleControl.UpdatePanelAnimation.js", "application/x-javascript")]
    

    Note

    The AssemblyInfo.vb file is in the My Project node of Solution Explorer. If you do not see any files in the My Project node, in the Project menu, click Show All Files. The AssemblyInfo.cs file is in the Properties node of Solution Explorer.

    The WebResource definition must include the default namespace of the assembly and the name of the .js file.

  9. Build the project.

    When compilation finishes, you will have an assembly named SampleControl.dll. The JavaScript code in the UpdatePanelAnimation.js file is embedded in this assembly as a resource.

Referencing the Embedded Script File

You can now reference the embedded script file in a Web application.

Note

Although you can create the class library project and the Web site in the same Visual Studio solution, in this walkthrough it is not assumed that you are doing this. Having the projects in separate solutions emulates how a control developer and a page developer would work separately. However, for convenience you can create both projects in the same solution and make small adjustments to procedures in the walkthrough.

To reference the embedded script file

  1. In Visual Studio, create a new AJAX-enabled Web site.

  2. Create a Bin folder in the root directory of the Web site.

  3. Copy SampleControl.dll from the Bin\Debug or Bin\Release directory of the class library project to the Bin folder of the Web site.

    Note

    If you created the class library project and the Web site in the same Visual Studio solution, you can add a reference from the class library project to the Web site. For details, see How to: Add a Reference to a Visual Studio Project in a Web Site.

  4. Replace the code in the Default.aspx file with the following code:

    <%@ Page Language="VB" AutoEventWireup="true" %>
    
    <%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title>ScriptReference</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" 
                                     EnablePartialRendering="True"
                                     runat="server">
                 <Scripts>
                    <asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" />
                 </Scripts>
                </asp:ScriptManager>
    
    
                <Samples:UpdatePanelAnimationWithClientResource 
                         ID="UpdatePanelAnimator1"
                         BorderColor="Green"
                         Animate="true"
                         UpdatePanelID="UpdatePanel1"
                         runat="server" >
                </Samples:UpdatePanelAnimationWithClientResource>
                <asp:UpdatePanel ID="UpdatePanel1" 
                                   UpdateMode="Conditional"
                                   runat="server">
                    <ContentTemplate>
                        <asp:Calendar ID="Calendar2" 
                                      runat="server">
                        </asp:Calendar>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    
    <%@ Page Language="C#" %>
    <%@ Register TagPrefix="Samples" Namespace="SampleControl" Assembly="SampleControl" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <script runat="server">
    
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>ScriptReference</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:ScriptManager ID="ScriptManager1" 
                                     EnablePartialRendering="True"
                                     runat="server">
                 <Scripts>
                    <asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" />
                 </Scripts>
                </asp:ScriptManager>
    
    
                <Samples:UpdatePanelAnimationWithClientResource 
                         ID="UpdatePanelAnimator1"
                         BorderColor="Green"
                         Animate="true"
                         UpdatePanelID="UpdatePanel1"
                         runat="server" >
                </Samples:UpdatePanelAnimationWithClientResource>
                <asp:UpdatePanel ID="UpdatePanel1" 
                                   UpdateMode="Conditional"
                                   runat="server">
                    <ContentTemplate>
                        <asp:Calendar ID="Calendar2" 
                                      runat="server">
                        </asp:Calendar>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </form>
    </body>
    </html>
    

    This code includes a ScriptReference control that references the assembly and the name of the .js file that you created in the previous procedure. The name of the .js file includes a prefix that references the default namespace of the assembly.

  5. Run the project, and in the page, click dates in the calendar.

    Every time that you click a date in the calendar, you see a green border around the UpdatePanel control.

Review

This walkthrough showed you how to embed a JavaScript file as a resource in an assembly. The embedded script file can be accessed in a Web application that contains the assembly.

The next step is to learn how to embed localized resources in an assembly for use in client script. For more information, see Walkthrough: Embedding Localized Resources for a JavaScript File.

See Also

Tasks

Walkthrough: Adding Localized Resources to a JavaScript File

Concepts

Creating Custom Client Script by Using the Microsoft AJAX Library