ASP.NET 3.5 Application Architecture and Design

By Vivek Thakur
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to Architecture and Design

About this book

Application architecture is an essential skill for ASP.NET developers. It is always tempting to jump in and start coding, but planning your architecture early in the project will leave you with a solid application that scales well, is easy to modify and extend, and saves you time and effort later on. As businesses struggle to control their costs, writing solid code that can be extended easily is becoming even more important.

This book takes a pragmatic approach to Application Architecture in ASP.NET 3.5. It presents a series of common architectural models, and shows how to select the best ones for your project and apply them.

The book begins by showing you how to use the main architectural models in your applications. You will see how to implement n-tier architectures, MVC, design patterns, and more. But this is no software engineering theory book – it is a practical, hands-on guide that shows you how to use these techniques in your software straight away. We then go on to build SOA (Service-Oriented Architecture) applications with the Windows Communication Framework (WCF). Finally the book contains some essential guidance on effective database design, and a chapter on localizing your applications.

This book is a great way to learn ASP.NET Architecture in a practical, hands-on way. It will also serve as a quick reference for improving your application design.

Publication date:
October 2008
Publisher
Packt
Pages
260
ISBN
9781847195500

 

Chapter 1. Introduction to Architecture and Design

Almost every software developer I know is fascinated by software architecture and design. High-level architecture and design patterns are concepts that beginner developers least understand. For most of us, programming is relatively easier to learn; usually good aptitude and decent logical skills are enough to be a good programmer. But architecture is altogether a different beast to handle. It is more of an art, and usually takes years of experience to master.

In this chapter, we will focus on:

  • Understanding architecture and design from a practical viewpoint

  • Architectural styles

  • What Design patterns are

  • Different stages of a project lifecycle

  • Difference between tiers and layers

Software Architecture

