When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















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

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, December 24, 2003

Accessing Common Code, Constants, and Functions in an ASP.NET Project
By Scott Mitchell


Introduction
When moving from classic ASP development to ASP.NET, one thing many developers find themselves needing to do is port their existing reusable code base from classic ASP to ASP.NET. With classic ASP, many developers created include files, which are files that would contain common functions, code, and constants. These include files could then be used in any classic ASP page by simply adding an #include directive at the top of the page: <!--#include file="includeFile.asp"-->. Include files in classic ASP were useful for centralizing code so that common functions and constants didn't need to be repeated in numerous pages. (For more information on using #include in classic ASP, be sure to read: The Low-Down on #includes.)

- continued -

In ASP.NET, #include is still supported to a degree, but there are better ways to create a common repository of functions, code, and constants. In this article we'll first examine the optimal approach for storing Web application-wide constants; next, we'll look at how to provide a means for creating functions common to all ASP.NET Web pages in the Web application.

Storing Constants
There are many times when various Web pages in a Web application need access to a similar set of constant values. The most common scenario is when the Web pages access database data. These pages, if accessing the database directly, need to know the connection string to the database. One approach is to simply hard-code the database connection string in each data-accessing page, but this approach can lead to quite the headache if the connection string changes, since it requires manually editing all pages where the constant has been duplicated.

A better approach is to use a centralized repository for storing such constants. This approach allows for the constant's value to be spelled out in precisely one location. The Web pages that need to access the constant's value can do so through a bit of code. With this technique, needed changes to the constant require only a change in one place, and the pages that use the constant are automatically updated accordingly.

The question, then, is where should these constants be stored, and how can they be accessed? The ASP.NET Web.config file provides as good a place as any for storing simply scalar constants. The Web.config file can have an appSettings element added, in which you can provide a variable number of constant names and values. For example, a database connection string could be defined in the Web.config file like so:

<configuration>
  <!-- application specific settings -->
  <appSettings>
      <add key="connString" value="connection string" />
  </appSettings>

  <system.web>
     ...
  </system.web>
</configuration>

Then, from an ASP.NET Web page, a constant value can be retrieved with just one line of code, ConfigurationSettings.AppSettings("constantName"), like in:

Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connString"))

Note: you will need to import the System.Configuration namespace into your project for the above code examples to work...

In the Web.config file you can even add your own constants "group," akin to the appSettings. For more information on this technique, as well as a more in-depth discussion on using Web.config to store application-wide constants, be sure to read: Specifying Configuration Settings in Web.config.

Rather than using the Web.config technique, you can roll your own constants managing class, as Rachael Schoenbaum showed in her article Using XML to Share Constants Across Projects.

Creating Functions Common to All ASP.NET Pages in a Web Project
Many classic ASP developers have built up a rich set of functions that are used in a variety of their pages through #include files. Imagine that we had the following classic ASP function, defined in a #include file and used in a number of classic ASP pages:

Function DisplayEmployee(objRS)
  Dim str
  str = "<div>Name: " & objRS("Name") & " (" & objRS("SSN") & ")<br>" & _
        "Dept: " & objRS("Dept") & "</div>"
  DisplayEmployee = str
End Function

This VBScript function takes in a Recordset and displays the name, social security number, and department of the employee in a pre-formatted way. Such a function might be used in numerous pages when working with employees in order to display their vital information in a consistent format. Therefore, when migrating from classic ASP to ASP.NET, the classic ASP developer might want to create a central function repository in his ASP.NET Web application that would contain functions like DisplayEmployee().

To provide such functionality in an ASP.NET project, create a class in your ASP.NET Web application project and for each common function, create a Shared function in the class. (Shared functions, or "static functions" in C# terminology, are class methods that can be invoked without an instance of the class being first created. That is, if you have a class named ConstClass, and a method named DisplayEmployee(), you can invoke the method with: ConstClass.DisplayEmployee(), as opposed to have to create an instance of the ConstClass first...)

To create a new class using Visual Studio .NET, right click on the Project name in the solution explorer and choose to Add Class, as shown in the screenshot below. You will be asked to pick a name for the class, I would suggest using something descriptive like ConstClass.

Adding a new class via VS.NET

This will create a blank class file with code like:

Public Class ConstClass

End Class

Now, just add the function(s) you want to have accessible from all ASP.NET Web pages in this project. When adding the function (or sub), be sure to use the keyword Shared in the function's definition, as shown below. For example, we could port the VBScript DisplayEmployee() function, adding it to the class:

Public Class ConstClass
  Public Shared Function DisplayEmployee(ByVal reader as SqlDataReader)
    Dim str as String
    str = "<div>Name: " & reader("Name") & " (" & reader("SSN") & ")<br>" & _
        "Dept: " & reader("Dept") & "</div>"
    
    Return str
  End Function
End Class

Now, in an ASP.NET Web page this method can be called like so: ConstClass.DisplayEmployee(reader). The following example illustrates this common function in use:

Dim myConnection as New SqlConnection(connString)
Dim myCommand as New SqlCommand(SQL, myConnection)

myConnection.Open()
Dim reader as SqlDataReader = myCommand.ExecuteReader()
While reader.Read()
  ConstClass.DisplayEmployee(reader)
End While

reader.Close()
myConnection.Close()

Conclusion
When moving from classic ASP to ASP.NET there is often a need to port over common functions and constants. If you are new to ASP.NET you might not be familiar with the options for providing common code to all ASP.NET Web pages in a given project. This article examined methods for sharing both constants and functions across ASP.NET Web pages in a Web application.

Happy Programming!

  • By Scott Mitchell


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • 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

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES