09/02/2008

MVC with ASP.NET

Model view controller with ASP.NET

 

It’s now generally admitted in the community that Unit testing and TDD (Test Driven Development) are valuable techniques when it comes to increasing the overall quality of our code. Nevertheless unit testing can be costly especially when you’ve applications with a lot of logic implemented in the UI. 

 

Therefore if we want to make our application testable we need to separates the UI from the rest of the application.  Martin Fowler described on his site some patterns that separate and diminish the UI logic to a bare minimum.  They are all variants of the classical MVC (Model View Controller) pattern.  The MVC split the application in 3 parts: the view handles the display, the controller that responds to user gestures and the model that contains the domain logic. 

 

The MVC is the foundation of very popular portal frameworks like Ruby on Rails.  To build web sites applying the MVC pattern with .Net developers can choose among several MVC frameworks like Monorail.  In anyway, MVC frameworks like Monorail are based on completely different paradigm as the ASP.NET framework.  This means that you have to re-learn to program web apps from scratch.  Another setback is that there are no ways to refactor your old ASP.NET applications so that they can fit into the MVC framework.

 

I want to make myself clear, I believe that frameworks like Monorail or the coming System.Web.MVC are the future way of programming web apps in .NET but it demands a considerable amount of effort to learn new frameworks. It’s difficult for someone like me who has invested lots of years in mastering the classical ASP.NET code-behind model to re-learn everything from scratch. In the meantime this should not be an excuse to not make my code more testable.

 

In this post I will explicit through a simple example how to use the model view controller pattern on top of the code-behind model. 

 

We will create a login form with the MVC pattern.

 

Setup your solution

Create a new solution “Zoo” with 3 projects ->

-         ZooWebsite-> ASP.NET web appplication

-         ZooLibrary  -> Class library

-          ZooTest  - Class library

 

- Create a reference from ZooWebsite to ZooLibrary

(ZooWebsite , add reference, project tab select ZooLibrary)

- On ZooLibrary add a reference to System.Web

 

 

The View

To make our code testable it’s very important to be able to decouple the UI from the ASP.NET code-behind.  Therefore we will create an interface our ASP.NET page should implement.  This View interface will represent the contract the UI as to conform to.  When we will test our controller we will not do this with our actual web page but through a mock object that implements the View interface.    

 

Add an interface ILoginView on the project ZooLibrary:

 

namespace ZooApplication.Library

{

     public interface ILoginView

    {

        string ErrorMessage { get;set;}

        string EmailAddress { get;set;}

        string Password { get;set;}

        void RedirectFromLoginPage();

        System.Web.UI.WebControls.Button BtnLogin { get;set;}

    }

}

-> Edit the default aspx page and enter: Welcome you are authenticated!

-> Add the login.aspx to the ZooWebsite project.

 -> Edit the source of the login.aspx part -> add two textboxes, a button, and validators:

 

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="Login.aspx.cs" Inherits="ZooApplication.Website.Login" %>

 

<!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">

<head runat="server">

    <title>Login page</title>

</head>

<body>

    <form id="form1" runat="server">

        <div>

                Login form<br />

                <asp:Label ID="LblErrorMsg" runat="server" Text="Invalid login" Visible="false" ></asp:Label><br />

                Email Address:

                <asp:TextBox ID="TxbEmailAddress" runat="server"></asp:TextBox>

                <asp:RequiredFieldValidator ID="RfvEmailAddress" runat="server" ErrorMessage="Enter your email address!"

                    ControlToValidate="TxbEmailAddress">

                </asp:RequiredFieldValidator>

                <asp:RegularExpressionValidator ID="RevEmailAddress" runat="server" ControlToValidate="TxbEmailAddress"

                    ErrorMessage="Invalid email address!" ValidationExpression="w+([-+.']w+)*@w+([-.]w+)*.w+([-.]w+)*">

                </asp:RegularExpressionValidator></div>

            <div>

                Password:

                <asp:TextBox ID="TxbPassword" runat="server"></asp:TextBox>

                <asp:RequiredFieldValidator ID="RfvPassword" runat="server" ErrorMessage="Enter your password!"

                    ControlToValidate="TxbPassword">

                </asp:RequiredFieldValidator>

            </div>

            <div>

                <asp:Button ID="PageBtnLogin" runat="server" Text="Login" />

            </div>

        </div>

    </form>

