sse698.2


 * Course:** SSE698
 * Project:** 2
 * Subject:** Introduction To Web Development Using ASP.NET
 * Student:** Dmitriy Slipak
 * E-mail:** dslipak@gmail.com

=Table Of Contents=


 * 1) Introduction
 * 2) ASP.NET Overview
 * 3) Web Services and ASP.NET
 * 4) AJAX Functionality
 * 5) Simple AJAX implementation with JavaScript and Web Services
 * 6) The Mono Project
 * 7) ASP.NET MVC
 * 8) Conclusion
 * 9) References

 =Introduction=

This report represents my introduction to web development using Microsoft ASP.NET technology. Here, I will give a brief review of major aspects in web development in general, and ASP.NET particularly. I will touch technologies commonly known via buzz-words such as AJAX, Web Services, MVC, etc.

In the beginning, there was an Active Server Pages (ASP) technology. This statement is true for the entrance of Microsoft into web development world. Sure, in the beginning, there was a CGI, but for Microsoft it was an ASP. The old classic ASP (that is prior .NET release) is very similar to PHP in common sense. Similar to PHP, old classic ASP allows mix HTML/JavaScript with scripting (via VBScript). Similar to PHP, VBScript file can be run as system script.

Old classic ASP was real challenge for developers under Microsoft Internet Information Server (IIS). ASP allowed to IIS developers create dynamic web applications/sites, with RDBMS to be involved. However, old classic ASP has some disadvantages, including inability to separate a content from the code, performance due to VBScript must be interpreted.

And then the world has been changed with ASP.NET that has totally different approach for web development.  =ASP.NET Overview=

ASP.NET is a unified Web development model that includes the services necessary to build enterprise-class Web applications with a minimum of coding. ASP.NET is part of the .NET Framework, and when coding ASP.NET applications we have access to classes in the .NET Framework. We can code applications in any language compatible with the common language run-time (CLR), including Microsoft Visual Basic and C#. These languages enable us to develop ASP.NET applications that benefit from the common language run-time, type safety, inheritance, and so on.


 * //Page and Controls Framework//**

In ASP.NET Web pages or Web forms, user interface programming is divided into two pieces: the visual component and the logic. The visual element consists of a file containing static markup such as HTML or ASP.NET server controls or both. The ASP.NET Web page works as a container for the static text and controls we want to display. The logic for the ASP.NET Web page consists of code that we create to interact with the page. The code can reside either in a script block in the page or in a separate class. If the code is in a separate class file, this file is referred to as the code-behind file. The code in the code-behind file can be written in Visual Basic, Visual C#, Visual J#, or JScript .NET. For more information about how ASP.NET Web pages are constructed, see ASP.NET Web Page Code Model. Below are examples of a web page file and code-behind file.

//Web form content// code format="asp" <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="myAjax.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

code

//Code-behind file content// code format="csharp" using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;

namespace myAjax {   public partial class WebForm1 : System.Web.UI.Page {       protected void Page_Load(object sender, EventArgs e)        {

}   } } code

ASP.NET Web pages are compiled into a dynamic-link library (.dll) file. The first time a user browses to the .aspx page, ASP.NET automatically generates a .NET class file that represents the page and then compiles it. The .dll file runs on the server and dynamically produces the HTML output for our page.

The ASP.NET page and controls framework is a programming framework that runs on a Web server to dynamically produce and render ASP.NET Web pages. ASP.NET Web pages can be requested from any browser or client device, and ASP.NET renders markup (such as HTML) to the requesting browser. As a rule, we can use the same page for multiple browsers, because ASP.NET renders the appropriate markup for the browser making the request. However, we can design our ASP.NET Web page to target a specific browser and take advantage of the features of that browser.

ASP.NET Web pages are completely object-oriented. Within ASP.NET Web pages we can work with HTML elements using properties, methods, and events. The ASP.NET page framework removes the implementation details of the separation of client and server inherent in Web-based applications by presenting a unified model for responding to client events in code that runs at the server. The framework also automatically maintains the state of a page and the controls on that page during the page processing life cycle.

The ASP.NET page and controls framework also enables us to encapsulate common UI functionality in easy-to-use, reusable controls. Controls are written once, can be used in many pages, and are integrated into the ASP.NET Web page that they are placed in during rendering.

The ASP.NET page and controls framework also provides features to control the overall look and feel of our Web site via themes and skins. We can define themes and skins and then apply them at a page level or at a control level.

In addition to themes, we can define master pages that we use to create a consistent layout for the pages in our application. A single master page defines the layout and standard behavior that we want for all the pages (or a group of pages) in our application. We can then create individual content pages that contain the page-specific content we want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.

The ASP.NET page framework also enables us to define the pattern for URLs that will be used in our site. This helps with search engine optimization (SEO) and makes URLs more user-friendly. The ASP.NET page and control framework is designed to generate HTML that conforms to accessibility guidelines.


 * //ASP.NET Compiler//**

All ASP.NET code is compiled, which enables strong typing, performance optimizations, and early binding, among other benefits. Once the code has been compiled, the common language run-time further compiles ASP.NET code to native code, providing improved performance.

ASP.NET includes a compiler that will compile all our application components including pages and controls into an assembly that the ASP.NET hosting environment can then use to service user requests.


 * //Security Infrastructure//**

In addition to the security features of .NET, ASP.NET provides an advanced security infrastructure for authenticating and authorizing user access as well as performing other security-related tasks. We can authenticate users using Windows authentication supplied by IIS, or we can manage authentication using our own user database using ASP.NET forms authentication and ASP.NET membership. Additionally, we can manage the authorization to the capabilities and information of our Web application using Windows groups or our own custom role database using ASP.NET roles. We can easily remove, add to, or replace these schemes depending upon the needs of our application.

ASP.NET always runs with a particular Windows identity so we can secure our application using Windows capabilities such as NTFS Access Control Lists (ACLs), database permissions, and so on.


 * //State-Management Facilities//**

ASP.NET provides intrinsic state management functionality that enables us to store information between page requests, such as customer information or the contents of a shopping cart. We can save and manage application-specific, session-specific, page-specific, user-specific, and developer-defined information. This information can be independent of any controls on the page.

ASP.NET offers distributed state facilities, which enable us to manage state information across multiple instances of the same application on one computer or on several computers.


 * //ASP.NET Configuration//**

ASP.NET applications use a configuration system that enables us to define configuration settings for our Web server, for a Web site, or for individual applications. We can make configuration settings at the time our ASP.NET applications are deployed and can add or revise configuration settings at any time with minimal effect on operational Web applications and servers. ASP.NET configuration settings are stored in XML-based files. Because these XML files are text files, it is simple to make configuration changes to our Web applications. We can extend the configuration scheme to suit our requirements.


 * //Health Monitoring and Performance Features//**

ASP.NET includes features that enable us to monitor health and performance of our ASP.NET application. ASP.NET health monitoring enables reporting of key events that provide information about the health of an application and about error conditions. These events show a combination of diagnostics and monitoring characteristics and offer a high degree of flexibility in terms of what is logged and how it is logged.

ASP.NET supports two groups of performance counters available to our applications:
 * The ASP.NET system performance counter group.
 * The ASP.NET application performance counter group.


 * //Debugging Support//**

ASP.NET takes advantage of the run-time debugging infrastructure to provide cross-language and cross-computer debugging support. We can debug both managed and unmanaged objects, in addition to all languages supported by the common language run-time and script languages. In addition, the ASP.NET page framework provides a trace mode that enables us to insert instrumentation messages into our ASP.NET Web pages.


 * //ASP.NET Advantages//**

Shortly the list of advantages of ASP.NET may be defined as below:
 * **Intuitive, consistent object model.** The ASP.NET page framework presents an object model that enables us to think of your forms as a unit, not as separate client and server pieces. In this model, we can program the page in a more intuitive way than in traditional Web applications, including the ability to set properties for page elements and respond to events. In addition, ASP.NET server controls are an abstraction from the physical contents of an HTML page and from the direct interaction between browser and server. In general, we can use server controls the way we might work with controls in a client application and not have to think about how to create the HTML to present and process the controls and their contents.


 * Event-driven programming model. ASP.NET Web pages bring to Web applications the familiar model of writing event handlers for events that occur on either the client or server. The ASP.NET page framework abstracts this model in such a way that the underlying mechanism of capturing an event on the client, transmitting it to the server, and calling the appropriate method is all automatic and invisible to us. The result is a clear, easily written code structure that supports event-driven development.


 * Intuitive state management. The ASP.NET page framework automatically handles the task of maintaining the state of our page and its controls, and it provides us with explicit ways to maintain the state of application-specific information. This is accomplished without heavy use of server resources and can be implemented with or without sending cookies to the browser.


 * Browser-independent applications. The ASP.NET page framework enables us to create all application logic on the server, eliminating the need to explicitly code for differences in browsers. However, it still enables us to take advantage of browser-specific features by writing client-side code to provide improved performance and a richer client experience.


 * .NET Framework common language run-time support. The ASP.NET page framework is built on the .NET Framework, so the entire framework is available to any ASP.NET application. Our applications can be written in any language that is compatible that is with the run-time. In addition, data access is simplified using the data access infrastructure provided by the .NET Framework, including ADO.NET.


 * .NET Framework scalable server performance. The ASP.NET page framework enables us to scale our Web application from one computer with a single processor to a multi-computer Web farm cleanly and without complicated changes to the application's logic.

Web Services and ASP.NET
A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.

Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

A SOAP message consists of several elements, most notably an envelope. The envelope encapsulates the data transmitted within the SOAP message. Below is a simple SOAP message complete with HTTP headers:

code format="xml" POST /URI/MyService.asmx HTTP/1.1 Connection: Keep-Alive Content-Length: 150 Content-Type: text/xml Host: localhost User-Agent: MS Web Services Client Protocol 1.0.2204.19 SOAPAction: "http://tempuri.org/MyService"

      code

In the example above, we see the HTTP headers for the request, including the HTTP SOAPAction header, which is optionally used by the server for routing the SOAP message. Following the HTTP headers we find the body of the HTTP message. The body of the HTTP message is the SOAP request for a PerfCounters Web Service, which we are going to build. It is very easy to build a new or use existing web services with ASP.NET. I will demonstrate it in this report later. 

AJAX Functionality
ASP.NET framework can be extended with AJAX. Asynchronous JavaScript + XML (AJAX), while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together, including: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and the XMLHttpRequest object. In a nutshell, it is the use of the nonstandard XMLHttpRequest object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including XML, HTML, and even text files. Ajax's most appealing characteristic, however, is its "asynchronous" nature, which means it can do all of this without having to refresh the page. This allows us to update portions of a page based upon user events.

The two features in question are that we can:
 * Make requests to the server without reloading the page.
 * Parse and work with XML documents.

A good example of AJAX functionality would be Gmail service from Google. All client-server interaction in Gmail exists without page reloads.

The ASP.NET framework can be extended with AJAX via AJAX Controls Toolkit – the toolkit that contains a rich set of controls that we can use to build highly responsive and interactive Ajax-enabled ASP.NET Web Forms applications, or via jQuery - a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.  =Simple AJAX implementation with JavaScript and Web Services=

In the year of 2006 I was inspired by AJAX. There was no AJAX Controls Toolkit for ASP.NET yet, but the Atlas (early product name for AJAX Controls Toolkit) at the early stage. I decided to implement AJAX functionality with JavaScript and Web Services. I will explain shortly the concept. I made some changes recently in the web services wrapper to handle IE 7 and IE 8 functionality.

The purpose of my own AJAX implementation was to be able build dynamic web application (with RDBMS communication) with client-server interaction without pages refreshing. I knew that it is possible to send and receive an information to web services via SOAP. This is true, hence the goal was create set of JavaScript function to handle data transformations between ASP.NET web forms and ASP.NET web services. I created a JavaScript library called web services wrapper (ws_wrapper.js) that contains set of functions for data transformations. Shortly, here are steps involved in my AJAX implementation:


 * 1) Web services wrapper will receive a data from web form to be transferred to web service method.
 * 2) Received data will be transformed to SOAP format (to SOAP envelop particularly).
 * 3) Data in SOAP format will be sent to web service method. Technically this is web service method call. The call may be asynchronous or not asynchronous.
 * 4) Once, the web method executed it will return required data.
 * 5) Web service wrapper will receive a data back from web service in SOAP format.
 * 6) Web service will unpack data received from web service method, and will update innerHTML property of DOM/HTML element in the web form.

The major player here is XMLHttpRequest object which allows SOAP communication. Lets take a look at web services wrapper library. The library itself represented by JavaScript file (ws_wrapper.js) with set of functions. Below is complete source code of ws_wrapper.js file.

code format="javascript" /* JavaScript wrapper for web services.
 * VERSION 0.2.2b
 * Copyright (C) 2006-2010 Dmitriy Slipak
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
 * USA.
 * You should have received a copy of the GNU General Public License
 * along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
 * USA.
 * USA.

/******************************************************************** function WS(h, d, u, f, r) { this.serviceHost = h;   this.serviceDesc = d;    this.serviceUrl = u;    this.serviceFunc = f;    this.serviceRcvr = r;
 * Object constructor                                             *
 * Arguments:                                                     *
 * h - web service host                                           *
 * d - web service description                                    *
 * u - web service url                                            *
 * f - web service method/function                                *
 * r - result receiver                                            *
 * r - result receiver                                            *

this.args = new Array; this.error = 0;

this.requestMessage = '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '<SOAP-ENV:Body>\n' + /*'<SOAP-ENV:Fault>\n' + '<SOAP-ENV:Code>\n' + '<SOAP-ENV:Value></SOAP-ENV:Value>\n' + '</SOAP-ENV:Code>\n' + '<SOAP-ENV:Reason>\n' + '<SOAP-ENV:Text xml:lang="en"></SOAP-ENV:Text>\n' + '</SOAP-ENV:Reason>\n' + '</SOAP-ENV:Fault>\n' +*/ '<ns:method>\nargs\n</ns:method>\n' + '</SOAP-ENV:Body>\n</SOAP-ENV:Envelope>';

this.clsids = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP.2.6', 'Microsoft.XMLHTTP.1.0', 'Microsoft.XMLHTTP.1', 'Microsoft.XMLHTTP'];

if (typeof(_ws_prototype_called) == 'undefined') { _ws_prototype_called = true;

WS.prototype.createXmlHttp = createXmlHttp; WS.prototype.addArgument = addArgument; WS.prototype.checkArgType = checkArgType; WS.prototype.execute = execute; WS.prototype.sendRequest = sendRequest; WS.prototype.processResponse = processResponse; }

/*******************************************************************   *   Function to create XmlHttpRequest object for old browsers      * *******************************************************************/   function createXmlHttp { var xmlHttp = null;

for (var i = 0; i < this.clsids.length && xmlHttp == null; i++) xmlHttp = new ActiveXObject(clsids[i]);

return xmlHttp; }

/*******************************************************************   *   Function to add arguments for web service call                 * *                                                                 *     *   Arguments:                                                     * *  n - argument's name                                            * *  t - argument's type                                            * *  v - argument's value                                           * *******************************************************************/   function addArgument(n, t, v) { var arg = [n, t, v];

if (!this.checkArgType(t, v)) { alert('Incorrect data type provided for argument -> ' + n); return; }

for (var i = 0; i < this.args.length; i++) { if (arg[0] == this.args[i][0]) { alert('Dublicate argument -> ' + arg); this.error = 1; return; }       }

this.args.push(arg); }

/*******************************************************************   *   Function to validate web service's argument                    * *                                                                 *     *   Arguments:                                                     * *  t - type                                                       * *  v - value                                                      * *******************************************************************/   function checkArgType(t, v) { if (typeof(v) == t)           return true; this.error = 1; return false; }

/*******************************************************************   *   Function to execute web service's method/function              * *******************************************************************/   function execute { if (this.error == 0) return this.sendRequest; }

/*******************************************************************   *   Function to compose and send XmlHttpRequest                    * *******************************************************************/   function sendRequest { var arg = ''; var request = null; var result = ''; var inst = this; var async = true;

this.requestMessage = this.requestMessage.replace(/method/gi, this.serviceFunc); for (var i = 0; i < this.args.length; i++) arg += '<ns:' + this.args[i][0] + '>' + this.args[i][2] + '</ns:' + this.args[i][0] + '>\n'; arg = arg.substring(0, arg.length - 1); this.requestMessage = this.requestMessage.replace(/args/gi, arg);

if ((this.serviceRcvr == null) ||           ((typeof(this.serviceRcvr) != 'object') && (typeof(this.serviceRcvr) != 'function'))) async = false;

try { if(window.XMLHttpRequest) request = new XMLHttpRequest; else if (window.ActiveXObject) //  support for IE < 7 request = this.createXmlHttp;

if (async) { request.onreadystatechange = function { if ((request.readyState == 4) && (request.status == '200')) result = inst.processResponse(request.responseXML,                           inst.serviceFunc, inst.serviceRcvr); };           }

request.open('POST', this.serviceUrl, async);

request.setRequestHeader('Man', 'POST ' + this.serviceUrl + ' HTTP/1.1'); request.setRequestHeader('SOAPAction', this.serviceHost + this.serviceFunc); request.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');

request.send(this.requestMessage);

if (!async) { while ((request.readyState != 4) &&                    (request.status != '200')) continue; result = this.processResponse(request.responseXML,                    this.serviceFunc, this.serviceRcvr); }       } catch (e) { alert('setRequest-> ' + e); }

return result; }

/*******************************************************************   *   Function to process response from XmlHttpRequest object        * *                                                                 *     *   Arguments:                                                     * *  r - response from XmlHttpRequest object                        * *  f - web service's method/function                              * *  rcvr - response receiver                                       * *******************************************************************/   function processResponse(r, f, rcvr) { var result = ''; var resultNode = null;

if (r.hasChildNodes) { resultNode = r.getElementsByTagName(f + 'Response').item(0);

if (resultNode != null) { if (resultNode.hasChildNodes) { var inNode = null; for (var i = 0; i < resultNode.childNodes.length; i++) { inNode = resultNode.childNodes.item(i); if (inNode.nodeName == 'result') { resultNode = inNode; break; }                   }                }            }        }

if (resultNode != null) { result = resultNode.textContent; if (result == undefined) result = resultNode.text; }

switch (typeof(rcvr)) { case 'function': rcvr.call(result); break; case 'object': if (rcvr != null) rcvr.innerHTML = result; else return result; break; default: return result; }   } } code

First function is a prototype for instance of web service wrapper code format="javascript" function WS(h, d, u, f, r) { this.serviceHost = h;   this.serviceDesc = d;    this.serviceUrl = u;    this.serviceFunc = f;    this.serviceRcvr = r; code

where


 * h** - server name/address (localhost in our case) where web service hosted;
 * d** – name/description of web service;
 * u** – relative path of web service, for example “/webservices/MyWebservice.asmx”;
 * f** – the method/function of web service to be executed;
 * r** - the name or instance of DOM/HTML element in the web form where web service will return data.

Currently, web service wrapper can manipulate data of the following data types: String, Numeric, Boolean, and Object.

A web service method can expect, and usually does an arguments. Hence, web server wrapper contains **addArgument** function which checks argument type and inserts appropriate argument into array of arguments.

Lets take a look at real example. I created small example to demonstrate my AJAX implementation. There will be a web service with two methods. One is for simple addition operation over two floating values, and another is for RDBMS communication. The example project structure is presented below.

The data represents a simple table with books information. I am using PostgreSQL database in this example, and Npgsql provider.

code format="sql" -- Table: books_p

-- DROP TABLE books_p;

CREATE TABLE books_p ( isbn character(13),  author character(200),  title character varying(255),  yop character(4) ) WITH ( OIDS=FALSE ); ALTER TABLE books_p OWNER TO "Dmitriy"; GRANT ALL ON TABLE books_p TO "Dmitriy"; GRANT SELECT, UPDATE, INSERT, DELETE ON TABLE books_p TO public; code



The structure of project presented below.



The web service methods are presented below.

code format="csharp" using System; using System.Text; using System.Web.Services; using Npgsql;

namespace myAjax.ws { [WebService(Namespace = "http://localhost/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class AJAX : System.Web.Services.WebService {       [WebMethod] public string GetDbData(int page) {           StringBuilder data = new StringBuilder; NpgsqlConnection conn; NpgsqlCommand command; NpgsqlDataReader dr;

using (conn = new NpgsqlConnection( "Server=localhost;Port=5432;User Id=pgdbusr;Password=pgdbusr; Database=books;Pooling=True;")) {               conn.Open;

command = new NpgsqlCommand("select count(*) from books_p", conn); int rows = Convert.ToInt16(command.ExecuteScalar.ToString); int rp = 10; int offset = 0; int anchors = rows / rp;

if (page != 1) offset = (page * rp) - rp;

using (command = new NpgsqlCommand("select isbn, author, title, yop from books_p limit " + rp.ToString + " offset " + offset.ToString, conn)) {                   try {                       using (dr = command.ExecuteReader) {                           data.Append(" ");

data.Append("  <td align=\"center\">ISBN "); data.Append("<td align=\"center\">Author "); data.Append("<td align=\"center\">Title "); data.Append("<td align=\"center\">YOP ");

while (dr.Read) {                               data.Append(" ");

for (int i = 0; i < dr.FieldCount; i++) data.Append(" <font size=\"2pt\">" + dr[i] + " ");

data.Append(" "); }

data.Append(" "); }                   }                    finally {                       conn.Close; }               }            }

return data.ToString; }

[WebMethod] public float Sum(float arg1, float arg2) {           return arg1+arg2; }   } } code

The magic of web service methods accessibility exists in the [WebMethod] directive.

Next, lets create a simple web form for our example. Below is a complete source code for web form.

code format="asp" <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="myAjax.aspx.cs" Inherits="myAjax.myAjax" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <script type="text/javascript" src="include/ws_wrapper.js"> myAjax <script type="text/javascript"> function get_db_data(p) { var data = document.getElementById('db_data'); data.innerHTML = '<img src=\"images/wait.gif\" border=\"0\">'; var ws = new WS('http://localhost/', 'ajax', 'ws/AJAX.asmx', 'GetDbData', true, data); ws.addArgument('page', 'number', p); ws.execute; }

function sum(a1, a2) { var sum = document.getElementById('sum_result'); var ws = new WS('http://localhost/', 'ajax', 'ws/AJAX.asmx', 'Sum', sum); ws.addArgument('arg1', 'number', parseFloat(a1)); ws.addArgument('arg2', 'number', parseFloat(a2)); ws.execute; } code

Here we can see how the web service methods will be called from our web form. The magic happens in JavaScript function. Lets take a look at sum JavaScript function.

code format="javascript" function sum(a1, a2) { var sum = document.getElementById('sum_result'); var ws = new WS('http://localhost/', 'ajax', 'ws/AJAX.asmx', 'Sum', sum); ws.addArgument('arg1', 'number', parseFloat(a1)); ws.addArgument('arg2', 'number', parseFloat(a2)); ws.execute; } code

First line is for creating a reference to web service return value receiver in the web form. In the next line, we create an instance of web service wrapper with appropriate arguments. In the next two lines, we add two arguments which actual web service method requires. The final line will do an actual web service call. Below are results of those two functions execution.

 =The Mono Project=

The importance of ASP.NET as well as entire .NET framework was not avoided by open source community. And so, the Mono project was born.

Mono is a software platform designed to allow developers to easily create cross platform applications. It is an open source implementation of Microsoft's .Net Framework based on the ECMA standards for C# and the Common Language Runtime. Mono can be run on GNU/Linux, BSD, Unix, Mac OS X, Solaris and Windows operating systems.

Mono is amazing project which allows easily port existing .NET application from Windows platform to *NIX. Below are screen shots of AJAX ASP.NET example (without a single change!) under Apache web server on my laptop which runs on FreeBSD.

 =ASP.NET MVC=

Another very good extension for ASP.NET is MVC paradigm implementation. The principal difference between web forms and MVC is an URL request handling. In case of web forms, when aspnet engine receives a request for particular URL it searches for physical file under IIS. In case of MVC, when the aspnet engine receives a request for particular URL it transfer that request to method/function in the controller.

Lets take a look at simple MVC ASP.NET application. In this example I will use the same books PostgreSQL database that I used in AJAX example above.

The project structure presented below.



Our Model contains following code:

code format="csharp" using System; using System.Data; using System.Collections.Generic; using Npgsql;

namespace mvc.Models {   public class DataModel {       public string isbn; public string author; public string title; public string yop; }

public class Data {       public List code

I also modified slightly **RegisterRoutines** fragment from Global.aspx file to handle default controller.

code format="csharp" public static void RegisterRoutes(RouteCollection routes) {    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(         "Default", // Route name          "{controller}/{action}/{id}", // URL with parameters          new { controller = "Default", action = "Index", id = UrlParameter.Optional } // Parameter defaults     ); } code

The example above will just display a list of books received from database. Below is the result.



Please note the URL in the browser's address bar does not contains .aspx page name. This might be also considered as feature of MVC in ASP.NET.  =Conclusion=

ASP.NET probably is the most powerful framework for web development at present. It allows create a simple web application in hours, and complex application in just a weeks. I will prove this statement in the next project – simple Flight Booking application.  =References=


 * 1) [|ASP.NET]
 * 2) [|Wikipedia]

Last revision date: {$revisiondate}