Components .NET

A well-designed web application written for ASP.NET, will include separate components that can be organized as separate data layers and business logic. Once created, you can easily use these components from any web page. ASP.NET.

There are two ways to create a component:Create a new file .cs in the App_Code subdirectory

ASP.NET automatically compiles any code files in this directory and makes the classes they contain available to the rest of the web application. When you add a new class to Visual Studio, you are always prompted to create the App_Code directory (if it doesn’t exist) and put the file in it.

Web applications created in Visual Studio using the Web Project model do not have the App_Code subdirectory. You can achieve the same result for a web project by adding a source code file to the project so that Visual Studio compiles it as part of the web application build.Create a new class library project in Visual Studio

All classes in such a project are compiled into a DLL assembly. When the build is ready, it can be added to the web application by selecting Add Reference in the Website menu (or in the Project menu, if the project development model is used) of Visual Studio. This step adds a link to this assembly to the web.config file and copies the assembly itself to the application’s Bin subdirectory.

Both approaches give the same result. For example, if you are writing code for a database component, you can access it in the same way, regardless of whether the compiled assembly is located in the Bin directory or the source code file is located in the App_Code directory. Similarly, if you use pre-compilation capabilities ASP.NET, both options will work the same. (Otherwise, you will see that it will take longer to complete the first request to the app than using the App_Code approach, because in this case, an additional compilation step is taken.)

Although both approaches have essentially the same foundation, they need to be managed with code in different ways. This is especially true when you need to reuse a component in multiple applications (or even in different types of applications .NET). If you use the App_Code approach in many web applications, it will generally be easy to make small changes, getting many different versions of the same shared class.

In addition, the second approach is more practical for building large-scale applications by a team of developers, when you need to have several different parts of the web application prepared and compiled separately. For these reasons, the class library approach is always preferable for professional work.

The App_Code subdirectory should only be used for classes that are closely related to the web application. Reusable functionality modules (such as business logic libraries, database components, validation procedures, encryption utilities, etc.) should always be built as separate class libraries.

Creating a component

The following example demonstrates a simple component that reads a randomly selected Sherlock Holmes quote from an XML file. (This XML file is available on the Internet and can be downloaded here – sherlock-holmes.xml).

The component consists of two classes: Quote, which represents a single quote, and SherlockQuotes, which allows you to read a random quote. Both of these classes are located in the SherlockLib namespace.

The first code example shows the SherlockQuotes class, which loads an XML file containing quotes in QEL (Quotation Exchange Language) when creating an instance of it. The SherlockQuotes class has a public GetRandom () method that can be used in the code of a web page:

using System;
using System.Xml;

namespace SherlockLib
{
	public class SherlockQuotes
	{
		private XmlDocument quoteDoc;
		private int quoteCount;

		public SherlockQuotes(string fileName)
		{
			quoteDoc = new XmlDocument();
			quoteDoc.Load(fileName);

			quoteCount = quoteDoc.DocumentElement.ChildNodes.Count;
		}

		public Quotation GetRandomQuote()
		{
			int i;
			Random x = new Random();
			i = x.Next(quoteCount-1);
			return new Quotation( quoteDoc.DocumentElement.ChildNodes[i] );
		}
	}
}

Each random quote received is stored in the Quotation object. This is what the Quotation class looks like:

using System;
using System.Xml;

namespace SherlockLib
{
	public class Quotation
	{
		private string qsource;
		private string date;
		private string quotation;
		
		public Quotation(XmlNode quoteNode)
		{
			if ( (quoteNode.SelectSingleNode("source")) != null)
				qsource = quoteNode.SelectSingleNode("source").InnerText;
			if ( (quoteNode.Attributes.GetNamedItem("date")) != null)
				date = quoteNode.Attributes.GetNamedItem("date").Value;
			quotation = quoteNode.FirstChild.InnerText;
		}

		public string Source
		{
			get {return qsource;}
			set {qsource = value;}
		}

		public string Date
		{
			get { return date; }
			set { date = value; }
		}

		public string QuotationText
		{
			get { return quotation; }
			set { quotation = value; }
		}
	}
}

Using a component via the App_Code directory

