asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Reusable Components in ASP.NET 2.0, Object Binding and Precompilation
By Thiru Thangarathinam
Rating: 3.6 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    One of the excellent features of ASP.NET 2.0 is the ability to create reusable components without having to compile them even once. This is possible with the addition of the new pre-defined directory named Code. The Code directory is a special directory that is used as a placeholder for storing all the reusable components. Any reusable component placed in this directory will be automatically referenced and made available to all the pages in the Web site. ASP.NET 2.0 not only makes creating reusable components easier, but also allows us to easily consume them by providing a new data source control named ObjectDataSource. With this new control, it is possible to bind to an output of an object's method directly to data-bound controls such as dropdownlist, gridview and so on.

    Creating Reusable Components in ASP.NET 2.0

    A cool and useful new feature in ASP.NET Whidbey is the addition of the \Code directory. The \Code directory, like the \bin directory, is a special directory used by ASP.NET, but with a twist. While the \bin directory is designed for storing pre-compiled assemblies used by your application, the \Code directory is designed for storing class files to be compiled dynamically at runtime. This allows you to store classes for business logic components, data access components, and so on in a single location in your application and use them from any page. Because the classes are compiled dynamically at runtime and are automatically referenced by the application containing the \Code directory, you don't need to build the project before deploying it, nor do you need to explicitly add a reference to the class, and you can easily make changes to a component and deploy it with a simple XCOPY or with a drag-and-drop operation. In addition to simplifying the deployment and the referencing of components, the \Code directory also greatly simplifies the creation and accessing of resource files (.resx) used in localization, as well as automatically generating and compiling proxy classes for WSDL files (.wsdl).

    To better illustrate how this works, let's take a look at a couple of examples. In the first example, we'll see how to create a simple business component and access it from a Web Forms page.

    using System;

    using System.Data.SqlClient;

    using System.Data.Sql;

     

    public class Categories

    {

        public Categories()

        {      

        }

     

        public SqlDataReader GetCatories()

        {

            string connString =

    System.Configuration.ConfigurationSettings.ConnectionStrings["Northwind"];

            SqlConnection sqlConn = new SqlConnection(connString);

            sqlConn.Open();

            SqlCommand sqlCmd = sqlConn.CreateCommand();

            sqlCmd.CommandText = "Select * from Categories";

            // Create the SqlDataReader object and return it

            SqlDataReader reader = sqlCmd.ExecuteReader();

            return reader;

        }

     

        public SqlDataReader GetProductsByCategoryID(int categoryID)

        {

            string connString = System.Configuration.ConfigurationSettings.ConnectionStrings["Northwind"];

            SqlConnection sqlConn = new SqlConnection(connString);

            sqlConn.Open();

            SqlCommand sqlCmd = sqlConn.CreateCommand();

            sqlCmd.CommandText = "Select ProductID, ProductName, UnitPrice,

                  UnitsInStock from Products Where CategoryID =" +

                  categoryID.ToString();

            // Create the SqlDataReader object and return it

            SqlDataReader reader = sqlCmd.ExecuteReader();

            return reader;

        }

    }

     

    <?xml version="1.0"?>

    <configuration>

          <connectionStrings>

                <add name="Northwind"

                         connectionString="server=localhost;uid=sa;pwd=thiru;

                         database=northwind">

                  </add>

            </connectionStrings>

           <system.web>     

                  ---

                  ---

                  ---

           

           </system.web>

    </configuration>

    Code Directory vs. Bin Directory

    With the introduction of this new Code directory, you might be wondering when to use which directory. If you have an assembly that you want to use in your Web site, create a Bin subdirectory and then copy the .dll to that subdirectory. If you are creating reusable components that you want to use from your ASP.NET pages, all you need to do is to create those components under the Code directory. Whenever a change occurs in the Code directory, ASP.NET will dynamically recompile the components and automatically make them available to all the pages in the Web site. Note that you should put only components into the Code subdirectory. You should not put pages, Web user controls, or other non-code files containing non-code elements into this subdirectory.

    Consuming the component from an ASP.NET Page

    <%@ page language="C#" %>

    <script runat="server">         

        void Page_Load(object sender, System.EventArgs e)

        {

            if (!Page.IsPostBack)

            {

                Categories cate = new Categories();

                System.Data.SqlClient.SqlDataReader reader = cate.GetCatories();

     

                ddlCategories.DataValueField = "CategoryID";

                ddlCategories.DataTextField = "CategoryName";

                ddlCategories.DataSource = reader;

                ddlCategories.DataBind();

            }

        }       

       

        void ddlCategories_SelectedIndexChanged(object sender,

           System.EventArgs e)

        {

            Categories cate = new Categories();

            int categoryID = Convert.ToInt32(ddlCategories.SelectedValue);

            System.Data.SqlClient.SqlDataReader reader =

                  cate.GetProductsByCategoryID(categoryID);

            productsView.DataSource = reader;

            productsView.DataBind();       

        }

       

    </script>

    <html>

    <head runat="server">

        <title>Categories Object Client</title>

    </head>

    <body>

        <form runat="server">

            Select Categories:

            <asp:dropdownlist autopostback="true"

                  id="ddlCategories" runat="server" width="192px"       

                  onselectedindexchanged="ddlCategories_SelectedIndexChanged">

            </asp:dropdownlist>

            <br/><br/>

            <asp:gridview runat="server" id="productsView">

                <alternatingrowstyle backcolor="Silver">

                </alternatingrowstyle>

            </asp:gridview>

        </form>

    </body>

    </html>

    If you navigate to the above page using the browser, you will see the following output.

    If you use Windows Explorer to examine the directory where your Web is located, you will see your page and the Code directory. Similarly, there is no .dll or other executable code in the Code directory or anywhere in the path of your Web. Instead, Visual Web Developer has compiled the page and the component dynamically.

    Using ObjectDataSource Control for Object Binding

    So far we have seen how to manually invoke the methods of the Categories class and then bind the returned data to data bound controls. Even though this approach works fine, you still need to duplicate the object method invocation code across all the pages in the Web site. ASP.NET 2.0 addresses this problem by providing a new data source control named ObjectDataSource.

    When you are creating a distributed ASP.NET application, you will most likely split your application into multiple layers such as presentation, business, and data access. This approach will result in an extensible application that can be easily maintained and enhanced over a period of time. ASP.NET complements this type of application design by providing a new ObjectDataSource control that can be used to directly bind an object's methods to data-bound controls such as GridView, DataList, and DropDownList and so on. This approach provides for clean separation and encapsulation of code, thereby eliminating the need to write data access layer code in the presentation layer. Now that we have understood the theory behind the ObjectDataSource control, let us take a look at an example on how to use the ObjectDataSource control.

    <%@ page language="C#" %>

    <script runat="server">

    </script>

     

    <html>

    <head runat="server">

        <title>Binding Categories object's methods to an ObjectSource Control</title>

    </head>

    <body>

        <form runat="server">

            <asp:objectdatasource runat="server" id="categoriesObjectSource"

                  typename="Categories" selectmethod="GetCatories">

            </asp:objectdatasource>

            <asp:objectdatasource runat="server" id="productsObjectSource"

                  typename="Categories" selectmethod="GetProductsByCategoryID">

                 <selectparameters>

                         <asp:controlparameter type="Int32" name="categoryID" controlid="ddlCategories" defaultvalue="1"

                         propertyname="SelectedValue"></asp:controlparameter>

                </selectparameters>

            </asp:objectdatasource>   

             Select Categories:

                  <asp:dropdownlist datatextfield="CategoryName"

                         datavaluefield="CategoryID" autopostback="true"

                         id="ddlCategories" datasourceid="categoriesObjectSource"

                         runat="server" width="192px">

                  </asp:dropdownlist>

            <br/><br/>

            <asp:gridview runat="server" id="productsView"

                  datasourceid="productsObjectSource">

                <alternatingrowstyle backcolor="Silver">

                </alternatingrowstyle>

            </asp:gridview>

        </form>

    </body>

    </html>

    Let us walk through the above lines of code. We start by declaring an ObjectDataSource named categoriesObjectSource. The ObjectDataSource control exposes two important attributes named TypeName and SelectMethod. The TypeName attribute allows us to specify the name of the class we want to bind this control to. The SelectMethod attribute allows us to specify the name of the method to invoke in the class. Then we bind the data in this categoriesObjectSource control to a DropDownList control named ddlCategories by setting the DataSourceID attribute of the DropDownList to categoriesObjectSource. After that we declare one more ObjectDataSource control named productsObjectSource. Basically this control will be directly bound to the output of the GetProductsByCategoryID. As mentioned before, the GetProductsByCategoryID method takes a category id as an argument and returns all the products in that category. To be able to invoke this method, the productsObjectSource control should be able to pass in the selected category id from the dropdownlist. We specify the value for the sql query parameter using the SelectParameters template. In this case, we want to retrieve the value of the category identifier using the SelectedValue property of the DropDownList. To do this, we set the ControlId and PropertyName attributes using the ControlParameter template. We also specify the data type of the category id parameter using the Type attribute. This allows the category id selected in the categories dropdownlist to be used as an argument to the sql query. We also set the default value of 1 for the CategoryID using the defaultvalue property. This default value will be used when the page is requested for the first time. In this example, we have used the ControlParameter template to specify the parameter values for an object's method. Apart from ControlParameter, you can also any one of the following parameter objects to provide values for the parameterized query.

    • QueryStringParameter- Using this template, you can get the value of the parameter from a key-value combination in the current query string.
    • SessionParameter - Allows us to get the parameter value from a specified Session variable.
    • CookieParameter - Allows us to get the parameter value from a specified cookie.
    • FormParameter - Allows us to get the parameter value from any property exposed in the current Request object, such as posted control values. The FormParameter object is a more general version of the QueryStringParameter and CookieParameter objects.

    We have now accomplished all of these declaratively without writing even a single line of code. If you execute the above code by navigating to the page using the browser, you will see an output that is exactly similar to the output of our previous example.

    Precompilation

    One of the advantages of ASP.NET 2.0 Web pages is dynamic compilation, which makes it possible to easily change an .aspx page, save the page, and request the page in the browser without having to recompile the Web site. This feature is very similar to the "Just Hit Save" programming model that we were all used to in ASP. This feature is very powerful and can be very useful while developing the application. However, note that dynamic compilation does result in a performance hit for the first time when someone makes a request for the Web page. In that case, it would be beneficial to precompile the Web site and make the compiled Web site available so that its performance can be increased. Additionally, there are times where you may want to deploy your Web application without the source code. One more use for precompilation is to check for errors. If a page in your site contains a compile-time error and you do not precompile the site, it is possible that a user will see the error the first time the page is requested.

    Now that we understand the need for precompilation, let us examine the different types of precompilation. ASP.NET 2.0 supports two modes of pre-compilation: in-place precompilation, and precompilation for deployment.

    In-Place Precompilation

    In-place precompilation allows you to manually batch-compile all the pages in your Web site. This is essentially what happens the first time a user hits a page within your application. There are two main reasons to use in-place precompilation: first, it eliminates the performance hit of batch compiling on the first page request, and second, it allows you to find compilation errors before your users do. In-place precompilation is very easy to do. All you need to do is to simply browse to the root of your Web site and then specify the special handler named precompile.axd. For example, to precompile the Web site named ReusableComponents in http://localhost/MyProjects/15Seconds/, just enter http://localhost/MyProjects/15Seconds/ReusableComponents/Precompile.axd in the address bar of the browser. If everything is fine and the Web site is compiled successfully, you will see the following output.

    Once you have precompiled your Web site, requests for pages within the site should be fulfilled immediately, without any compilation lag.

    Precompilation for Deployment

    The second precompilation mode allows you to create an executable version of your entire Web site that can be deployed without any source code, including HTML and other static files. By precompiling the Web site for deployment, you can prevent easy access to the intellectual property represented by your code. The resulting set of assemblies and stub files can be deployed to a production server through XCOPY, FTP, Windows Explorer, and so on.

    To precompile a site for deployment, ASP.NET 2.0 provides a command-line utility called aspnet_compiler.exe. To invoke the ASP.NET precompiler, you need to open the Visual Studio.NET Command Prompt and enter the following command.

    aspnet_compiler -v /<websitename> -p <source> <destination>
    
    Where <websitename> is the name of the web site, and <source> and <destination> are file system paths pointing to the location of the site to compile and the location to which the compiled version should be emitted. For the purposes our example Web site, the command would look something like the following:
    aspnet_compiler -v /ReusableComponents 
    -p c:\inetpub\wwwroot\myprojects\15seconds\reusablecomponents c:\compiled
    

    If you want to view all of the available options for the ASP.NET precompiler, you can simply enter the command aspnet_compiler /? in the command prompt. After precompiling the Web site for deployment, if you navigate to the destination directory in Windows Explorer, you'll see that the result of precompiling a Web site is a site with a bin directory containing several assemblies and descriptive files, as well as a number of stub files with the same names as the original pages, but with the code (both HTML and executable code) stripped out. If you browse the site, the output will be identical to the original site.

    Conclusion

    In this article, we demonstrated the steps to be followed for creating a reusable component in ASP.NET 2.0 and then showed how to consume that component from an ASP.NET page. We also saw how the ObjectDataSource control can be used to directly bind the output of an object to the controls in an ASP.NET page. Finally, we had a detailed look at the process of Precompilation and how Precompilation can be used not only to increase the performance of the Web application but also catch compilation errors.

    About the Author

    Thiru has many years of experience in architecting, designing, developing and implementing applications using Object Oriented Application development methodologies. He also possesses a thorough understanding of software life cycle (design, development and testing).

    He is an expert with ASP.NET, .NET Framework, Visual C#.NET, Visual Basic.NET, ADO.NET, XML Web Services and .NET Remoting and holds MCAD for .NET, MCSD and MCP certifications.

    Thiru has authored numerous books and articles. He can be reached at thiruthangarathinam@yahoo.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Apr 27, 2004 - Develop and Customize Web Parts with Custom Tool Parts
    Tool Parts provide an interface for Web Part properties well beyond the capabilities of the default property pane. In this article Gayan Peiris shows how to customize Web Parts with custom Tool Parts.
    [Read This Article]  [Top]
    Mar 31, 2004 - Build a Managed BHO and Plug into the Browser
    Browser Helper Objects (BHOs) are COM components that communicate with Internet Explorer to enrich the browsing experience. Michele Leroux Bustamante returns to the world of COM to show you how to build a managed BHO with the help of the .NET Framework's COM interoperability features.
    [Read This Article]  [Top]
    Feb 18, 2004 - Customizing SharePoint Web Parts with Custom Properties
    In addition to creating custom Web Parts for SharePoint Portal Server, developers can actually create their own custom properties to further enhance Web Part appearance and behavior. Gayan Peiris explains the process and provides all the necessary code.
    [Read This Article]  [Top]
    Sep 26, 2003 - Accessing Shared Resources Using ASP.NET
    Accessing shared resources is a challenge for many ASP.NET developers. Tony Arslan explains how a simple serviced component can solve this infamous problem.
    [Read This Article]  [Top]
    Oct 2, 2002 - Function Pointers and COM
    Using callbacks and function pointers in VB can be risky and complicated. Ben Garcia explains his work-around for the function pointer issue he encountered while creating the VB version of his SNMP component.
    [Read This Article]  [Top]
    Sep 4, 2002 - Creating an SNMP Component - Part 2
    In part two of this intriguing article series, Ben Garcia shows how to build an updated and improved SNMP component in VC++ AND VB, and he briefly explains why limitations in VB make VC++ a better language for developing this type of application.
    [Read This Article]  [Top]
    Jul 23, 2002 - Creating an SNMP Component
    Ben Garcia sheds some light on the Simple Network Management Protocol (SNMP). First he provides a history of SNMP, then he dives right into its architecture. Finally, he shows how to build a COM component that communicates with SNMP-enabled devices.
    [Read This Article]  [Top]
    Jun 26, 2002 - Accessing Caller ID from the Web - Part 1
    Paul Apostolos begins his series on using Web services and the MSComm32.OCX component to access caller id information from a Web page. In part 1, learn how to write the Visual Basic program that runs on the server and updates a database with incoming callers.
    [Read This Article]  [Top]
    Nov 20, 2001 - Creating a Server Component with VB - Redesigned - Part 2
    Doug Dean explains different methods of retrieving and manipulating data from a database in a VB DLL so that it is ready to be rendered in a browser.
    [Read This Article]  [Top]
    Aug 28, 2001 - Create Your Own Visual Basic Add-Ins
    In this article, S.S. Ahmed shows you how to create VB add-ins. Programmers always feel that they are short of several features while working with development tools. Since Microsoft made Visual Basic an extensible product, VB developers can create their own features in VB.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers