Article

About the Author

Philip Miseldine

author_philipmiseldine Philip is a Computer Science PhD student at Liverpool John Moores University. He's still not mastered guitar tabs, never finished Mario, and needs a haircut. He discusses life at http://www.miseldine.com/.

View all articles by Philip Miseldine...

Why Use .NET?

By Philip Miseldine

May 10th, 2004

Reader Rating: 8.5

Page: 1 2 Next

.NET hasn't traditionally been the SitePoint community's framework of choice for Web development. A simple comparison of the activity within the PHP and the .NET forums highlights this fact. But with the release of SitePoint's first ASP.NET book, I thought it was about time us .NETers stood proud, and shouted from the rooftops exactly what makes this technology so good.

However, it isn't the purpose of this article to deride other technologies; this isn't "PHP vs. .NET Part 2". Every platform, framework, and architecture has its own strengths and weaknesses, and .NET is no exception. So, the features highlighted in this article aren't discussed as if they are unique or necessarily better in .NET (although, of course, most are!), but it should give those who are still dipping toes into .NET some good reasons to dive right in.

The Framework

Without writing a single line of code, .NET provides you with a scalable and powerful framework to code upon. Before I explain its benefits, let's have a little discussion about how exactly it works.

When a .NET application is compiled, it's not compiled to machine code. Instead, .NET applications are compiled to IL (Intermediate Language), which is akin to Java bytecode. When the application is executed, it is then compiled into native executable code, which is managed by the Common Language Runtime (CLR). What this management means to us as developers is that the CLR can guarantee certain aspects of your application function, for example, garbage collection and exception handling, giving it inherent robustness and security. This architecture is known as Managed Code, and gives your applications a great deal of tolerance out of the box.

In ASP.NET, compilation is dynamic. .NET compiles its output when a page or resource is first requested. Subsequent requests then use this compiled output to produce the resource, resulting in extremely fast, compiled applications. This is why, when you first run an ASP.NET application, there's a short delay before the request is returned. So, don't worry: things only get faster…much faster!

The framework also includes the Microsoft Framework Classes, the largest and most feature-rich set of ready-to-use classes Microsoft has ever released. The System classes, as they're known, can be employed by any .NET application, meaning the code you write for your Website can just as easily be used within desktop applications or mobile devices (assuming you've designed them correctly, that is!). This in turn makes your developments far more productive, as writing for the Web can be just as simple as writing for the desktop.

The System classes also provide distinct methods for performing certain tasks. As an example, let's say we need to send an email. We can use the System.Web.Mail.SmtpMail class to achieve this:

SmtpMail.Send("FROM","TO","SUBJECT","MESSAGE BODY");

Because we have a defined point of access to the mail service (in this case, the SmtpMail class), any future changes or improvements to the code that sends mail is co-ordinated and our application will automatically benefit. Contrast this with ASP development, for example, where there were many different implementations for sending an email, often using COM. In addition, .NET's co-ordination increases code readability. If we're looking at a system as a new developer, the SmtpMail class can easily be recognised and its functionality attributed to it. Again, contrasted with ASP, where we'd need to recognise the particular COM object used to gain an understanding of the code, this delivers considerable benefits.

Not only does the framework provide a reliable, managed method of writing and executing your applications, it also helps co-ordinate your code. Not bad for something you get for free!

Object Orientated Architecture

Everything in .NET is an object. This means that everything you use and write is also an object. In ASP.NET, for example, a Web page is treated as an object -- even a tag can be treated as an object. This yields a powerful means of accessing and controlling your Web applications as you deal with properties to set and retrieve information, and respond to events occurring within the application.

Let's look at this in action. The code below sets the title of the Web page when it's first loaded, then changes the title when the user clicks on a button:

<%@ Page Language="C#" %>
<script runat="server">

 void Button1_Click(object sender, EventArgs e)  
 {
   titleTag.InnerText = "You clicked the button!";
 }

 void Page_Load(object sender, EventArgs e)  
 {
   if (!IsPostBack)
     titleTag.InnerText = "Page has loaded";
 }

</script>
<html>
<head>
<title runat="server" id="titleTag"/>
</head>
<body>
 <form runat="server">
   <asp:Button id="Button1" OnClick="Button1_Click" runat="server" Text="Button"/>
 </form>
</body>
</html>

Notice that, to execute code when the page first loads, we place it within the Page_OnLoad event, which is fired when the page is first requested. In procedural languages, like ASP, this code would have been placed at the very beginning of the page to achieve a similar result. By using events, however, we can very effectively organise our code and control its execution. Hence, when the user clicks on the Button control placed on the page, the Button's OnClick event is fired, and our code executed.

The code also exposes the title tag of our page as an object that's ready for us to use within our code, by adding a runat="server" attribute to the tag, and giving it an ID. We can then access the properties of this tag, in this case, InnerHTML to set its value. This makes accessing and setting the output of pages easy to control.

This object orientation also means we have access to a wide range of encapsulated code and functionality in the form of server controls. Just as in desktop development, you can drag and drop controls onto your pages, set their appearance, location, and write code to fire on specific events. The Button defined above is an example of a server control. .NET ships with a whole host of powerful server controls, such as the DataGrid, which allows for powerful and refined display of a wide range of data, and the Panel control, which lets you section your pages to hide or display different groups of elements as appropriate.

All the rules of object orientation apply to controls too. In the same way that you can create specialisations of classes, you can inherit the abilities of a control and add your own functionality. The recent RSS DataList control tutorial highlights how easy this is to implement.

Caching

For total performance, ASP.NET includes a very powerful and easy to use caching system. Any object can be sent to the cache for later retrieval, with total control on its life span. For example, the code below fetches results from a database (see the section on Data Access later for more information):

SqlConnection conn = new SqlConnection(connectionString);  
SqlDataAdapter a = new SqlDataAdapter("select * from mytable;", conn);  
DataSet s = new DataSet();  
a.Fill(s);

We can cache the results (in this case, represented by a DataSet) of our query, so subsequent requests will not need to connect to the database to complete the request. How easy is ASP.NET caching? Take a look:

Cache["databasequery"] = s;

Once an object is stored within the cache, we can access it again in a similarly easy way:

s = (DataSet)Cache["databasequery"];

Before we access the cache however, it is important we first check there is something available in the cache. So, introducing caching to our earlier code means only 3 extra lines of code:

DataSet s = new DataSet();
if (Cache["databasequery"] == null) {
 SqlConnection conn = new SqlConnection(connectionString);
 SqlDataAdapter a = new SqlDataAdapter("select * from mytable;", conn);
 a.Fill(s);
 Cache["databasequery"] = s;
}
else
{
 s = (DataSet)Cache["databasequery"];
}

ASP.NET can also cache complete pages. By adding a directive to the page, caching can be controlled by a parameter (e.g. http://mydomain.com/myresource.aspx?clearcache=true) or by the IP address of the requestor, and a timeout for the cache can be set.

XML Configuration

Configuration of your ASP.NET applications is controlled by the use of a Web.config file. Taking an XML format, this file is completely extendible, so you can effectively abstract configuration settings (such as database connection strings) from your code. This improves the administration and maintenance of your application by providing a central location for storing information that may be needed by many of your resources.

Let's see this in action. The following XML is a snippet from a full Web.config specifying a string containing the database connection string we'll use from our application:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <appSettings>
   <add key="ConnectionString"
     value="server=localhost;database=test;uid=sa;pwd=password;"
   />
 </appSettings>
 <system.web>
   <customErrors mode="Off"/>
 </system.web>
</configuration>

It should be noted that ASP.NET makes the Web.config file inaccessible through the Web, which provides some security. However, storing sensitive information like connection strings anywhere on your server in plain text might pose a security risk. In this case, you could first encrypt the connection string before adding it to your Web.config file, and decrypting it when it is required.

To access via our code a setting we've placed in the Web.config file, we use the following call:

connString = ConfigurationSettings.AppSettings("ConnectionString");

The value of the connection string can now be altered without changing or recompiling our code.

Code Separation

Anyone who's spent time hacking together inline scripts knows that changes to the design of a page can alter the overall effect of an application. In combination with ASP.NET's object model for Web pages, code-behinds separate code from the design of a page, leaving your Web designers free to alter your designs without breaking your code.

A code-behind itself is just a file that contains the source code for a page, which is linked to the Web page (HTML) through a declaration:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" Inherits="SitePoint.Webform1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
   <title>WebForm1</title>
 </head>
 <body>
   <form id="Form1" method="post" runat="server">
   </form>
 </body>
</html>

The code-behind file, here referenced as WebForm1.aspx.cs, must contain an implementation for the object this page inherits, in this case defined as SitePoint.Webform1:

using System;

namespace SitePoint {
 public class WebForm1 : System.Web.UI.Page {

   private void Page_Load(object sender, System.EventArgs e) {
     //code to run at page load
   }
 }
}


If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links