The easiest way to quickly test this class is to copy the source code files to the App_Code subdirectory of the web application. You can do this in Windows Explorer or use Visual Studio (by selecting Add Existing Item from the Website menu).

You can now import the SherlockLib namespace into a web page to make these classes easier to access.:

using SherlockLib;

Finally, this class can be used in the code of a web page similar to any class from .NET Framework. Below is a sample code that displays information about a quote on a web page:

protected void Page_Load(object sender, EventArgs e)
{
            SherlockQuotes quotes = new SherlockQuotes(Server.MapPath("./sherlock-holmes.xml")); 
            Quotation quote = quotes.GetRandomQuote(); 
            Response.Write("<b>" + quote.Source + "</b> (<i>" + quote.Date + "</i>)"); 
            Response.Write("<blockquote>" + quote.QuotationText + "</blockquote>");
}

If you run this application, the result will be as shown in the picture. After each page refresh, a different quote is displayed.

The App_Code approach has another limitation — you can only use one language. This limitation is a consequence of the way that ASP.NET performs dynamic compilation. In fact, all classes in the App_Code directory are compiled into a single file, so you can’t mix C# and VB.

Using a component via the Bin directory

If you need a component to provide a significant amount of functionality and allow multiple use in other applications, it is better to create it using a separate project. In this case, you can apply it, test it, and create new versions separately from the original web application.

To build a separate component, you need to create a class library project in Visual Studio. Although you can create such a project using a separate instance of Visual Studio, it is often easier to load a class library project and web application into a single Visual Studio solution for debugging purposes. This makes it easy to modify both the web application code and the component code at the same time, as well as to switch from an event handler in a web page to a method in a component in one step.

To use this approach, first create a web application. Then select Add –> New Project from the File menu to open the Add New Project dialog box. In the list on the left, select the Visual C# template group and click the Class Library template:

After adding the required code to the class library project, you can compile the component by right-clicking on this project in the Solution Explorer window and selecting Build from the context menu. As a result, a DLL assembly will be generated that contains all the classes of this component.

To allow a web application to use this component, you must add a link to this assembly to the web application project. This will enable Visual Studio to provide its usual tools, such as syntax checking and IntelliSense. Otherwise, Visual Studio will interpret all attempts to use this class as errors and refuse to compile the code.

To add a link, select Add Reference in the Website menu (or in the Project menu, if you are developing a web project). The Add Reference dialog box opens with several tabs, which are briefly described below:.NET

This tab allows you to add a link to a .NET assembly. You can choose from a list of well-known builds stored in the registry. This tab is usually used to add a link to an assembly that is part of it .NET Framework.COM

This tab allows you to add a link to an outdated COM component. You can choose from a list of shared components installed in the Windows system directory. When adding a link to a COM component .NET automatically creates an intermediate interface class called an interop assembly. This assembly is used in the code to interact with the inherited component.Projects

This tab allows you to add a link to the class library project .NET, which is currently loaded in Visual Studio. On this tab, Visual Studio automatically displays a list of eligible projects. This is often the easiest way to add links to your own special components.Browse

This tab allows you to find the compiled build file .NET (or COM component) on the computer. This approach is useful for testing special components if the source project is missing or if you don’t want to upload it to Visual Studio for fear of accidentally changing it.Recent

This tab allows you to add a link to one of the compiled assemblies .NET files that were used recently (eliminating the need to search for the required build again).

The image below shows how to add a link to the currently uploaded project:

After adding the link, the corresponding DLL file is automatically copied to the Bin directory of the current project. You can verify this by using the Path property of the link in the Properties window or simply viewing the directory in File Explorer. It is important to note that this file will be automatically overwritten by the most recently compiled version of the build each time the web application is launched.

It’s really that simple. To use a different component (from your own business logic layer, from third-party developers, or from somewhere else), all you need to do is add a link to the assembly of interest. In addition ASP.NET allows you to use assemblies with special controls, and just as easily as assemblies with special components. This makes it possible to put reusable output and user interface functionality in separate packages that can be applied over and over again within the same application or many different applications.

Leave a Reply

Your email address will not be published.

You May Also Like