There are many different definitions of software architecture scattered across the web, in reference materials, and in books. In the wide world of programming, many of the definitions you may find are most likely going to be extremely technical in the language they use, and can be difficult for a beginner to fully grasp and understand. There are even places on the web that list thousands and thousands of different definitions by leading software architects, engineers, doctors, philosophers, and professors. (Reference: http://www.sei.cmu.edu/architecture/community_definitions.html).

To begin with, let's start with a technical definition:

Software architecture is an abstraction, or a high-level view of the system. It focuses on aspects of the system that are most helpful in accomplishing major goals, such as reliability, scalability, and changeability. The architecture explains how you go about accomplishing those goals.

Now we will translate this definition into something simple, generic, and easy to understand:

Software architecture is a blueprint of your application.

To elaborate more on the "blueprint" part, let us try to understand software architecture with a simple analogy—the process of casting.

Casting is a manufacturing process in which a liquid material is poured into a mold that contains a hollow cavity of a desired shape. The liquid is then allowed to cool and solidify, taking the shape of the mold it was poured into. The mold is the guide that shapes the liquid into the intended result. Keep in mind that the mold can be of any shape, size, or dimension, and is separate or unrelated to the liquid that is poured in.

Now, think of software architecture as the mold and think of your project as the liquid that is poured into this mold. Just like casting, software architecture is the guide that shapes your project into the intended result. The architecture of a software system has no strict relation to the actual code that is written for this system. The architecture simply makes sure that the development process stays within certain defined limits.

 

Software Architecture


There are many different definitions of software architecture scattered across the web, in reference materials, and in books. In the wide world of programming, many of the definitions you may find are most likely going to be extremely technical in the language they use, and can be difficult for a beginner to fully grasp and understand. There are even places on the web that list thousands and thousands of different definitions by leading software architects, engineers, doctors, philosophers, and professors. (Reference: http://www.sei.cmu.edu/architecture/community_definitions.html).

To begin with, let's start with a technical definition:

Software architecture is an abstraction, or a high-level view of the system. It focuses on aspects of the system that are most helpful in accomplishing major goals, such as reliability, scalability, and changeability. The architecture explains how you go about accomplishing those goals.

Now we will translate this definition into something simple, generic, and easy to understand:

Software architecture is a blueprint of your application.

To elaborate more on the "blueprint" part, let us try to understand software architecture with a simple analogy—the process of casting.

Casting is a manufacturing process in which a liquid material is poured into a mold that contains a hollow cavity of a desired shape. The liquid is then allowed to cool and solidify, taking the shape of the mold it was poured into. The mold is the guide that shapes the liquid into the intended result. Keep in mind that the mold can be of any shape, size, or dimension, and is separate or unrelated to the liquid that is poured in.

Now, think of software architecture as the mold and think of your project as the liquid that is poured into this mold. Just like casting, software architecture is the guide that shapes your project into the intended result. The architecture of a software system has no strict relation to the actual code that is written for this system. The architecture simply makes sure that the development process stays within certain defined limits.

 

Software Design


Software design refers to the thought process involved in planning and providing for a better solution during problem solving. Software design comes after the architecture is decided upon. Architecture is more closely related to the business needs of the project, and theoretically it does not concern the actual technology platform (such as J2EE or Microsoft .NET or PHP) on which the application will be built (although practically we can decide the platform either in parallel with working on the architecture of the application or before doing so). Software design deals with the high-level concepts related to the actual implementation of the architecture in our projects, which include tasks such as usability studies to make sure our project targets the right kind of users, deciding which design patterns to use to make our application scalable, secure and robust. During the design phase, we also decide on the implementation methodology to be used in the actual development phase (which comes after design and involves actual coding). The following diagram shows how architecture and design fit together and relate to each other:

As we can see in the diagram, the actual business requirements and scope of the project are the deciding factors when working on the application architecture. Software design and development come next and, based on the design, the actual development work gets executed. A single problem can have many possible solutions, some of which will be more efficient than others. Before a developer starts chunking out code for a particular business requirement, it would be prudent and beneficial to give some thought and select the best approach from the possible list of options to assure that code performance, scalability and maintainability is not sacrificed in the long run.

In order to understand all of this by way of a simple analogy, consider a car manufacturing plant as an example. The mechanical engineers developing the high-level blueprint of the car would be the architects, and the blueprint itself would be the architecture of the car. This blueprint would include high-level specifications such as:

  • Dimensions of the car and its components

  • Engine capacity

  • Type of car (hatchback, sedan, or SUV)

  • Maximum passenger capacity, and load capacity

  • Minimum build strength

So the blueprint would specify the limitations as well as the conditions that need to be fulfilled for any design of that car, and besides the blueprint there would be additional constraints such as the budget for the production costs. But this blueprint would not include details of how exactly the engine would be designed, what quality of steel would be used, what type of tires would be used, what type of plastics would be used for the dashboard and other parts, and so on. All of this would actually be decided by the design engineers, who will make sure that their choices fit the blueprint specifications in the best possible way. The engineers will also consider production and design techniques that other car companies might have followed, so that they don't re-invent the wheel.

The actual assembly line production will follow the designs and techniques specified by the engineers and will involve tasks such as cutting metal, choosing the right machines, assembling the individual components, painting, safety tests, and so on, to create a complete working car. The following figure will correlate this example with the equivalent aspects of software development:

From the figure we can see how the car company example loosely translates to software architecture, design, and development. Now let us take another analogy, this time more closely related to the software industry. Consider a company that needs to build a bulk emailing program for its social networking website. A software architect will first understand the high-level requirements of the program, such as:

  • How many average emails need to be sent on a daily or hourly basis?

  • How often will the emails need to be sent?

  • Will there be attachments involved? If yes, what will be the biggest attachment size?

  • Does this program need to be extensible and re-usable (for other similar websites or applications in that company)?

Based on the answers to the above questions, the architect will come up with an application architecture which covers all aspects of the actual business needs. The architecture will decide how the emailing program should be developed: a Windows Service, or a Web Service, or a console utility, or some batch program run by a scheduler.

But the architecture would not include details such as:

  • How should the program handle exceptions?

  • How will we make sure that the code is efficient in terms of performance, and does not hang while sending bulk emails in a short period?

  • How should the program perform error logging?

  • How will the program be developed so that it is re-usable (if the architecture dictates it to be developed as a re-usable component)?

That's the part where design comes into the picture. The application architecture would define limits and boundaries within which the design would move around and improvise. So the architecture would neither go deep into the nitty-gritties of the design phase, nor would it dictate implementation guidelines and programming rules, as the architecture has no relation with programming at all. In fact, the architecture lays out specifications which are more aligned with business requirements, and makes sure that all business aspects are met and taken care of.

Coming back to our bulk email program, the term software design can be loosely translated into the process of designing the actual program, which involves using specific programming techniques (or design patterns, which we will study later) and laying out the basic solution framework. All coding would actually occur within that framework. We can have multiple design options for the same architectural specification, and it is up to the stakeholders to decide which one to go for, considering the overall efficiency and budget constraints.

Here is a simple diagram illustrating the basic process:

 

Architectural Styles


With time, some of the famous and widely used approaches and techniques among the architects have been grouped together into architectural styles. A particular architectural style represents the interaction and behavior pattern between the system and its components, along with a particular layout and structure. Some famous architectural styles are:

  • n-tier model

  • Windows DNA

  • Data-centric

  • Service Oriented Architecture

  • Plug-in system

There are many more styles, and each style can be customized to suit individual project needs. We will learn more about some of these styles in the coming chapters, along with some practical examples. It is very important to understand the concept, approach, and effective implementation of a style so that we can decide when to use which style in our own applications. One can even create a new style by combining any of the existing styles and customizing it to achieve greater efficiency and adaptability.

 

Architecture and Design in ASP.NET


But, as we look to the horizon of a decade hence, we see no silver bullet. There is no single development, in either technology or in management technique that by itself promises even one order-of-magnitude improvement in productivity, in reliability, in simplicity.

The above quote (taken from No Silver Bullet—essence and accident in software Engineering, Brooks, F. P.) aptly highlights the fact that technological improvements can only be stepping stones instead of being silver bullets to solve all architectural and design problems in one go. The ASP.NET platform has rapidly gained a foothold in the web development industry. One of the major factors in favor of ASP.NET, compared to JAVA or PHP, is the excellent integration of the Microsoft IDE, Visual Studio, with the framework. The VS IDE has evolved, complementing the framework itself, with time-saving features such as detailed intelligence support, debugging assistant, and code complete, to list a few. Also, Microsoft has been aggressively adding different tools and technologies, enhancing the overall developer experience. AJAX, LINQ, WCF, WWF and SilverLight have not only stirred up the development world but have also left many developers confused and wondering as to how good these new technologies are, and how they can maximize their productivity by using them.

Note

Some developers strongly feel that these new technologies are coming along much faster than they can be absorbed. There have been many heated debates on the extra aggressiveness with which Microsoft is releasing new products. In many of the offline discussions we have had upto now, most people feel that developers are not getting enough time to absorb existing technologies and "keep pace with MS". People are still struggling with master pages and partial classes, and we have AJAX, SilverLight, WPF, etc.!

Many developers feel that there is simply too much to grasp in too little time, considering the fact that many clients are still using VS2003 and are refusing to upgrade due to reasons such as lack of funds, apprehension of going with new and untested technologies such as WPF and Silverlight, lack of experienced programmers, and so on. Some customers are also confused and are not sure how these new technologies can benefit their business!

We should understand that none of the new technologies were created to be "silver bullets". They have been added to give developers options to chose from, to reduce development time, and to be more effective. These technologies should be used in the right architectural context instead of blindly following them, which can lead to a greater risk through poor implementation. All changes are good, but we need to understand why the change is needed and how it will help us in balancing the advantages and disadvantages.

We have thousands of books, online articles and tutorials on how to use AJAX, LINQ, WWF, and WPF in ASP.NET, but there are still very few online articles and limited books that focus on what architecture to use, and in which ASP.NET application. Because each project is unique in its own way, we can never use a copy-paste solution. The important thing to bar in mind when learning application architecture and design is that there are no strict rules, only guidelines. And these guidelines were developed based on the experience gained over years of work by developers on different projects.

Upcoming latest technologies should not be mistaken as the means to develop better applications. Lets go back to the pre-ASP.NET years for a moment. In those days, classic ASP was very famous. There were many big, famous, and stable applications in classic ASP 3.0. It was difficult to create an object-oriented application with classic ASP (compared to the intuitive way, in which we can do it so easily now in ASP.NET), but good programmers used classes in ASP as well, adopting elements of object-oriented re-usable design. A better platform, such as ASP.NET, did help in building websites that could support a better architecture, but the power to use it in an efficient way still lies in the hands of an experienced programmer.

Just as ASP.NET was a major stepping stone in web development, AJAX enhanced the UI experience along the same lines, providing a user-friendly experience while browsing websites, and LINQ was introduced to revolutionize data access. But still there are numerous robust and popular websites in ASP.NET not using any of the new technologies. This means that the key to building a good website can never only be learning and absorbing the latest technology out there, but also how you put it to use—how you make these technologies work for your project in a comprehensive way.

If one knows how to write clean and maintainable code and use efficient programming techniques to create a good stable architectural platform and application structure, then technology will supplement the design. Without a stable architecture and good coding practices, a programmer might use the technologies in a haphazard manner, creating messy code and junk websites. But once we understand basics of the application architecture and the different design patterns, then these technology tools become our assets.

Technology and Art

Unlike coding, which demands strong logical skills, application architecture and design is more of an art, and it takes time and experience to become a good architect. For example, it takes a very good and experienced designer to create a unique and attractive design for a car. Once it's done, the assembly line can create millions of units of that model using the appropriate machines and tools for the job. Similarly, it is relatively easier to understand and code in ASP.NET, but it can take some time for even an intermediate developer to be able to understand and design the pros and cons of the different architectural options that might suit a given web application. And unlike coding, there are no strict rules in architecture. A design which might not work for some projects can work perfectly well for others. That's why it might take years of experience to develop an eye for good architecture and design. This, coupled with the fact that each application is unique in its own sense and warrants its own design and architecture, can be confusing for developers when deciding what is best for their project.

Therefore, architecture is one thing which requires patient understanding, as well as creativity in order to be able to adapt and innovate according to a project's needs.

 

Architecture: First Steps


How do business requirements dictate architectural decisions? Lets understand this through a quick and small example. Assume that a software company, Takshila Inc., has recently bagged the contract for building a new inventory management system for a local cosmetics manufacturing firm. After the initial talks with the stakeholders, the business analyst from Takshila comes up with high-level specifications, which are:

  • The system should be accessible from any online location

  • The system should be able to process multiple orders at the same time

  • The system should be able to interact and process information from different locations having different databases

  • The system should interact with other software packages (such as financial software) already in use by the company

  • The system should be easy to customize later by the internal development team

With these requirements in mind, and after detailed discussions with team members, the software architect has come up with the following architectural specifications for the proposed inventory management software:

  • The system should be web based, using a thin-client architecture.

  • The system should have built-in multithreading capabilities.

  • The system should be database-independent, which means that the system should be able to work with multiple types of databases without changing the code—probable use of dependency injection.

  • The system should expose a set of functions as an API, and should also be able to import data from other sources and process this data in its own tables.

  • The system should have loosely-coupled tiers, so that each individual tier has no dependency on the other and can be used with any other tier.

Note how the business requirements have been translated into architectural specifications, and still there is not a word about a programming or development platform! So the architecture has nothing to do with development platforms, programming languages, design and so on. We can create a system satisfying the above requirements in many ways, using different designs and probably using different platforms too (for example, one could either use ASP.NET or JSP/J2EE). In short, the architecture does not care whether you use LINQ, AJAX, or Ruby on Rails. As long as you are meeting the architectural specifications, you are free to choose your own technology and tools.

 

Design Patterns


The word pattern means a guide or a model that is to be followed when making things. In software development, we often use programming techniques and solutions developed by others that prove to be credible over time. Solutions to software problems were not developed overnight, and most of these problems were common across the development world, so these time-tested solutions were grouped to be re-used by others.

So a design pattern is a re-usable solution that can be used in our projects so that time-tested programming techniques can be employed to solve similar kinds of problems.

The main difference between architecture and design patterns is that design patterns deal with implementation-level issues, and are more close to the programming and development platform, whereas architecture is at a more abstract level and is independent of the implementation. Design patterns tell us how we can achieve a solution in terms of implementation. But the patterns themselves are independent of the programming language and technology platform. We can implement a particular design pattern in any language we want: JAVA, C# or PHP. We cannot use design patterns as-it-is in our projects. They show us the right path to take in order to solve a problem, but they are not a complete solution. We cannot simply copy-paste a particular design pattern's code directly into our project. We will need to modify it to suit our own unique needs and implementation platform.

In the coming chapters, we will learn some of the famous design and commonly used patterns, with sample code in ASP.NET.

 

Project Life Cycle


From an idea to a fully functional binary or DLL, a project passes through a varied range of activities and processes. The project life cycle refers to the different logical and physical stages that a project goes through from inception to completion. The life cycle starts with gathering the business requirements and ends when the final product is delivered after complete testing. The following are the major stages of a generic project life cycle:

  1. 1. Project Initiation

  2. 2. Planning and Prototyping

  3. 3. Project Construction

  4. 4. Project Transition and Release

These stages are more-or-less common through all projects. In this section, we will see some of the basic processes and understand the importance of each. Note that it is not necessary for each project to follow a standard life cycle strictly. Every project will have its own modified version of the life cycle, as well as its own duration for each stage.

Project Initiation

This is the part where the project idea is discussed with the stakeholders. Here, we discuss the feasibility of the project, and decide if it is really worth moving forward with the project at all. A few things which might be discussed are:

  • Does the project's business model make sense?

  • Is the project feasible given the current technological platforms?

  • How big is the project going to be? Is it possible to complete the project within the business deadline?

  • Do we have the required technical talent available in the market to complete the project on time?

In this phase, the business analyst or the stakeholder(s) will create a high-level requirements document. This document will list the aim of the project and its fundamental business logic in business terms. One can also create RFQ (Request For Quotation) or RFI (Request For Information) documents to be sent to other firms who might be willing to bid for the development of the project, or to the internal development team for further development time and cost estimates.

So in this first stage, the stakeholders discuss and decide on the business feasibility of the project and prepare a document that captures most of the requirements at a very high level.

Project Planning and Prototyping

In this phase, we elaborate on the project requirements by capturing all business requirements in specially formatted documents called use cases, and then prepare a prototype as well as a project plan for the next stages of the project life cycle. Once the project initiation and inception stage is over and the project owners have selected a development team, the second phase starts, in which the architect or the development team leads and the project manager will work out a plan and a development cycle. In this phase, most of the major pre-development activities take place. These activities are described in more detail below:

Project Plan

The project manager will need to create a plan that will lay out all of the major tasks in the project life cycle, along with the resources and time required. Without a plan it would be very difficult to track and manage the progress of different stages of a project. The project plan at this stage might not be able to cover the actual development phase, because this will depend on the completion of the following tasks.

Use Case Design

The architect/business analysts will first start this phase by creating use cases, which can be simple documents explaining the interaction between the application and the end user. A "use case" lists the interaction steps sequentially, along with other possible paths for a single interaction with the user. Each use case should capture a specific scenario from end-to-end. It should also list all pre-conditions as well as post-conditions for that scenario. Here is a sample use case:

UseCase 1.10 User Login

 

Description:

Actor gains access to system.

Actors:

All roles.

Trigger:

Actor invokes the application.

Pre-Conditions:

Not applicable

Post-Conditions:

Actor is successfully logged in to system.

Basic Flow:

BF1: Log on to Client

  1. 1. The System displays the Login screen.

    2. The Actor enters:

    a. Email ID

    b. Password

  2. 3. The System validates the email ID and password.

  3. 4. The use case ends when the Actor is logged into the system. The System displays a list of messages sorted in chronological order, with links to Compose, Delete and Aggregate messages. The actor can select any of the links.

Alternate Flows:

AF1: Forgot Password

The use case starts when the actor has not logged in and clicks Forgot Password link.

  1. 1. The System displays the Forgot Password screen.

  2. 2. The Actor enters his email address.

  3. 3. The Actor clicks on Send Password.

  4. 4. The use case ends when the System sends the new password to the actor's email address.

AF2: Change Password

The use case starts when the My Account action is invoked. The actor is already logged in.

  1. 1. The System displays the My Account screen.

  2. 2. The Actor clicks on Change Password.

  3. 3. The Actor enters the current password and the new password.

  4. 4. The Actor clicks on Change Password.

The use case ends when the System saves the new password.

Exception Flows:

none

Special Requirements:

None

There are many ways of creating use cases; we can also create them diagrammatically. But to keep things simple, we can follow the above use case, which is easier to understand. After the major use cases are covered, we can move to the next step in this elaboration phase, which is, prototyping.

Prototyping

The Graphical User Interface (GUI) of any project is one of the most critical areas in terms of its overall presence and credibility. And many projects are delayed because of repeated changes in the GUI throughout the project life cycle, adding to the frustration of the programmers. For web projects, designing a working prototype in HTML before starting to work on any other activity can be very helpful, for project stakeholders as well as developers. A working prototype means that the different HTML pages would be linked to each other (based on the use cases we covered earlier), and can use dummy data to give a realistic impression of the actual project.

A GUI prototype is not only a part of the Proof of Concept(POC), but also forms an important extension of the project requirements specifications, in a graphical sense. Properly-linked HTML pages with some dummy data showing the important business process flows can be an indispensable tool, aiding in the visual understanding of the project, as well as answering all kinds of technical and business-related questions. That is why it is highly recommended to develop a prototype before starting the actual coding for a project.

Class Model

The architect and the technical lead will create an object model of the system, highlighting all important entities and how they will interact. We will learn more about how to create an object model in the coming chapters of this book.

Database Model

A database model would be created based on the class model described above. This data model, along with the object model and use cases, will help provide the development team with clear instructions, and paths to the targets and objectives. It is very common for a data model to be created before a class model. It's also very common for these two steps to be completed at the same time, as they are very closely related.

Based on the use cases, the prototype and the object/data models, the project manager, along with the architect and the team lead, will develop a project plan for the construction phase, in which the coding takes place. This plan will highlight the milestones as well as list all of the important deliverables of that phase.

Project Construction: Programming and Development

When all of the primary documentation is complete, the actual development work starts. The technical team will study the use cases and the object and data models, and start planning the delivery cycles. Here, we can use one of the following famous development methodologies:

  • SCRUM Development

  • Waterfall Model

  • Agile Development/Extreme Programming (XP)

  • Iterative Development

You can find more information about each of these techniques online via the list of references I have provided. There is a lot of online as well as offline text available on these methodologies. I personally prefer SCRUM development, which is a Chaos Theory based approach. In SCRUM, we have sprint, which is an iteration with a certain number of days (for example, 30) at the end of which the development team covers a certain set of use cases and lets the stakeholders see and test the application. During the next iteration, they cover more features, which are prioritized accordingly. Each iteration passes through a full software development cycle: planning, requirements, design, coding, testing, and documentation. The goal is to have an available release (without bugs) at the end of each iteration.

A major goal to be achieved by using this process is to allow the client to take their new product to market before it is completed in its entirety. We are also minimizing risk by developing highly-focused components in a short period of time. This development process will continue throughout all phases, promoting the release of components to a beta phase in a live environment as the life cycles are completed. The following are the major benefits or principles of the SCRUM method:

  • Keeping things simple by chunking (or batching)

  • Customer satisfaction through rapid, continuous delivery of useful software they can get their hands on

  • Working software is delivered frequently (taking weeks rather than months)

  • Working software is the primary measure of progress

  • Late changes or additions in requirements are welcome and can be added to iterations with ease

  • Close, daily cooperation between clients and developers

  • Continuous attention to technical excellence and good design

  • Regular adaptation to changing circumstances

Because the stakeholders can see and review the current application at the end of each sprint, it gives them a valuable opportunity to change anything they don't like. Changes made at a later stage (such as when all use cases are covered) would take a longer time to absorb into the application, and can sometimes derail the project completely.

Project Transition and Release

At the end of the last iteration, the project will be in alpha stage, which means that all of the main use cases are implemented. The alpha build of the software is the build delivered to the software testers, usually internal to the organization/community developing the software. Usually, no end users see this phase. Alpha stage software is never completely bug free, but functionally covers all use cases.

Once the alpha testing is over, the project moves to the beta phase, which means that external users/end users (outside the company or organization that developed the software) can now start checking the system and using it.

A beta version is the first version released outside of the organization or community that developed the software, for the purpose of evaluation or real-world testing. Beta level software generally includes all of the features, but may also include known issues and bugs of a less serious variety. Once the beta phase is over and all major bugs have been fixed, the project is in an RTM (Release To Manufacture) stage, or in the Gold Edition.

The following is a summary table showing all of the important project phases:

Project Stages

Project Pitfalls

1. Initiation: Understanding project needs from a very high-level perspective and conducting a small feasibility study

A poor feasibility study can hinder or block project progress later on; it is very important to see what really can be achieved and what cannot, given the current technological offerings

2(a) Planning: Understand the project needs comprehensively, develop business use cases, detailed project plan, high-level architecture, class diagrams, data model, sequence diagrams, prototype

Detailed planning and project management is the key here; without a well laid out plan the project is doomed to fail. Wrong estimates or an improper choice of architecture can sound the death knell for the project's progress

2(b) Development: Work iteratively on selected use cases, QA process follows

Lack of unit tests, deviations in architecture, patching and short circuiting code to avoid missing deadlines

3. Transition: Beta testing, release docs, deployment instructions, bug fixing

Without proper usability and integration testing, success is not possible

4. Support: Provide support after the Gold/RTM release

Good support is very crucial

 

Tiers and Layers


There is a misunderstanding that tier and layers are two different names for the same entity. The concept of tier and layers came into being with the need for identifying and segregating different parts of an application into separate connected components. This separation can be at two levels:

  • Physical Separation

  • Logical Separation

Physical Separation

In a tier-based architecture, we separate code physically into different assemblies (or a set of assemblies). For example, we may have a single assembly for the web project, and another one for the class project having business code. If we want to deploy our application across multiple servers, spanning different geographical locations, then we need to use an n-tier architecture (which we will study in the coming chapters of this book).

Logical Separation

Separating into layers mean that we logically separate the code, but the entire application will be a part of a single physical assembly (or a set of assemblies depending on the compilation model). We may put the code files into separate folders, each having its own namespace for easier code management and readability, but we won't have a separate assembly for each different namespace or part of the code. Also, unlike physical separation, it will not be possible to deploy parts of the application in a distributed manner.

So a "tier" is a unit of deployment, while a "layer" is a logical separation of responsibility within the code. A layer becomes a tier if it can be physically separated from the layers consuming it. Alternatively, a tier is a layer which could be physically separated from the layers consuming it.

Note

If we are using the Visual Studio 2005 Website model, then we may have a set of assemblies for each page/folder, whereas if we use a Web Application Project (WAP) model (similar to the one used in VS 2003) we will have only a single assembly for the entire project.

Let's say we have a simple online guestbook system, which is a web-based application developed in ASP.NET. Here is a simple flowchart in a very basic form:

The user logs on to the website and visits the online guestbook, and clicks on the show all comments button. As a result, the system will show a list of comments to the user. For the same, the system sends a query to the Access DB, which in turn replies with a list of all the comments.

Now, one way to program this system is to create a simple web form with button, with the code to get the comments from the database placed inside the ASPX form (without using any code behind classes). The solution will compile into a single DLL. This inline coding approach will be discussed in the next chapter. Another method is to use code behind classes segregating the ASPX code and the C#/VB.NET code. We can introduce further loose coupling by separating the business logic and data access code into separate class library projects.

For a Windows-based project, also known as a thick-client, an n-tier project would have:

  • Windows forms (or Windows Presentation Foundations, WPF) as the Presentation layer

  • C# or VB.NET code handling the business logic as the Business Layer (BL)

  • Data access code as the Data Access Layer (DAL)

  • The physical database as the Data Layer (DL)

Data access layer (DAL) is a set of classes used to encapsulate data access methods like CRUD (Create Read Update and Delete) operations as well as any other methods accessing data from a data store (known as Data Layer). DAL's primary job is to communicate with the Data layer, which can be any RDBMS, set of XML files, text files, and so on. The DAL layer should act as a 'dumb layer' which is used directly by the BLL or any other service layer. The DAL layer should not contain any specific logic in its classes, and it should be used like a "utility" or "helper" class to fetch and store data to and from a data store.

Business logic layer (or the BLL) contains the business logic and set of operational rules particular to the application and talks to the data access layer (DAL) to:

  • fetch data on which it has to apply rules

  • save updated data after applying rules to it

  • perform operations and validate data

BLL usually presents the data to the higher Layers (like a GUI layer) after performing business rules on it. This layer may also include error handling, logging, and exception handling strategies, besides encapsulating all the business rules of the project.

UI layer contains the graphical display components and files like ASPX, ASCX, MasterPages, stylesheets and so on. The UI layer usually is the Website or Web Project in the Visual Studio solution for ASP.NET projects.

Most developers confuse the data access code (DAL) as the data layer (DL). The data and data the access layer are different. DAL is the actual code that we use in our applications to connect to a database, and the database itself is actually the data layer (DL).

Here is a sample diagram of how the different layers act:

Now in the diagram, if we separate each of the code layers into its own project and class library, then we will have a 4-tier project: Presentation tier, BL tier, DAL tier and DL tier (the physical database).

But with web based applications, we have a built-in 3-tier architecture by default. The presentation tier is the client-side browser (instead of Windows forms), the code (assuming you have web forms, BL, and DAL in one assembly) is the Application tier, and the physical database is the Data tier.

If we break up the web project so that we have the business logic and data access code in one assembly, and the web forms/ascx controls and so on in another, we will have a 4-tier architecture. We can go on like this by breaking each component out into its own tier and introducing further loose coupling. We will see more on how to introduce loose coupling in our projects in the later chapters of this book. For the rest of the book, we will be focusing only on thin-client based architectures, that is, web applications in ASP.NET.

We will now see what options we have for how we can break the code into different tier and layers in any Visual Studio web project, and thus define a few models. Here I am assuming that we are breaking the main application into tiers, and not focusing on the database and the presentation (browser) tiers.

Single Tier—Single Layer Model

We will have a single project in our solution, which will have UI, BL and DAL code under a single namespace.

ASP.NET Web Project compiling into a DLL in the /bin folder and under a single namespace: MyApp

No. of project files: 1

No of namespaces: 1

There is no separation of presentation, business logic, and data access code layers. Because we will have only one assembly (or set of assemblies) that cannot be distributed independently, this model would be single tier and single layer. We can use this model for very simple projects, on which only one developer is working and where we are sure there are no major scalability or maintainability issues. For example, a personal guestbook system, small 2 or 3 page web applications, or web sites with mostly static content.

Note

Actually if you make an application based on the above model, it will follow a 3-tier architecture 'overall', if we bring the database and the browser as the other tiers and count them inside the application. This is the reason why I mentioned that for the time being we should forget about the external tiers and focus on how to break the monolithic ASP.NET application into further tiers.

Single Tier—Two Layer Model

In this type of solution, we will still have only one web project, but we will separate the UI code into one namespace, and the BL and DAL into another namespace.

ASP.NET Web Project that has two folders:

  • Code: This folder will have class files containing business logic and data access code under a single namespace, say MyApp.Code

  • Web: This folder will have the user controls, ASPX pages, and other presentation-related code under the namespace, say MyApp.Web

Here, as the business logic and data access code are logically separated from the presentation code, we have two layers. However, as all code files would still be compiling into assemblies under a single project's /bin, we will have only one tier. We can use this model for projects that have little or no business logic but need to access a database for content.

Single Tier—Three Layer Model

In this model, we logically break BL and DAL in different namespaces, introducing cleaner code separation.

ASP.NET Web Project that has logical separation between presentation, business logic and data access code:

  • All presentation code will be under the MyApp.Web namespace (Layer 1).

  • Furthermore, the single project can have two folders:

    • Business (Layer 2): for business logic code, with namespace MyApp.Code.Business

    • DAL (Layer 3): for data access code, with namespace MyApp.Code.DAL

Note that it is not necessary to have different folders for the logical separation of code; using different namespaces in different code files will also work fine. We can use this model for a medium-to-large web application where we know that many users won't log in simultaneously. For handling a large number of users, the application needs to be scalable, and to do this we might need to separate BL and DAL code into their own physical assemblies.

Two Tier Model

Here we create two projects, one normal web project for UI code, and another class library project for the BL and DAL code. This will ensure that even if we change the BL or DAL code, we don't need to recompile the web project as we have separate physical assemblies. This setup is more scalable and maintainable than all previous options. Separating code into different assemblies will involve a slight performance hit, but that is negligible considering the flexibility and maintainability benefits we get by having two tiers.

The solution will have:

  • ASP.NET Web Project having GUI and presentation code (Tier 1)

  • A class library project having business logic and data access coding under a single namespace, MyApp.Code; no separate namespaces for business logic and data access code (Tier 2)

In this case, we still have the BL and DAL code under one namespace, but we can logically separate them further, as shown below.

Two Tier—Two Layer Model

We can further separate the BL and DAL code into their own separate namespaces and class files, so that different developers can work on BL and DAL simultaneously, under a multiteam set up.

The solution will have:

  • ASP.NET Web Project having Presentation Layer coding in ASPX and ASCX files, under the namespace, MyApp.Web (Tier 1)

  • A class library project having two folders (Tier 2):

    • Business: for business logic code, with namespace MyApp.Code.Business (Layer 1)

    • DAL: for data access code, with namespace MyApp.Code.DAL (Layer 2)

Three Tier Model

If the project is large, with a lot of complicated business logic, then it's more useful to separate the BL and DAL into in their own assemblies so that we can change the BL code without changing the DAL assembly. This makes our application more flexible and loosely-coupled as we can use a different DAL assembly for a different database with the same BL assembly.

The solution will have:

  • ASP.NET Web Project having Presentation Layer coding in ASPX and ASCX files, under namespace MyApp.Web (Tier 1)

  • A class library project having business logic code, with namespace, MyApp.Code.Business (Tier 2)

  • A class library project DAL for data access code, with namespace, MyApp.Code.DAL (Tier 3)

Note

Once again, if we also bring the Presentation and Database to be a part of the entire application here, the above 3-tier model would become a 5-tier model!

The above structures and layouts show some of the possible ways we can architect our solutions, and also illustrate the differences between layers and tiers. We can have more tiers (n-tier), and can customize our solution with a mix of tiers and layers, according to the project's needs. There is a common misconception among beginner developers that a 3-tier (or n-tier) architecture is the only best model, and many new developers try to blindly follow this model without even giving a second thought to their actual project's needs. As we go from one tier to n-tier, the code complexity increases, and it is better not to go for an n-tier architecture unless the application demands it. For small projects, we can keep things simple and easy.

In the coming chapters we will learn how, why, and which architecture to use (with sample projects), depending on the business needs.

 

Summary


In this chapter, we learnt the definitions of architecture and design, how they are different from each other and where they fit into our projects. It is very important to understand the different stages of a project life cycle so that we can manage our projects better and mitigate risks early. We also examined the difference between tiers and layers and the different ways we can structure our project using tiers and/or layers. In the coming chapters, we will go deeper into n-tier projects and, with sample applications and code, we will understand the advantages and disadvantages of each option.

About the Author

  • Vivek Thakur

    Vivek is passionate about architecting and developing applications based on Microsoft .NET platform using ASP.NET, C#, VB.NET, and MS AJAX. He has authored several technical articles on ASP.NET and has also been an All-Star-level contributor on ASP.NET forums. Vivek’s passion for ASP.NET has been formally recognized by the Most Valuable Professional (MVP) award given to him by Microsoft in April 2007, and again in 2008. He is also a Subject Matter Expert for Microsoft ASP.NET 3.5 Certification Exams. He is a leading contributor and moderator in the CodeAsp.Net forums. Vivek is currently working as the Managing Partner in Axero Solutions LLC, a US-based software product development and business consulting firm.

    Although his expertise lies in Microsoft's .NET platform, Vivek is also knowledgeable in J2EE and C/C++. He has a deep interest in programming, chaos theory and artificial intelligence, and is a strong advocate of chaos theory in software systems and management.

    Besides his love for software architecture and design, Vivek also focuses on project management skills and has substantial experience in managing small to medium sized projects. He has also conducted numerous training sessions and provided concept-based tutoring in different software firms across India.

    Vivek received his Bachelors degree in engineering from the Indian Institute of Technology (IIT), New Delhi, India.


    Contact Vivek Thakur

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial