Why use .net by naveen kumar veligeti

21
Naveen Kumar Veligeti Why Use .NET? .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. 1

description

Why use .NET? The Main features of the .NET Framework.

Transcript of Why use .net by naveen kumar veligeti

Page 1: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

Why Use .NET?

.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

1

Page 2: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

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:

2

Page 3: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

<%@ 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">

3

Page 4: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

   <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

4

Page 5: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

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) {

5

Page 6: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

 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:

6

Page 7: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

<?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.

7

Page 8: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

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:

8

Page 9: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

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

   }

 }

}

Mobile Support

Mobile devices are becoming an extremely popular method of accessing information on the Web. .NET gives you the tools to support over 200 different mobile devices from a single source base. Having analysed any device that requests your page, the Mobile Internet Toolkit (MIT) automatically dishes out your pages in different mark-up (WML, HTML 3.0) and in different form factors (screen size, card sizes) appropriate to the device in question.

This means that if we access our page through a WAP browser, we'd be served a WML output, paginated to our mobile phone's display size and

9

Page 10: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

network connectivity. However, if we accessed the very same page through a PDA, we'd be served an HTML output, with much more information on each page taking into account of the extra features and larger screen size our PDA has over the mobile phone.

Data Access

One area in which .NET really shines is that of its extendible data access components, known as ADO.NET. ADO.NET provides a high level interface to virtually every database that exists, with generic connectivity through ODBC and OLE DB, as well as specialised and optimised connectivity for SQL Server, Oracle and MySQL (through a third party component).

With ADO.NET, all data is transported in XML, allowing for great interoperability between data providers and applications. This also allows XML files to be used for data storage using the same structures and access techniques as traditional databases.

ADO.NET uses a disconnected model, which means that applications work with data locally, only contacting the server for data transfer or update. This means your application isn't as reliant on the performance of the database, improving performance and the scalability of applications by removing bottlenecks.

With these enhancements comes a productivity boost. While data access still isn't "plug and play" -- that is, you still need to deal with SQL statements, data structures, and to a certain extent, deal with your database -- it does introduce easy-to-use methods for accessing data. For example, here's the code to pull a set of rows from a table on a running SQL Server and display the first field in each row:

SqlConnection conn = new SqlConnection(connectionString);  

10

Page 11: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

SqlDataAdapter a = new SqlDataAdapter("select * from mytable;", conn);  

DataSet s = new DataSet();  

a.Fill(s);  

foreach (DataRow dr in s.Tables[0].Rows)  

{  

 Console.WriteLine(dr[0].ToString());  

}

Anyone who's dealt with traditional ADO or other data access objects will notice how clean and methodical the access is.

We can also, at any point, read and write XML from our DataSet using the ReadXML and WriteXML methods. So, to extend the earlier example, we can now output the results of our query in structured XML to a file fileName:

SqlConnection conn = new SqlConnection(connectionString);  

SqlDataAdapter a = new SqlDataAdapter("select * from mytable;", conn);  

DataSet s = new DataSet();  

a.Fill(s);  

s.WriteXml(fileName);

Language Preference

.NET is language neutral. As mentioned at the start of this article, all .NET compilers interpret and compile your code to the same base language, IL (intermediate language, akin to Java bytecode) to run on the CLR (Common Language Runtime). This means you can happily use Visual

11

Page 12: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

Basic.NET and receive the same performance and functionality of those traditionally more powerful languages like C++. In essence, you can choose the language you use.

As with spoken languages, the availability of information in the form of example differs from language to language. While you may be able to read and express anything you would wish to in Esperanto, to read the majority of content on the Web, you'll still need a decent grasp of English. This is similar with .NET. You may choose Eiffel.NET as the language with which to develop your applications, yet most examples and references you'll find will be coded in either C# or VB.NET. To apply these to Eiffel, you'll need an understanding of these languages as well.

So, what are the choices? C# is a language developed by Microsoft specifically for .NET. Taking a similar syntax style to that of Java, C# is recognised as a clean, modern language and, with its similarity to Java, is a great bridge from Java to .NET. Visual Basic .NET (VB.NET) extends Visual Basic 6 to offer the power of object orientated programming within .NET. In a nutshell, anyone who's already familiar with VB6 will have little problem moving up to VB.NET.

Let's have a look at some example code: a class written in C#, and its equivalent in VB.NET:

namespace sitepoint.csharp  

{  

 public class HelloWorld  

 {  

   public string sayHello(string name)  

   {  

     return "Hello "+name+"!";  

12

Page 13: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

   }  

 }  

}  

 

Namespace sitepoint.visualbasic  

 Public Class HelloWorld  

   Function sayHello(ByVal name As String) As String  

     Return "Hello " + name + "!"  

   End Function  

 End Class  

End Namespace

A single project can even use different classes for different files! This language tolerance also means we can reuse code developed with different languages without the headaches of the past. No marshalling, no COM, just transparent language interoperability courtesy of .NET.

Web Services

Web services aren't new or unique to .NET. In fact, that is the whole point of a Web service -- that it uses standards to enable cross-platform, cross-development execution of code. However, the way in which .NET simplifies the creation of Web services is certainly a great string in its bow.

A Web service is essentially a collection of methods that can be accessed via HTTP and SOAP. You can, as with any method, have a custom object return type, or pass custom objects to the method, which means you can distribute parts of your application very simply.

13

Page 14: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

An example: below we have the Hello World example class used earlier in this article:

namespace sitepoint.csharp  

{  

 public class HelloWorld  

 {  

   public string sayHello(string name)  

   {  

     return "Hello "+name+"!";  

   }  

 }  

}

At the moment, to use the sayHello method, we must use it within .NET and have the compiled assembly available on our machine.

By exposing the method sayHello as a Web service, however, we can host the code on a network, far away from our machine, and also allow developers of other languages (not necessarily .NET languages!) to use our functionality.

Exposing the method as a Web method is simplicity itself. We just add a WebMethod attribute to the method and inherit behavior from the WebService class:

using System.Web.Services;  

14

Page 15: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

 

namespace sitepoint.csharp  

{  

 public class HelloWorld: WebService  

 {  

   [WebMethod]  

   public string sayHello(string name)  

   {  

     return "Hello "+name+"!";  

   }  

 }  

}

After linking this to a service page (a one-line instruction contained within a .asmx file), we have exposed this method and its functionality on the Web, ready for all to use (or consume).

When you consume a Web service, you create a proxy class that contains the methods exposed by the service, and define classes for the types used within the methods. This proxy class means you can treat the Web service as if it were local to your application: it automatically handles the remote calls to the service.

If you've identified functionality in your code that you feel could benefit from being distributed (heavy computational tasks, for example), which could be sold as a service to third parties, or which might require high levels of maintenance, Web services will help ease deployment headaches while opening new avenues for sale. It's a win-win situation.

15

Page 16: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

It's By Microsoft

This might be a point against .NET in your books, and if you're wishing to write cross-platform software, it certainly is. But whatever your personal view of the corporation, one fact remains: Microsoft has the money to innovate and market their products like no one else in the industry. This means that .NET isn't disappearing any time soon and, as with every Microsoft development framework, there are heaps of freely available guides, ebooks and reference libraries to help us developers.

Previews of Microsoft's next generation operating system Longhorn show how the skills learnt from developing .NET today will be directly transferable to Longhorn development tomorrow. This almost guarantees the worth of .NET skills for the foreseeable future, something that's normally very difficult to say in the rapidly evolving computer industry.

Of course, with the positives come certain negatives, most principally the lack of full cross-platform support with .NET. While there is nothing stopping .NET from making its way to Linux technically (and projects like Mono show just how true this is), there is no drive from Microsoft to support .NET on alternative operating systems, because of the obvious conflict of interest with Windows, the market where Microsoft makes the bulk of its money. While this may rule out .NET development for some, in reality, products like Windows Server 2003 now remove many of the obstacles to Windows server adoption such as the concerns around security, reliability and performance that existed in the past.

It's Cheap!

Not a statement that can be usually directed at Microsoft, particularly in comparison with its open source rivals, but pound for pound, dollar for dollar, .NET offers great value for money.

To get started with .NET, all you need is a box with a modern version of Windows installed (ASP.NET requires IIS 5.0 or above, meaning Windows 2000 or XP Pro are required for serving Web applications). The framework

16

Page 17: Why use .net by naveen kumar veligeti

Naveen Kumar Veligeti

itself is free, and Microsoft's strong support for .NET means a decent IDE in the form of Web Matrix is available for free; however, as with most development frameworks, to write code, all you need is Notepad.

And, of course, there is the mighty Visual Studio .NET. By requiring a hefty license fee, it can't be called cheap, but the productivity gains and project organisation it introduces means Visual Studio .NET can pay for its license several times over in a single development process.

As mentioned in the data access section of this article, .NET supports virtually every database available today, including open source, freely available databases like MySQL. However, Microsoft also has a free database in the form of MSDE, a developer edition of their SQL Server database. While Microsoft still will not allow commercial use of the database, MSDE provides a powerful, easy to administer database that can be directly scaled to SQL Server.

For more information on where to get the components you need, and a comprehensive guide on how to install them, see the first chapter of "Build Your Own ASP.NET Web Site Using C# & VB.NET".

Prices for Web hosting have also been steadily decreasing since .NET's release. Large hosts like InterLand and 1&1 now offer fully-featured .NET packages at similar prices to traditional LAMP (Linux-Apache-MySQL-PHP) configurations.

The Future

Microsoft is in no way finished with .NET yet. Whidbey, due for release next year, includes countless enhancements and new additions, including object relational mapping, simplified user management, themeing, and much more besides. Read the Preparing for Whidbey article for more information on what to expect.

17