</body>

</html>

 

 Because the code-behind is not testable and don’t make part of the SUT (Subject Under Test) we want to diminish the code-behind logic to a bare minimum.   The view responsibility is limited to output  the data coming from our model in a human readable way and to expose user input to the controller. 

Therefore we implement our interface through an aspx page that only contains a set of properties that binds data coming from the controller with our web controls. 

Generally we will try to implement all the presentation logic into the controller.  The only exception here will be the RedirectFromLoginPage() method. 

We could use a provider pattern to abstract this from the page but for the sake of simplicity I’ve decided to implement it directly in the page. 

 

 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using ZooApplication.Library;

 

namespace ZooApplication.Website

{

    public partial class Login : System.Web.UI.

18/03/2007

Comparing ASP.NET with PHP

In 2005 my management asked me to write a report comparing ASP.NET and PHP. 

These technologies have evolved since 2005 and so has my opinion.  Nevertheless I think that the comparison I made remains valid. 

 

Introduction

When I compared J2EE, the Sun’s Java enterprise platform, with .Net I found lots of articles, studies and benchmarks. So I started this analysis by collecting articles that compared .NET and PHP and was rapidly disappointed because I found very few articles on this subject.  In fact this didn’t surprise me because these technologies are very difficult to compare.  You can easily compare J2EE and .NET because these have clear resemblance in the way they are used, in their architecture and programming model but PHP and .Net have only one thing in common, they can be used to build websites.

Nevertheless I go for the challenge, I will compare Skynet most used technologies PHP and .Net.  In this document I give a brief history of PHP and .Net, explain what they are and analyze the strengths and weaknesses of both and how these could fit in a growing organization as Skynet. 

History of PHP

1995 - Rasmus Lerdorf creates a perl bibliotheque and named it PHP ‘Personal Home Page Tools’. 

1997 - PHP2 (stayed mostly in beta stadium)

1998 - PHP3 : was first version of the actual php language

2005 - PHP5 introduced notions of Object Oriented paradigm into the language.  PHP was initially an open source project that has constantly grown in popularity especially against webmasters.    

History of ASP.NET

1995 - ASP was first released.

2001 – Microsoft released his new vision and technology: .Net. It englobes he whole new set of technologies like the web application part ASP.NET. ASP.NET has the same name as ASP but it is a completely new technology. From ASP it has only the name in common. The father of .Net is Anders Hejlsberg inventor of Pascal language.  .Net was mainly the response of Microsft to Sun’s Java platform.  

2005 - .NET2 is released with Visual Studio2005 – SQL2005 – Biztalk2006

 

What is PHP?

PHP: Hypertext Preprocessor is an open source server side programming language extensively used for web scripts and to process data passed via the Common Gateway Interface from HTML forms etc.[2] PHP can be written as scripts that reside on the server and may produce HTML output that downloads to the web browser. When the PHP preprocessor in your Web server notices a PHP language tag like the following, the

PHP engine is invoked to execute that code:

 

Hello

<?php

some code here that output the word WORLD!

?>

Result of the html page:

Hello WORLD!!!

 

PHP is similar to Microsoft's Active Server Page technology (ASP) the ancestor of ASP.NET.  PHP runs mostly on UNIX servers but it can also run on Windows based servers. It is used for connecting to a database to create all kinds of web applications, such as product catalogs, changing content, calendars, and e-commerce.

 

What is .Net?

Is Microsoft's set of software technologies for connecting information, people, systems and devices. It is based on web services which are small applications that can connect to each other as well as to other larger applications over the Internet. .Net is made to run on any type of devices and for the development of all type of applications: web sites, web services, windows applications, windows services…

 Although .Net is a set of proprietary technologies developed by Microsoft to offer an alternative to Java and J2EE that runs only on windows based machines Microsoft published the definitions of the.Net technologies as open standards. This allows projects like Mono.   Mono is the name of an open source project led by Novell (formerly by Ximian) to create an ECMA Standard compliant (Ecma-334 and Ecma-335), .NET compatible set of tools. Mono can be run on GNU/Linux, UNIX, Mac OS X, and Windows based computers.

 

ASP.NET is the technology built into .NET that you use to create Web pages and other Internet-based applications. ASP.NET is not merely the next version of ASP (Active Server pages). ASP was thrown out and ASP.NET was written from the ground up. It's a brand new, object-oriented platform with a completely different programming model as ASP or PHP.  In ASP.NET developers are able to write web applications on the same manner as they writes other programs like windows applications. 

 

Another big difference of ASP.NET with ASP or PHP is the separations of the HTML and the program part.  In ASP.NET the code part of the web application is completely separated from the visual part.  Separation of the code and html is entirely new for web development.  PHP code consists of HTML and code mixed together but there are tinplating frameworks available that brake the html from the code.  With ASP.NET the coding and design part can completely be separated and the design and development work can be done by different teams.

 

 

PHP Strength and Weaknesses

PHP is very easy to learn as most of all scripting languages (javascript, vbscript,…).  Especially for programmers that knows the C language.  As most of the scripting languages it’s not strongly typed what give PHP flexibility but this comes at the expense of robustness.  Most generally, "strong typing" implies that the programming language or implementation enforces some kind of constraints upon programs, preventing them from running code which uses data in an invalid way. For instance, an integer addition (1+1=2) operation may not be used upon strings; (“1” + “1”=”11”) a procedure which operates upon linked lists may not be used upon numbers.  The flexibility of weak typing of scripting languages causes bugs that are very hard to detect. 

 

Also as most of all scripting languages php is interpreted.  Again interpreted languages are easy to handle because you don’t need to compile the code but this come at the expense of efficiency because interpreted code is always slower as compiled code. Some optimizer are available that compiles PHP code to speed performance. Additional commercial products also exist, such as the Zend Performance Suite, which can cache precompiled PHP pages, further speeding overall performance but these remains external products.

 

But the greatest advantage to use a compiler is not performance but checking for errors.  Good type checking is a well proven part of software engineering. A strongly typed language complier picks up errors and this is not possible for weak typed languages.

 

Other advantages of typed languages are that the IDE (development tool) can help the programmer.  The programmer doesn’t have to do manual type inference or read documentation.  All this is not possible for PHP due to he’s weak typing.

 

PHP don’t enforce at all Object Orientation. Even PHP5 is not truly object oriented because it has to stay compatible with the older versions.  What give the ability to programmers to really play with the code and don’t enforce at all Object Oriented structure.  This is also a great shame, as there is much to be gained from adopting an object oriented approach to developing object oriented applications, perhaps the most important being code reuse. A well written piece of object oriented code can easily be employed to solve the same problem in other projects; we can simply slot it in whenever we need it.  This is why code reuse happens less frequently in PHP.

 

“The object oriented paradigm is an approach to programming that’s intended to encourage the development of maintainable and well structured applications. Many PHP coders regard object oriented programming (OOP) as some kind of mystic art, given that frequently, examples of PHP look only at procedural approaches to problem solving. (Note that procedural programming is the name given to non-object oriented programming.” [1]

 

 

ASP.NET Strength and Weaknesses

ASP.NET has a more rigorous Object Oriented programming model as PHP what makes it more complicated to learn. To master the power of ASP.NET developers must have a through understanding of the Object Oriented paradigm but for programmers who master this paradigm ASP.NET code is easier to write, debug, and maintain as PHP, particularly for larger projects.

.Net is an object-oriented programmer's dream, with language flexibility, and with sophisticated object-oriented features supported.  The object-oriented foundation of ASP.NET programming make it easier to read, reuse, maintain, and share code among groups of programmers who must work together on a single project.

 

Therefore ASP.NET uses the descriptive programming paradigm. The paradigm is based on the idea that most of the programming tasks consist of solving common problem.  One goal of ASP.NET was to eliminate much of the tedious coding. By solving these problems by using reusable components, wizards or patterns we are able to reduce drastically the amount of coding and also increase the quality.  ASP.NET provides an incredible amount of components, wizards and patterns.  This is also why some beginning developers find ASP.NET complicated. ASP.NET is also more difficult to learn for web developers because they have to completely change the way they write web applications.  But ASP.NET code can be written in any language, so developers can leverage their existing programming knowledge, transferring their experience from one language to .Net. PHP developers can even choose for the PHP language in .Net.

 

ASP.NET provides the developer with a generous suite of debugging tools (including breakpoints, tracing, and extensive error messages).  Having a great IDE is the central factor to increase developer’s productivity and overall quality.  .Net comes with many IDE where the developer can develop any kind of applications with the most powerful WYSIWYG design and editing tools and wizards that can help him through tedious or complex tasks.    Developers can choose for the enterprise or professional edition of Visual Studio but Microsoft also released several free versions: Visual Studio C# Express, Web Express, VB Express.  Where in Visual Studio you can program all types of applications the Express editions are limited to Web development or Windows development. Beside Microsoft lots of different IDE are also available like from Borland. 

 

.Net code is compiled in native processor code.  Compiled code is a lot faster as interpreted code like PHP.  ASP.NET comes also out of the box with powerful caching capabilities what makes it very scalable.

 

Facing growth

Web development in PHP becomes harder to maintain and develop when the scope of the projects and the teams grows. 

 

PHP is perfectly suited for applications with a low degree of complexity.  It makes webmaster able to easily maintain the design and coding part of the applications.  When the complexity and size of the projects increase above a certain level it is not possible for one individual to have a complete picture of the application.  Organizations have to adapt and face new challenges.  Because the higher complexity demands more specialized skills webmasters have to specialize themselves in coders or webmasters and the development of web applications have to be more organized.  This is the time in the organization lifecycle where development processes arises.  With these processes more and diversified tasks have to be done like business analyses, functional analyses, testing and decision processes must be formalized. All theses tasks demand further specializations and organization members that are involved in the process of building new applications have to play new roles like the role of tester, architect, business analyst, project manager.   

 

To be able to work with many developers and to support the development process new tools have to be setup that helps maintaining the quality and productivity of the development and facilitates the communication between the different roles. 

Growing organizations needs tools that sustain the project lifecycle like source controllers that let several developers work on the same applications, release management tools where version of different applications are stored, process guidance tools that help the project manager gather data on the productivity or quality of the project, testing automation tools, reporting and planning tools.

 

Although some project lifecycle management software exist for PHP they are hard to integrate and to setup. This is the reason why at Skynet for PHP development we still miss all these tools that enhance the quality and productivity of the developments. .Net and other enterprise platforms like J2EE offer a large amount of such software.  Most of them can be integrated into the development environment of the developers or can be deployed as separated software for project managers, business analyst, testers.  Developments of projects in larger teams in .Net can be completely supported with Team System and it integrates perfectly into the usual tools used by the project manager or business analyst like Word or Excel. It comes out of the box with several processes like Agile or CMMI but can also be adapted to the organization existing processes.

 

PHP was and remain an open source project.  This explains why tools for the support of lifecycle management are hard to find and to integrate.  Nevertheless this could change in the future because PHP is now conducted by a commercial organization: ‘Zend Technologies’.  Zend is currently investing in the development of lifecycle management tools.  Nevertheless Zend is just a beginner and started to penetrate the market.  It could last for years before Zend will be able to compete with organizations as Microsoft, IBM or Sun that have invested since years in the development of lifecycle management tools.

 

 

 


 

Summary

Feature

.Net

Java

PHP

Integrates tools for working in team  like source controller, process guidance tools, architecture tools

Yes

Yes

Yes, open source tools are available but they are not integrated

IDE with Integrated testing tools (Unit – Load).  Improve the overall quality of the development process

Yes

Yes

No

Compiled Code – Increases website speed (precompiled is the fastest)

Yes – both precompiled and dynamically compiled when a page is requested

Yes – both precompiled and dynamically compiled when a page is requested

No – a 3rd party accelerator (zend core) can be used to increase performance

Compiled Code – Compiler detect compile time errors what increase the early fault detection in code

Yes

Yes

No

Scripted Language – results in poor website performance

No

No

Yes – a 3rd party accelerator can be used to increase performance but it s not standard and outside component

Strong error handling features

Yes

Yes

Yes

Object Oriented – Increases the ability for code reuse and provides enhanced features as well as reduced development time; since code is more reusable, results in fewer bugs that can be discovered by any client and fixed for everyone; encourages developers to write more maintainable code.

Yes

Yes

No, even PHP5 is not truly Object Oriented

Strong Typed – Demand more effort to the programmer but pays of in  quality and robustness

Yes

Yes

No

Supported Development Languages – easier to find developers

C++, C#, Visual Basic.NET, Jscript.NET, Python, Perl, Java (J#), COBOL, Eiffel, Delphi – 25 languages supported currently

Java

PHP

Browser Specific HTML Rendering – different HTML is automatically sent to IE than to Netscape, reducing incompatibility issues

Yes

No

No

Open Source

No

Yes

Yes

 

 

14:58 Écrit par Geoffrey Vandiest dans Web | Lien permanent | Commentaires (0) | Tags : asp net vs php, comparing, asp net, php, web, technologies |  Facebook |

08/02/2007

Web technology cocktail

Interoperability between PHP & .Net

 

In my team, we are currently testing a new type of architecture. We decided to mix technologies and uses PHP for the front-end of our application and WCF for the business tyre.

One advantage of PHP over .Net is that there are a lot more PHP developers available on the market and they are usually cheaper as their ASP.NET colleagues. Most of the developers working on the web started their career as webmasters. They learned programming on PHP because of the simplicity of the PHP language and the fact that Microsoft never made a product that was appealing to them. For most of this type of autodidacts it’s really hard to master an OO platform as ASP.NET of JSP. So in my opinion despite the fact that ASP.NET or JSP are far more advanced and proposes a better set of tools, PHP will remain for a long time the most used web platform. For the same reasons I predict that it will be very hard for Microsoft to sell his “expression” suite to webmasters.

The PHP language is very flexible and easy. The entering cost was really low, in a couple of days we where able to master the language. We found a very effective way of interoperate both technologies by using wsdl2php.

Nevertheless I’m a bit disappointed over PHP because we are missing a good development environment. For the moment we are using Zend Studio and it really sucks. The auto completion is not working properly and we were unable to configure it for remote debugging or for source control. We use a distant development server because the application will be deployed on linux clusters and we wanted to have the same development environment as our deployment environment. Zend is really bad with this type of configuration.

It’s like we are back to the stone age of development; no debugger, no source controller. Because of that we are forced to phone to all members of the team to know who is working on what. Our code is full of "echo" and "print_r" statements. Bugs appears because someone else has saved some new files on the server that are incompatible with the current version of the files.

PHP is a nice little platform but it really miss an IDE as VS.NET 2005 IDE and other tools that boost up productivity and quality.

13:20 Écrit par Geoffrey Vandiest dans Web | Lien permanent | Commentaires (0) | Tags : interoperability, php, asp net, wcf |  Facebook |