Design-Pattern (Theory) PDF
Design-Pattern (Theory) PDF
Course Outlines
Course: CSE 6007
Course Title: Design and Development Open Multi-tier Application
Faculty: Prof.. S M Monzurur Rahman ([email protected])
Assessment:
Component Marks(%)
Attendance 5
Continuous Assessment - Class Test 10
Continuous Assessment - Project 15
Midterm 30
Final 40
Total 100
Reference Book
1. Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
2. Patterns of Enterprise Application Architecture, By Martin Fowler
3. WCF 4.0 Multi-tier Services Development with LINQ to Entities By Mike Liu
Lecture 1
Lecture 4
1
• Dependency Injection Pattern
Lecture 5
• The Facade Design Pattern
• The Template Design Pattern
• Model-View-Controller
Lecture 6
• Mid-Exam
Lecture 7
• Enterprise Pattern
• SOAP
• Open and Close Multi-tier
Lecture 8
• The Composite Design Pattern
• The Visitor Design Pattern
• The Proxy Design Pattern
Lecture 9
• SOA Design pattern
• SOA in .NET
• Web services
• SOAP
• WCF: Windows Communication Foundation
Lecture 10
• **** Class Test
• Implementing a Basic WCF Service
• Creating a client to consume the WCF service
Lecture 11
• MVC3-Rajor
Lecture 12
• Project Demonstration
• Review
Lecture 13
• Final Exam
2
United International University
Design Pattern
• Lets we have an old object and interface which takes old object
• After some time, interface has been changed and issue is how to handle the
change.
• Design pattern gives the solution to this problem using adaptor pattern.
• Lets you are designing a web site which has the following pages.
• There are a lot of interactions between pages and which makes the programming
complex. In that case a mediator design pattern provides a good solution.
2. Creational Patterns
• Creational design patterns are design patterns that deal with object creation
mechanisms, trying to create objects in a manner suitable to the situation.
• .Example:
Factory
Prototype
Singleton pattern
Builder pattern
3. Structural patterns
• Structural design patterns are design patterns that ease the design by identifying a
simple way to realize relationships between entities.
• Example:
Adapter
4. Behavioral patterns
• Behavioral design patterns are design patterns that identify common communication
patterns between objects and realize these patterns. By doing so, these patterns
increase flexibility in carrying out this communication.
• .Example:
Chain of responsibility
Mediator
Visitor
Riehle and Zullighoven make similar distinctions, but seem to partition the different
kinds of patterns among analysis, design, and implementation. They define the terms
conceptual patterns, design patterns, and programming patterns as follows:
1. Conceptual Patterns
A conceptual pattern is a pattern whose form is described by means of terms and
concepts from an application domain.
2. Design Patterns
A design pattern is a pattern whose form is described by means of software
design constructs, for example objects, classes, inheritance, aggregation and use-
relationship.
3. Programming Patterns
A programming pattern is a pattern whose form is described by means of
programming language constructs
Qualities of a Pattern
A well written pattern should exhibit several desirable qualities and they are:
• Equilibrium
Each pattern must realize some kind of balance among its forces and constraints.
This may be due to one or more invariants or heuristics that are used to minimize
conflict within the solution space. The invariants often typify an underlying
problem solving principle or philosophy for the particular domain, and provide a
rationale for each step/rule in the pattern.
• Model: Encapsulates core data and logic. Model is often related with the business
logic of the application. It knows all the data that needs to be displayed. It is
always isolated from the User Interface (UI) and the way data needs to be
displayed.
• View: It is the UI part of the application. It uses read-only methods of the model
and queries data to display them to the end users. It may be a window GUI or a
• Design patterns are less specialized than frameworks. Frameworks always have a
particular application domain. In constrast, design patterns can be used in nearly
any kind of application. While more specialized design patterns are certainly
possible, even these wouldn't dictate an application architecture.
Pattern Catalogs
Design Anti-Patterns
Anti-patterns are useful for the same reason that patterns are useful, anti-patterns provide
a way to document and spot bad design and to (hopefully) provide remedies. It's a good
idea to know about anti-patterns so that your code doesn't use any, so that they can be
recognised the next time code is maintained and so that their impact can be appreciated at
the next code review. They should be identified as early as possible in the software life-
cycle as it's easier to re-design code than unpick its implementation.
• Some have criticized design patterns, pointing out that they don't provide reuse
nor do they differ significantly from other abstractions. The purpose of design
patterns is to capture commonality at the design level. Patterns can be reused once
implemented; however, as soon as the design is implemented, it has become
specific to the particular language and environment in which it will be deployed.
The implementation of a persistence layer pattern would be radically different on
a handheld device compared to one for a server environment. The pattern for
these two environments will have some elements in common and this
commonality can be reused at the design level. The pattern can then be
decomposed and refined, one for each environment, and the individual patterns
can be reused and implemented. The two patterns and the common part can then
be made publically available from the Portland Pattern Repository. Patterns and
their implementations compliment each other, however, one isn't a replacement
for the other and patterns are design-level entities.
• I've often thought design patterns were clever, but a toy when compared to reality.
I think in real systems we use thousands of different patterns and morph them and
hybridize them as we go. Building real software out of a few toy patterns is like
building a Lamborghini out of lego. I think what we really need then are ways to
dynamically discover the patterns we care about at a given moment, I think of it
as "data mining the code".
1. Strategy Pattern
• Behavioral Pattern
• Encapsulates an algorithm inside a class.
• Defines a family of interchangeable encapsulated algorithms that receives the
same input type and provides the same output type in different manners that can
be determined in run-time.
• Carry() is defined in base class and run() is overridden in the derived classes
as required.
• Suddenly you recognise that, as this is for worldwide cars, there are some
cars, which go for race.
• Only change required is to add a race() method in the base class so some
cars can go for the race.
• User starts the Demo with the above change , Some thing went horribly wrong:
• But consider about ToyCar they do not race nor they do not Carry.
- Race() to do nothing
• As long as new type of car's come, the more modification is required in base
class and derived classes (need to override code). This is the problem to
maintain the code. To solve this problem Strategy Design Patterns comes as a
solution.
Solution
• In order to solve the above problem we separate car class than car behavior i.e.
Separate the algorithm code from the class code.
• We use "Program to an interface, not an implementation” The interfaces can
be designed as follows:
public Car()
{
}
Car Class
Jeep Class
ToyCar Class
RentalCar Class
• When new thing comes we change outside of the class i.e. when new algorithm
comes (behavior), we need to implement that new behavior in a new interface not
in class level and that behavior can set dynamically using set method.
• Any class change their behavior outside of the class e.g.
The Solution
The solution to basic problems is to implement a Strategy pattern. Consider the following
architecture:
Whenever we create classes that are composed of behavioral actions, we call these
compositions. Classes such as Dog, Cat, and AllyCat are compositions of behaviors and
gain their behavior through composition, not inheritance. Inheritance (like the previous
architecture) can lead to unintended consequences when fiddling with the superclass and
is more prone to breaking existing code.
• Structural Pattern
• Also known as wrapper.
• The Decorator Pattern is used for adding additional functionality to a particular
object as opposed to a class of objects. It is easy to add functionality to an entire
class of objects by subclassing an object, but it is impossible to extend a single
object this way. With the Decorator Pattern, you can add functionality to a single
object and leave others like it unmodified.
Example
• Consider you have a following computer class with a description method:
• In this way if you need again and again modification to your class then it is
difficult to manage since you need to touch the actual class again and again.
• To solve the above problem, Decorator pattern comes as a rescue. The design
pattern suggests you to create a wrapper class and place the instance of the class
to the wrapper class and wrapper class allow you to add new functionality i.e.
changing the description method. In this way you do not need to modify the
computer class.
In order to solve the above problem you can design the classes as follows:
• Here Monitor description method calls Disk description method and Disk
description method in turn call Computer method.
• How to code the above Decorator design pattern.
o When Disk come to the table then we can design Disk decorator as
follows:
o Similarly if you need another Decorator e.g. Monitor then you can design
that as follows. Do not forget that in the constructor you can pass CD
object for Computer c parameter since CD is itself a Computer type.
o The output will be – You are getting a computer and a disk and a monitor
and a CD and a CD
• The idea behind a decorator pattern is that you can customize your objects by
adding multiple wrappers over and over again even the same wrapper twice or
more times.
• So using Decorator pattern you can customize your object each time using a
wrapper without modifying your codes.
Decorator Advantages
Decorator Disadvantages
o objects differ only in the way they are interconnected, not in their class or
o these systems are easy to customise by those who understand them, they
Example
• You need a factory pattern to make the better solution for the above problem.
• In the Factory Pattern, a factory method defines what functions must be available
in the non-abstract or concrete factory. These functions must be able to create
objects that are extensions of a specific class. Which exact subclass is created will
depend on the value of a parameter passed to the function.
• The first version of the Factory class is as follows, The CreateConnection() is
called creational method. We need to make the Connection abstract class in order
to support CreateConnection() method of Factory Design Pattern
• Now have a look how Factory Design Pattern provides the solution.
.
• The intent of this pattern is to provide the way to implement data-types as
immutable classes so that their instances can be handled like built-in values. It is
architectural pattern.
• A value object is a small simple object, like a money or date range, whose
equality is not based on identity.
• You can have multiple copies of an object that represents the date 16 Jan 1998.
Any of these copies will be equal to each other. For a small object such as this, it
is often easier to create new ones and move them around rather than rely on a
single object to represent the date.
• A reference object is an object whose equality is based on its identity. Reference
objects are big in size e.g. customer, order etc.
• A general heuristic is that value objects should be entirely immutable. If you want
to change a value object you should replace the object with a new one and not be
Example
//Nails.php
class Nails
{
private $_quantity;
//testtoolBox.php
You probably already noticed that problem is that we are both using the same Nails
object. In this case the problem may be easy to spot and avoid, but as your application
becomes bigger, preventing this type of mishap can save you a huge headache. Another
mayor benefit of using Value Objects is they enable you to encapsulate type-specific
operations. Martin Fowler does a great job at demonstrating this with his Money pattern,
which encapsulates the handling of rounding currency.
Lab Exercise
• Given the following code, complete the code for a BoatFactory class so it can be
used to create big and small boat objects:
if (s.equals(“big”))
return new CruiseShip( );
Background
You are working as part of team which is tasked with designing a security package. The
package is to be used as part of a university system to control access to system services.
The access control policy is based on the role a particular user plays. There are three
roles: Lecturer, Student, and Administrator. Table 1 presents the access rights for each role.
A member of your team has proposed an initial design which is shown in Figure 1. With
this design, the abstract superclass Operator is intended to be sub-classed with concrete
classes representing particular roles. The Operator class provides a default implementation
of the isAuthorizedTo() method which simply returns false. The concrete subclasses
override this method and depending on the String argument value, return true or false
indicating whether instances of the class have permission to do what is described by the
String argument. For example, calling isAuthorisedTo() with the argument “install software”
on an Administrator instance would return true; calling the method with the same argument
on a Student or Lecturer object would return false.
You raise this problem with your team. Another member responds and points out that the
problem is easily solved by creating additional subclasses to cater for all the
combinations of roles. Specifically, this means defining 3 additional subclasses:
LecturerAndStudent, LecturerAndAdministrator, and StudentAndAdministrator. To cater for an
individual playing all three roles, a further subclass LecturerAndStudentAndAdministrator
would be required.
You think about this suggestion for a moment and it doesn’t take you long to see that it’s
unattractive. First, it would be error-prone to maintain since if the access rights change
for one role, you will have to edit the source files for four classes. For example, adding a
new privilege for students, such as allowing them access to file sharing services (likely to
be used for sharing music files!) would involve editing the Student, LecturerAndStudent,
You air your thoughts to your team members. They are impressed by your analysis but
look to you for a solution. You quickly consider each of the design patterns you know
about, but none of them seem to tackle this seemingly generic problem. A brief search on
the Internet using Google with the terms “subclass explosion” and “design pattern”
returns a host of links which have in common the Decorator design pattern. The
Decorator pattern looks promising …
The task
Investigate the Decorator design pattern and apply it to develop an alternative design to
the access control problem. Your design should address the problems inherent in the
original design. The exam question will assess your understanding and application of the
pattern and thus requires that you do the necessary preparatory work prior to the exam.
Week 3: The Observer Design Pattern, The Singleton Design Pattern, The Adapter
Design Pattern
• Behavioral Pattern – The problem deals with “How can you alert (potentially)
many objects when a certain object’s state changes? Is there a scheme that’s
dynamic—one that allows interconnections to come and go as a script executes?
• The observer pattern is a software design pattern in which an object (called the
subject object) maintains a list of its dependents (called observers) and notifies
them automatically of any state changes, usually by calling one of their methods.
It is mainly used to implement distributed event handling systems.
Example
• The Observer pattern defines an one-to-many dependency between a subject
object and any number of observer objects so that when the subject object
changes state, all its observer objects are notified and updated automatically.
• The Observer pattern essentially allows an unlimited number of objects to
observe or listen to events in the observed object (or subject) by registering
themselves. After observers are registered to an event, the subject will notify
them when the event is fired.
• The subject handles this by storing an observer collection and iterating
through it when the event occurs in order to notify each observer.
Subject
Knows it observers
Has any number of observer
Provides an interface to attach and detaching observer object at run time
Observer
ConcreteSubject
ConcreteObserver
• Structural Pattern
• Adapters are used to enable objects with different interfaces to communicate
with each other.
• Convert the interface of a class into another interface clients expect. It is
useful when we upgrade system
• Lets you have an interface class which fits in with a back end class.
• After some time, management upgrades the system and now the back end object
takes Acme object instead of Ace object.
• You can see from the above figure that after upgrade Ace object is not able to
plug into Backend object any more.
• So what do you do - you put an adaptor class in between interface and back end.
The adaptor helps interface to communicate with back end class i.e. adaptor
adapts one object to another receptacle object. This strategy is called adaptor
design pattern.
• We need an adaptor because Acme object which fits in with back end and Acme’s
object’s setFirstName and setLastName is supposed to be setName. Similarly,
Acme’s object’s getFirstName and getLastName is supposed to be getName. So,
we need an adaptor or converter to convert Ace object to Acme Object.
• In order to code the above we first code AceInterface and AceClassas follows.
AceClass is based on AceInterface.
AcmeInterface.
construct of such class is as follows. Not that it accepts AceClass object in the
• Creational Pattern- Ensure a class only has one instance, and provide a global
point of access to it.
• Sometimes we want just a single instance of a class to exist in the system. For
example, we want just one window manager. And we want to ensure that
additional instances of the class cannot be created.
Example
• Normally when you have a class and you create many instances of it then you get
many objects e.g.,
• But in the case of singleton design pattern we get one instantiated object for
many calls of getInstance() method instead of new e.g.,
return singleObject;
}
database = Database.getInstance("products");
database = Database.getInstance("employees");
• What if two threads concurrently invoke the instance() method? Any problems?
• When more than one threads pass through the get instance method of the single
pattern Database class then both thread see singleObject==null and both of them
create Database object and which is not desirable.
private DatabaseSynchronized(String n)
{
name = n;
record = 0;
}
return singleObject;
}
public TestSingletonSynchronized()
{
DatabaseSynchronized database;
database = DatabaseSynchronized.getInstance("products");
The code below shows a user list that sends out a message when users are
added. This list is watched by a logging observer that puts out a message when a
user is added. You are supposed to run this program in the lab and understand
observer patter (Do it in C#).
Observer.php
<?php
interface IObserver {
function onChanged($sender, $args);
}
interface IObservable {
function addObserver($observer);
}
$ul->addCustomer( "Jack" );
$ul->addCustomer( "John" );
?>
This code defines four elements: two interfaces and two classes. The IObservable
interface defines an object that can be observed, and the UserList implements that
IObserver list defines what it takes to
interface to register itself as observable. The
be an observer, and the UserListLogger implements that IObserver interface.
The observable user list and the user list event logger
If you run this on the command line, you see this output:
'Jack' notifies UserListLogger
'Jack' notifies AuditLogger
'John' notifies UserListLogger
'John' notifies AuditLogger
Home Work - 2
Imagine you are designing a virtual world in which the following types of objects needed
to be inter-related: lamps, switches, outlets, and rooms. Assume the following semantics
for those objects:
Q1. If you used the Observer pattern to relate those objects, please describe everything
that would happen (according to that pattern) when a lamp was plugged into a socket.
Q2. If you used the Observer pattern to relate those objects, please describe everything
that would happen (according to that pattern) when a switch was flipped from off to on.
Home Work - 3
What design pattern should you think of when you want to reuse an object but it has
the wrong interface? Give an example to support your answer.
Home Work - 4
“I am limited to how many database connections I can have. What design pattern helps
me limit the number of objects I can create?”
• You could use Singleton pattern where we only want one instance of the class.
After making the constructor private, you get one version of the class. – Give
example code to support the above.
• You can use the Singleton pattern to limit the number to X as well.- Give example
code to support the above.
• Behavioral Pattern – It’s generally considered “good form” to avoid the use of
global variables, objects are usually passed from one code segment to another as
parameters.
• The problem with passing instances globally is that objects sometimes end up as
“tramp data,” passed into one function only to be passed again to another function
which truly needs the object. To make writing, reading, and consuming code
simpler, it’s best to minimize the number of different objects and consolidate
knowledge of how to get to a numerous of other widely-used objects into a single,
well-known object.
• How can you get references to objects through a single, well-known, object? The
Registry design pattern is like an “object phone book”—a directory—that stores
and retrieves references to objects.
• The Registry pattern can be useful, for example, if, for the bulk of your
application, you use the same database connection, but need to connect to an
alternate database to perform a small set of tasks every now and then. If your DB
class is implemented as a Singleton, this is impossible (unless you implement two
separate classes, that is)—but a Registry makes it very easy:
class Registry {
private static $_register;
public static function add(&$item, $name = null)
{
if (is_object($item) && is_null($name)) {
$name = get_class($item);
}
elseif (is_null($name)) {
$msg = "You must provide a name for non-objects";
throw new Exception($msg);
}
$name = strtolower($name);
self::$_register[$name] = $item;
}
Example
public interface ICar {
public float getSpeed();
public void setPedalPressure(final float PEDAL_PRESSURE);
}
In the above example, using the ICar interface, an engine instance is created by using the
IEngine interface in order to perform operations on the car. Hence, it is considered
highly-coupled, because it couples a car directly with a particular engine implementation.
In the example above, the CarFactory class assembles a car and an engine together by
injecting a particular engine implementation into a car. This moves the dependency
management from the DefaultCarImpl class into the CarFactory class. As a
consequence, if the DefaultCarImpl needed to be assembled with a different
DefaultEngineImpl implementation, the DefaultCarImpl code would not be changed.
<service-point id="CarBuilderService">
<invoke-factory>
<construct class="Car">
<service>DefaultCarImpl</service>
<service>DefaultEngineImpl</service>
</construct>
</invoke-factory>
</service-point>
Lab Practice
The code given in HomeWork4.rar has a registry design pattern
demonstration. You are supposed to run this program in C# or Java twice in the lab
to understand registry pattern. After first run there will be an object will be created
in object directory. And after second run the object will be retrieved from the file.
Home WOrk
The code given in HomeWork4.rar has a dependency injection design pattern
demonstration. You are supposed to run program yesTest.php and noTest.php to
understand how to use dependency injection pattern.
• Structural Pattern
• Provide a unified interface to a set of interfaces in a subsystem.
• Façade defines a higher-level interface that makes the subsystem easier to
use.
• It wraps a complicated subsystem with a simpler interface.
How it works
• Lets we have a difficult interface in one area of code and the other code only takes
simple interface.
• Adapter pattern
o is used for providing an interface for incompatible classes.i.e Adapter
provides a different interface to its subjects.
o Adapter changes an object's interface and make it usable by another
objects .i.e the Adapter pattern changes the interface of one or more
classes into one interface that a client is expecting.
• Facade provides
o the simpler interface to the client.let us assume u have number of sub
systems and each one has exposed some interfaces.but all interfaces are
not required by the client.so what we do make one interface top of the
subsystems i.e facade.
o In Facade we wraps multiple objects.
o Facade is the simpler interface of the complex sub systems
As told Façade is seen as the simpler interface of the complex sub systems and the UML
is as follows.
Example
class program
{
internal class Book
{
internal string FindBook()
{
return "Subsystem for Book, Method FindBook\n";
}
internal string Returned()
{
return "Subsystem for Book, Method Returned\n";
}
}
internal class Shelf
{
internal string AssignBook()
{
return "Subsystem for Shelf, Method AssignBook\n";
}
Output
Motivation
• Behavioral Pattern
• It is used to set up the outline or skeleton of an algorithm (a sequence of
actions), leaving the details to specific implementations later. This way,
subclasses can override parts of the algorithm without changing its overall
structure.
• The Template Design Pattern is perhaps one of the most widely used and
useful design pattern.
Example
• In Template Design Pattern you will have a base class and that will have a
template method which is go in the following example. The template method will
have series of methods which make the outline of an algorithm. The inheriting
classes may override the methods which are in the template method. The template
method is final one.
• Next two inheriting classes. Here overriding methods are provided for specific
robot building.
public AutomotiveRobot(String n)
{
name = n;
}
public CookieRobot(String n)
{
name = n;
}
System.out.println(automotiveRobot.getName() + ":");
automotiveRobot.go();
System.out.println();
System.out.println(cookieRobot.getName() + ":");
cookieRobot.go();
}
}
• You can provide conditional methods in the template method of the base class so
that algorithm does not need to take all the methods. Example is given as follows.
Here testOK() method controls whether we need or not test() method.
public CookieHookRobot(String n)
{
name = n;
}
How It Works
The MVC abstraction can be graphically represented as follows. Events typically cause a
controller to change a model, or view, or both. Whenever a controller changes a model’s
data or properties, all dependent views are automatically updated. Similarly, whenever a
controller changes a view, for example, by revealing areas that were previously hidden,
the view gets data from the underlying model to refresh itself.
Example
We explain the MVC pattern with the help of a simple spinner component which
consists of a text field and two arrow buttons that can be used to increment or decrement
a numeric value shown in the text field.
The trampolines that initially receive the action events fired by the arrow buttons, are also
controllers — However, instead of modifying the spinner’s model directly, they delegate
the task to a separate controller (action listener).
In MVP, the Presenter contains the UI business logic for the View. All invocations from
the View delegate directly to Presenter. The Presenter is also decoupled directly from the
View and talks to it through an interface. This is to allow mocking of the View in a unit
test. One common attribute of MVP is that there has to be a lot of two-way dispatching.
For example, when someone clicks the "Save" button, the event handler delegates to the
Presenter's "OnSave" method. Once the save is completed, the Presenter will then call
back the View through its interface so that the View can display that the save has
completed. The key differences between the patterns:
MVP Pattern
• View is more loosely coupled to the model. The presenter is responsible for
binding the model to the view.
• Easier to unit test because interaction with the view is through an interface
HW-2
HW-3
ABC Company stored data about employees (e.g., name, age, address) in two
areas - one is in an excel file (abc.xls) and the other is in a text file (abc.txt). You are
hired to write a program to process ABC’s employees. Here process means – reading data
from file and printing names of each file. Write a program (in java or C#) using template
design pattern for ABC to process employees’ data.
Hints: You need one abstract class where process template method exists and two sub
classes – one for text file processing and the other is excel file processing. The process
template method shall contain two steps – readData() and printData().
• Design patterns which are used mostly for Enterprise Application Architecture are
known as Enterprise Design Pattern.
• Enterprise Design patterns are introduced in Core J2EE Patterns, the patterns deal with
presentation, and application logic.
Base Patterns
Command: - An object encapsulates everything needed to execute a method in another
object
Registry: This pattern is useful for making data available to all classes in a process.
Through careful use of serialization, it can also be used to store information across a
session or even across instances of an application.
Front Controller: A controller that handles all requests for a Web site.
Application Controller: A centralized point for handling screen navigation and the flow
of an application
Page Controller: An object that handles a request for a specific page or action on a Web
site. Lighter weight but less flexible than Front Controller, Page Controller addresses
the same need. Use this pattern to manage requests and handle view logic if you want
fast results and your system is unlikely to grow substantially in complexity.
Transaction Script When you want to get things done fast, with minimal up-front
planning, fall back on procedural library code for your application logic. This pattern
does not scale well. This pattern Organizes business logic by procedures where each
procedure handles a single request from the presentation.
Domain Model: An object model of the domain that incorporates both behavior and data.
Example
• Let we have two set of objects i.e. command issuer and receiver as follows.
Crisis centre issues command to the server to keep it up. There are set
Servers are called receivers and Crisis centre is called invoker here. Coding starts
with the interface of receiver as follows.
public ShutDownCommand(Receiver r)
{
receiver = r;
}
public RunDiagnosticsCommand(Receiver r)
{
receiver = r;
}
public RebootCommand(Receiver r)
At last step we create invoker to test our command design pattern. Invoker loads
commands.
public Invoker()
{
position = -1;
}
public TestCommands()
{
Invoker invoker = new Invoker();
invoker.setCommand(shutDownAsia);
invoker.run();
invoker.setCommand(rebootAsia);
invoker.run();
invoker.undo();
invoker.undo();
}
}
Command(Command)
ConcreteCommand (ServerCommand)
Client (CommandApp)
Invoker (User)
Receiver (Server)
• knows how to perform the operations associated with carrying out the request.
Multi-tier Computing
• The J2EE platform is an implementation of the concept of Multi-tie computing.
• Multi-tier is a distributed software architecture in which systems are divided into
autonomous processes, where a client sends requests to a server and that server
sends responses as an answer to the request to that client.
• Multi-tier is a concept that will distribute the autonomous processes over clients
and servers, based on the suitability for the task of those clients and servers.
Example
2) Presentation logic
• The presentation logic layer is responsible for what is displayed to the user. It
defines which screens are displayed, when they are displayed, which
navigation paths exist between screens, which fields to display etc.. The
presentation logic layer is application dependent.
3) Application logic
• The application logic layer contains the actual application logic. This is the layer
where the application functionality is defined. The application logic layer is
application dependent.
• In practice, this layer is the least recognizable of all layers. This layer is typically
spread over all other layers whith most of its logic ending up in the presentation
logic layer.
• The business logic layer contains the business rules of an organization. All the
business rules should be shared between all the applications of the
organization. This will ensure that changes in business rules will propagate
through all the organization's applications. This layer is not application
dependent but organization dependent.
5) Database logic
• The database logic layer contains the data dictionary of the application. It
describes the tables, their columns, data types, primary and secondary keys.
6) Database manager
o This layer is responsible for the actual storage of data. This layer can be
application dependent but most of the time it is not. Most of the time the
database manager is a commercial off-the-shelve application, which is able to
manage many applications. For very simple applications the database
manager and the operating file system are the same (persistence).
o In practice, the database logic layer and the database manager layer are
almost always one layer. Most database managers generate the physical
storage facilities of the data on the basis of a database logic written in SQL.
Whenever we speak of "database" in this tutorial we mean the integrated
database logic / database manager layer.
o A physical layer is called a tier. A tier is for all practical purposes and
considerations the same as a process.
o When creating a distributed Multi-tier system there are several strategies on
can use to divide the logical layers over processes, ranging from all layers on
their own process to all layers in one process (which of course is not
distributed anymore). One can even choose to implement one layer in
multiple processes.
o In the past, several strategies were implemented with different degrees of
success. In the next paragraphs several tier-models are introduced. Note that
1-Tier
Figure: 1-tier
2-Tier
Figure: n-tier
o As a result of having the source code organized into multiple tiers, debugging
and maintaining your application as a whole will be easier. The organization
will allow for you as a developer (or any other developers you might be
working with) to easily locate specific sections where an exception is
occurring or where a change needs to be implemented.
• SOAP allows the creation of Web services, which are standardized computing
resources that take input from across a network and respond in an advertised way.
• SOAP is a specification for extensible markup language (XML) messages that
travel between endpoints. It is a way for software programs to invoke other
software programs (or parts of them) over the network.
• SOAP is a lightweight protocol for exchange of information between tiers of an
enterprise application.
• WSDL is an XML format for describing SOAP opeartions. In SOAP a client is a
script that uses a Web Service and Server is defined as a script that provides a
Web Service.
Element Defines
<types> The data types used by the web service
<message> The messages used by the web service
<portType> The operations performed by the web service
<binding> The communication protocols used by the web service
<definitions>
<types>
definition of types........
</types>
<message>
definition of a message....
</message>
<portType>
definition of a port.......
</portType>
<binding>
definition of a binding....
</binding>
</definitions>
A WSDL document can also contain other elements, like extension elements, and a
service element that makes it possible to group together the definitions of several web
services in one single WSDL document.
<message name="getTermRequest">
<part name="term" type="xs:string"/>
</message>
<message name="getTermResponse">
<part name="value" type="xs:string"/>
</message>
<portType name="glossaryTerms">
<operation name="getTerm">
<input message="getTermRequest"/>
<output message="getTermResponse"/>
</operation>
</portType>
In this example the <portType> element defines "glossaryTerms" as the name of a port, and
"getTerm" as the name of an operation.
The "getTerm" operation has an input message called "getTermRequest" and an output message
called "getTermResponse".
The <message> elements define the parts of each message and the associated data types.
Operation Types
The request-response type is the most common operation type, but WSDL defines four types:
Type Definition
One-way The operation can receive a message but will not return a
response
Request-response The operation can receive a request and will return a response
Solicit-response The operation can send a request and will wait for a response
Notification The operation can send a message but will not wait for a
response
<message name="getTermRequest">
<part name="term" type="xs:string"/>
</message>
<message name="getTermResponse">
<part name="value" type="xs:string"/>
</message>
<portType name="glossaryTerms">
<operation name="getTerm">
<input message="getTermRequest"/>
<output message="getTermResponse"/>
</operation>
</portType>
In the example above, the port "glossaryTerms" defines a request-response operation called
"getTerm".
The "getTerm" operation requires an input message called "getTermRequest" with a parameter
called "term", and will return an output message called "getTermResponse" with a parameter
called "value".
WSDL Bindings
WSDL bindings defines the message format and protocol details for a web service.
Binding to SOAP
A request-response operation example:
<message name="getTermRequest">
<part name="term" type="xs:string"/>
</message>
<message name="getTermResponse">
<part name="value" type="xs:string"/>
</message>
<portType name="glossaryTerms">
<operation name="getTerm">
<input message="getTermRequest"/>
<output message="getTermResponse"/>
</operation>
</portType>
The name attribute (you can use any name you want) defines the name of the binding, and the
type attribute points to the port for the binding, in this case the "glossaryTerms" port.
The style attribute can be "rpc" or "document". In this case we use document. The transport
attribute defines the SOAP protocol to use. In this case we use HTTP.
The operation element defines each operation that the port exposes.
For each operation the corresponding SOAP action has to be defined. You must also specify how
the input and output are encoded. In this case we use "literal".
Lab Work
Background
Connectivity between applications is very important. Connectivity in any case is very
important for that matter but it specially is very important between applications.
Connecting web application used to be a big challenge before the advent of technologies
like SOAP (Simple Object Access Protocol). The reason it was so difficult was, there
were so many technologies people were working in. The applications were hosted on
different types of servers, etc. But these things should not be a barrier to facilitate the
communication between applications. The only requirement was to have some standards
to follow and standard ways of doing things so that the applications become capable of
communicating with other applications irrespective of the technologies used.
We have SOAP and XML to give us connectivity between applications. Does it mean
that I have to write XML and SOAP specific things myself to facilitate this
communications? I could do that but that will be very time consuming and sometimes
error prone too.
Where does Web Services come in picture? Well, Web services is the mechanism that
ASP.NET framework provides to make it easy for us to write code to facilitate
connectivity between applications. As ASP.NET developer, If I need an application that
will be used by many other applications then I can simply decide to write a web service
for it and ASP.NET framework will take care of doing the low level SOAP and XML
work for us.
The other side of the coin is, if our ASP.NET application wants to use a web service, i.e.,
an application that is providing me SOAP based interface for communication. So what
we are going to do now is write a small Web service to see how we can have our
application communication-ready for other applications and secondly, we will try to
consume a webservice to understand how we can use other applications from our
application.
We have a very basic web service implemented which can let the user have some basic
arithmetic operations. Now to create the WebService binary, we will have to use the
following command on Visual Studio Command Prompt.
This will create a DLL file for our web service. This DLL file can be used by any client
by using the SOAP protocol. If we need to test our web service for how it works over the
SOAP protocol, we can view the service.asmx file in the browser and see what functions
our web service is exposing (After running web service from VS-2010). We can even test these
methods here and see the XML file that contains the service description.
Consuming a WebService
The HTTP-Post method can be used by calling .asmx file directly from client. We can
directly use the method name and the parameter names will be taken from our input fields
on form.
When this form get submitted, the web service's method will be called. The second
method where we can use the XMLHttp over SOAP to access the webservice is used
when we want to use the web service using full capability of SOAP.
The third way of using the web service is by generating a Proxy class for the web
service and then using that proxy class. This method is, to me, more type safe and
less error prone as once we have the proxy class generated, it can take care of SOAP
messages, serialization and ensure that all the problems can be handled at compile
time instead of runtime.
To use this service, we need to do "Add Web reference" and add the webservice
reference. Alternatively I can also use WSDL.exe, a command line tool, to generate
the proxy classes and use them. "Add web Reference" is also using the same
WSDL.exe to generate the proxy classes.
Home Work
The ultimate remote control is capable of executing commands to run a set of household
instruments as shown below.
The remote control is used as an invoker which executes the set commands as follows.
How it works
• Composite Design Pattern works for hierarchies. Lets consider the following
hierarchy for which we are going to design composite design pattern. Lets you
want to iterate over the organization and print out the name of VPs. Using
composite design pattern you need to develop the same strategy for iteration for
Division, VPs and root VP.
• The iterator of VP is given below. Note that only single object exists in VP object
so iterator is very simple here.
public VPIterator(VP v)
{
vp = v;
}
• Next coding the branches i.e. division. Division contains leaves. The class is
given below.
public Division(String n)
{
name = n;
}
while (iterator.hasNext()){
Corporate c = (Corporate) iterator.next();
c.print();
}
}
}
public DivisionIterator(Corporate[] c)
{
corporate = c;
}
public Corporation()
{
}
while (iterator.hasNext()){
Corporate c = (Corporate) iterator.next();
c.print();
}
}
}
public TestCorporation()
{
// Construct the organization
corporation = new Corporation();
sales.add(western);
corporation.add(rnd);
corporation.add(sales);
corporation.add(vp);
Component
• is the abstraction for all components, including composite ones
• declares the interface for objects in the composition
Leaf
• represents leaf objects in the composition
• implements all Component methods
How it works
• Consider the corporation structure (object structure) that we have used in iterator
design pattern.
UML
• Visitor (Visitor)
o declares a Visit operation for each class of ConcreteElement in the object
structure.
• ConcreteVisitor (IncomeVisitor, VacationVisitor)
o implements each operation declared by Visitor. Each operation implements a
fragment of the algorithm defined for the corresponding class or object in the
structure. ConcreteVisitor provides the context for the algorithm and stores its
//Visitor
interface IVisitor
{
void Visit(Element element);
}
// Concrete Visitors
class IncomeVisitor : IVisitor
{
public void Visit(Element element)
{
Employee employee = element as Employee;
// Element
// Constructor
public Employee(string name, double income,
int vacationDays)
{
this._name = name;
this._income = income;
this._vacationDays = vacationDays;
}
//Object Structure
class Employees
{
private List<Employee> _employees = new List<Employee>();
//Client
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
// Setup employee collection
Employees e = new Employees();
e.Attach(new Clerk());
e.Attach(new Director());
e.Attach(new President());
Output
Home Work
Let’s assume we are working on an application that calculates the cost associated with
different teams in a company. The organizational chart of this company is illustrated in
the figure below. At the top of the org chart is the Chief Executive Officer (CEO) who
has 2 Vice Presidents reporting to him. The VP of Technology has 2 developers and since
the company is still in the growth mode, the VP of Sales does not have anyone reporting
to him.
The application you should develop in C# or Java using composite design pattern and
should calculate the “cost” incurred in different teams. The cost is calculated by the
summation of the salary of the department head and the salaries of employees that report
Hints:
The Composite Pattern is perfect for this application as we would like to treat the object
(say Developer1) and the collection of objects (say VP-Technology) in the same manner.
Physical Model
Model – Class Diagram
Service
• Login
• Logoff
• GetCustomers
• GetOrders
• In this example, a book publisher can receive book orders from both a single,
individual reader as well as large quantity book orders from large national
book resellers. Orders are received by the Order System application, which
collects and processes the orders.
• Internally, the Order System application collects and processes the orders,
such as validating credit cards and forwarding the order to the Order
Fulfillment system. Both the Order System application and the Order
Fulfillment application communicate with other internal applications and
systems for various reasons.
• Over time this publishing company becomes popular because it is hiring great
authors and putting out high-quality books, and it becomes apparent that this
simple solution is not keeping up with the demand and volume of orders. For
• One could argue that web services was the first step on the road to SOA. Is
that statement true? Yes and no. No, in that you can have an SOA solution
without using web services. Yes, in that it is a great beginning to something
much larger.
Advantage
• WCF is interoperable with other services when compared to .Net
Remoting,where the client and service have to be .Net.
• WCF services provide better reliability and security in compared to ASMX web
services.
• In WCF, there is no need to make much change in code for implementing the
security model and changing the binding. Small changes in the configuration
will make your requirements.
• WCF has integrated logging mechanism, changing the configuration file
settings will provide this functionality. In other technology developer has to
write the code.
Disadvantage
Making right design for your requirement is little bit difficult.
Contracts
• WCF contracts are much like a contract that you and I would sign in real life.
A contract I may sign could contain information such as the type of work I will
perform and what information I might make available to the other party.
• A WCF contract contains very similar information. It contains information that
stipulates what a service does and the type of information it will make
available.
• A data contract explicitly stipulates the data that will be exchanged by the
service. The service and the client need to agree on parameters and return
types of the methods.
• A service contract is what informs the clients and the rest of the outside world
what the endpoint has to offer and communicate.
Service Runtime
• The Service Runtime layer is the layer that specifies and manages the
behaviors of the service that occur during service operation, or service
runtime (thus “service runtime behaviors”). Service behaviors control service
type behaviors.
The following lists include major behaviors managed by the Service Runtime layer:
Messaging
The Messaging layer defines what formats and data exchange patterns can be used
during service communication. Client applications can be developed to access this
layer and control messaging details and work directly with messages and channels.
The following lists include major of the channels and components that the Messaging
layer is composed of:
The following list details the hosting and activation options provided by this layer:
• Windows Activation Service: The Windows Activation Service enables WCF
applications to be automatically started when running on a computer that is
running the Windows Activation Service.
• .EXE: WCF allows services to be run as executables (.EXE files).
• Windows Services: WCF allows services to be run as a Windows service.
• COM+: WCF allows services to be run as a COM+ application.
In WCF, every service is associated with a unique address. WCF supports the
following transport schemas:
• HTTP
• TCP
• Peer network
• IPC (Inter-Process Communication)
• MSMQ
http://localhost:8001
http://localhost:8001/MyService
net.tcp://localhost:8002/MyService
net.msmq://localhost/private/MyQueue
Contracts
Defining and implementing a service contract in C# is given as follows:
[ServiceContract]
interface IMyContract
{
[OperationContract]
string MyMethod(string text);
A .svc file
<%@ ServiceHost
Language = "C#"
Debug = "true"
Bindings
Binding will describes how client will communicate with service. There are different
protocols available for the WCF to communicate to the Client. You can mention the
protocol type based on your requirements. Binding has several characteristics,
including the following:
• Transport
Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ
are some type of protocols.
• Encoding (Optional)
• Protocol (Optional)
• Every service is associated with an address that defines where the service is, a
binding that defines how to communicate with the service, and a contract that
defines what the service does. This triumvirate governing the service is easy to
remember as the ABC of the service. WCF formalizes this relationship in the form
of an endpoint. The endpoint is the fusion of the address, contract, and binding.
namespace MyNamespace
{
[ServiceContract]
interface IMyContract
{...}
class MyService : IMyContract
{...}
}
<system.serviceModel>
<services>
<service name = "MyNamespace.MyService">
<endpoint
address = "http://localhost:8000/MyService"
binding = "wsHttpBinding"
contract = "MyNamespace.IMyContract"
/>
</service>
</services>
</system.serviceModel>
Server-side Programming
IUniService.cs
namespace UniService
{
[ServiceContract]
public interface IUniService
{
[OperationContract]
string GetGrade(double marks);
}
}
GradingService.svc
namespace UniService
{
public class GradingService : IUniService
{
Web.config
<system.serviceModel>
<services>
<service behaviorConfiguration="WCFDemoService.Service1Behavior"
name="UniService.GradingService">
<endpoint address="" binding="wsHttpBinding"
contract="UniService.IUniService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFDemoService.Service1Behavior">
<!-- To avoid disclosing metadata
information, set the value below to false and remove the metadata
endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in
faults for debugging purposes, set the value below to true. Set to
false before deployment to avoid disclosing exception information -->
<serviceDebug
includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
resultTB.Text = client.GetGrade(marks);
}
catch
{
resultTB.Text = "NA";
}
}
Must add service reference as follows:
Must use the same namespace which was given in service as follow:
To test whether our service was built ok then set main project as WCFdemoservice
and run it from VS-2008 and you will see the following.
If you want to publish this website to IIS then the followings are important.
Also by clicking the edit configuration of the above figure you need to select c# as
the application language.
Use Debug version not Release version while you develop your solution. I had that
problem.
The Following Module was built either with optimizations enabled or without debug
information
…….. discovered that I wasn't outputting my debug info on my build. If you right click
on the project and go to 'properties', then select the 'build' tab, on the bottom of the
page there's an 'Advanced...' button that will display your setting for you output
debug info. Set that to 'full' and the error should go away.
Lab Work
In this lab work (WCFExample.rar), the above grade calculator and how to use this
service projects are given. You are supposed to run this solution and modify by adding
another method into this to understand well this activity.
You are asked to develop a web-service which hosts a method that takes a tax payer’s
(Bangladeshi) income and deduction information and after that returns his amount of tax
payable to the government. You can make the reasonable assumptions but make it as
simple as possible. You also need to develop a windows form application which can
demonstrate the consumption of this web-service.
ABC
• As discussed earlier, A service always has at least one endpoint, but can have multiple. A
client normally communicates with only one endpoint. A plain-old-webservice only has
one endpoint and communicates via HTTP and Text/XML. The picture below shows a
service with three endpoints. Notice the ABC.
Address Types
1. Endpoint Address
2. Base Address
Base addresses provide a way to specify a single, primary address for a given
service and assign relative addresses to each individual endpoint. For
example, suppose you have a service with three exposed endpoints. You can
assign a given service the following primary, or base, address:
http://mymachine:8080/myservice/
3. MEX Address
MEX addresses allow a client to gather information about a particular service.
MEX, meaning metadata exchange, is an HTTP endpoint address used to
obtain service information. For example, the following address is an MEX
address:
http://mymachine:8080/myservice/mex
1. HTTP Address
HTTP is an Application Layer protocol that is a request/response
http://www.sqlxml.com:8080/myservice
2. Base Address
HTTP addresses can be secured by using SSL (Secure Socket Layer):
https://www.sqlxml.com:8080/myservice
3. TCP Address
TCP provides communication services at an intermediate level between an
application program and the IP;
net.tcp://www.sqlxml.com:8080/myservice
4. MSMQ Address
Bindings
1. BasicHttpBinding
Due to the binding's simplicity it enables a higher level of interoperability with
existing web service client and services. It represents bindings that a service can
use to communicate with ASMX-based clients. It aims for clients which do not
have .NET 3.0 installed. The following example illustrates some of the properties
of BasicHttpBinding being configured in a configuration file:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name = “basichttpbind”
closeTimeout = “00:00:30”
openTimeout = “00:00:30”
sendTimeout = “00:00:30”
receiveTimeout = “00:00:30”>
</binding>
</basicHttpBinding>
</bindings>
</system.ServiceModel>
3. NetTcpBinding
The NetTcpBinding provides a secure and reliable binding environment for .NET-to-
.NET cross-machine communication. It uses the TCP protocol and provides full
support for SOAP security, transactions, and reliability.
<system.serviceModel>
<bindings>
<netTCPBinding>
<binding name = “nettcpbind”
portsharingenabled = “true”
listenbacklog = “10”
closeTimeout = “00:00:30”
transactionflow = “true”>
</binding>
</netTCPBinding>
</bindings>
</system.ServiceModel>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name = “netnamedpipebind”
maxconnections = “50”
openTimeout = “00:00:30”>
</binding>
</netNamedPipeBinding>
</bindings>
</system.ServiceModel>
5. NetMsmqBinding
The NetMsmqBinding provides a secure and reliable queued communication for
cross-machine environments. Queuing is provided by using the MSMQ (Microsoft
Message Queuing) as a transport, which enables support for disconnected
operations, failure isolation, and load leveling.
<system.serviceModel>
<bindings>
<netMsmqBinding>
<binding name = “netmsmqbind”
exactlyonce = “true”
durable = “true”
usemsmqtracing = “false”
openTimeout = “00:00:30”>
</binding>
</netMsmqBinding>
</bindings>
</system.ServiceModel>
IServiceClass.cs
namespace WCFService
{
[ServiceContract]
public interface IServiceClass
{
[OperationContract]
string GetText();
[OperationContract]
int MultiplyNumbers(int firstvalue, int secondvalue);
}
}
ServiceClass.cs
namespace WCFService
{
public class ServiceClass : IServiceClass
{
string IServiceClass.GetText()
{
StreamReader sw = new StreamReader(
@"D:\Monzur\UIU_semester\Summer-2011\CSE 6007\SmapleWCFPoj\
TCP_BindingExample\FileFolder\WCFServiceTest.txt");
return sw.ReadLine();
}
int IServiceClass.MultiplyNumbers(int firstvalue,int
secondvalue)
{
return firstvalue * secondvalue;
}
}
}
public WCFForm()
{
InitializeComponent();
}
1. Service Contract
[OperationContract]
bool CheckOrder(int ordernumber);
Lab-1
The example-1 uses TCP binding to read the content of a file and
multiply two numbers. You are expected to provide the options TCP or
Named pipe bindings i.e. two endpoints. The rest is same as before.
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -ga
administrator
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i
Start installing ASP.NET (4.0.30319).
.......
Finished installing ASP.NET (4.0.30319).
MVC1
1. No separation of presentation layer and business layer.
2. Doesnt promote reusability of application components.
3. its for simple applications.
MVC2
1. Ease of maintenance resulting from separation of presentation layer and business layer.
2. Reusability of components
3. Controller presents a single point of entry to the web application providing cleaner means of implementing
security and state mgmt.
4. MVC2 is not the successor to MVC.
ASP.NET MVC has always supported the concept of “view engines” – which are the pluggable modules that
implement different template syntax options. The “default” view engine for ASP.NET MVC today uses the same
.aspx/.ascx/.master file templates as ASP.NET Web Forms. Other popular ASP.NET MVC view engines used
today include Spark and NHaml.
The new view-engine option we’ve been working on is optimized around HTML generation using a code-focused
templating approach. The codename for this new view engine is “Razor”, and we’ll be shipping the first public
beta of it shortly.
Design Goals
We had several design goals in mind as we prototyped and evaluated “Razor”:
• Compact, Expressive, and Fluid: Razor minimizes the number of characters and keystrokes required in a file, and
enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to
explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables
a really compact and expressive syntax which is clean, fast and fun to type.
• Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of concepts. You use
all your existing language and HTML skills.
• Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old
text editor (notepad works great).
• Has great Intellisense: While Razor has been designed to not require a specific tool or code editor, it will have
awesome statement completion support within Visual Studio. We’ll be updating Visual Studio 2010 and Visual Web
Developer 2010 to have full editor intellisense for it.
• Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a
controller or web-server, and can be hosted in any unit test project – no special app-domain required).
We’ve spent the last few months building applications with it and doing lots of usability studies of it with a variety of volunteers
(including several groups of non-.NET web developers). The feedback so far from people using it has been really great.
Razor will be one of the view engine options we ship built-into ASP.NET MVC. All view helper methods and programming
model features will be available with both Razor and the .ASPX view engine.
To see a quick example of this let’s create a simple “hello world” sample that outputs a message like so:
If we were to build the above “hello world” sample using ASP.NET’s existing .ASPX markup syntax, we might write it using
<%= %> blocks to indicate “code nuggets” within our HTML markup like so:
One observation to make about this “hello world” sample is that each code nugget block requires 5 characters (<%= %>) to
denote the start and stop of the code sequence. Some of these characters (in particular the % key – which is center top on
most keyboards) aren’t the easiest to touch-type.
The Razor parser has semantic knowledge of C#/VB code used within code-blocks – which is why we didn’t need to explicitly
close the code blocks above. Razor was able to identify the above statements as self-contained code blocks, and implicitly
closed them for us.
Even in this trivial “hello world” example we’ve managed to save ourselves 12 keystrokes over what we had to type before. The
@ character is also easier to reach on the keyboard than the % character which makes it faster and more fluid to type.
If we were to implement this using ASP.NET’s existing .ASPX markup syntax, we might write the below code to dynamically
generate a <ul> list with <li> items for each product inside it:
Notice above how we started a “foreach” loop using the @ symbol, and then contained a line of HTML content with code blocks
within it. Because the Razor parser understands the C# semantics in our code block, it was able to determine that the <li>
content should be contained within the foreach and treated like content that should be looped. It also recognized that the
trailing } terminated the foreach statement.
Razor was also smart enough to identify the @p.Name and @p.Price statements within the <li> element as server code – and
execute them each time through the loop. Notice how Razor was smart enough to automatically close the @p.Name and
@p.Price code blocks by inferring how the HTML and code is being used together.
The ability to code like this without having to add lots of open/close markers throughout your templates ends up making the
whole coding process really fluid and fast.
If Statements
Like our foreach example above, you can embed content within if statements (or any other C# or VB language construct),
without having to be explicit about the code block’s begin/end. For example:
Multi-line Statements
You can denote multiple lines of code by wrapping it within a @{ code } block like so:
Multi-Token Statements
The @( ) syntax enables a code block to have multiple tokens. For example, we could re-write the above code to concatenate
a string and the number together within a @( code ) block:
Razor’s language parser is clever enough in most cases to infer whether a @ character within a template is being used for
code or static content. For example, below I’m using a @ character as part of an email address:
When parsing a file, Razor examines the content on the right-hand side of any @ character and attempts to determine whether
it is C# code (if it is a CSHTML file) or VB code (if it is a VBHTML file) or whether it is just static content. The above code will
output the following HTML (where the email address is output as static content and the @DateTime.Now is evaluated as code:
In cases where the content is valid as code as well (and you want to treat it as content), you can explicitly escape out @
characters by typing @@.
When nesting HTML content within an if/else, foreach or other block statement, you should look to wrap the inner content
within an HTML or XML element to better identify that it is the beginning of a content block.
This will render the below content to the client – note that it includes the <span> tag:
You can optionally wrap nested content with a <text> block for cases where you have content that you want to render to the
client without a wrapping tag:
The above code will render the below content to the client – note that it does not include any wrapping tag:
HTML Encoding
By default content emitted using a @ block is automatically HTML encoded to better protect against XSS attack scenarios.
Below is a simple example of a layout page – which we’ll save in a file called “SiteLayout.cshtml”. It can contain any static
HTML content we want to include in it, as well as dynamic server code. We’ll then add a call to the “RenderBody()” helper
method at the location in the template where we want to “fill in” specific body content for a requested URL:
We can then create a view template called “Home.cshtml” that contains only the content/code necessary to construct the
specific body of a requested page, and which relies on the layout template for its outer content:
When we render Home.cshtml as a view-template, it will combine the content from the layout and sub-page and send the
following content to the client:
We are trying to keep the code you write compact, easy and fluid. We also want to enable anyone with a text editor to be able
to open, edit and easily tweak/customize them. No code generation or intellisense required.
Because these two sections are marked as “optional”, I’m not required to define them within my Home.cshtml file. My site will
continue to work fine if they aren’t there.
Let’s go back into Home.cshtml, though, and define a custom Menu and Footer section for them. The below screenshot
contains all of the content in Home.cshtml – there is nothing else required in the file. Note: I moved setting the LayoutPage to
be a site wide setting – which is why it is no longer there.
When we render Home.cshtml as a view-template again, it will now combine the content from the layout and sub-page,
integrating the two new custom section overrides in it, and send down the following content to the client:
ASP.NET MVC today has the concept of “HTML Helpers” – which are methods that can be invoked within code-blocks, and
which encapsulate generating HTML. These are implemented using pure code today (typically as extension methods). All of
the existing HTML extension methods built with ASP.NET MVC (both ones we’ve built and ones built by others) will work using
the “Razor” view engine (no code changes required):
Generating HTML output using a code-only class approach works – but is not ideal.
One of the features we are looking to enable with Razor is an easy way to create re-usable HTML helpers using a more
declarative approach. Our plan is to enable you to define reusable helpers using a @helper { } declarative syntax like below.
You’ll be able to place .cshtml files that contain these helpers into a Views\Helpers directory and then re-use them from any
view or page in your site (no extra steps required):
Note: The @helper syntax won’t be in the first beta of Razor – but is something we hope will be enabled with the next drop.
Code-based helpers will work with the first beta.
One other useful (and extremely powerful) feature we are enabling with Razor is the ability to pass “inline template” parameters
to helper methods. These “inline templates” can contain both HTML and code, and can be invoked on-demand by helper
methods.
Below is an example of this feature in action using a “Grid” HTML Helper that renders a DataGrid to the client:
The Grid.Render() method call above is C#. We are using the new C# named parameter syntax to pass strongly-typed
arguments to the Grid.Render method - which means we get full statement completion/intellisense and compile-time checking
for the above syntax.
The “format” parameter we are passing when defining columns is an “inline template” – which contains both custom html and
code, and which we can use to customize the format of the data. What is powerful about this is that the Grid helper can invoke
our inline template as a delegate method, and invoke it as needed and as many times as it wants. In the scenario above it will
call it each time it renders a row in the grid – and pass in the “item” that our template can use to display the appropriate
response.
This capability will enable much richer HTML helper methods to be developed. You’ll be able to implement them using both a
code approach (like the way you build extension methods today) as well as using the declarative @helper {} approach.
Notice above how we are providing intellisense for a Product object on the “@p.” code embedded within the <li> element inside
a foreach loop. Also notice how our \Views folder within the Solution Explorer contains both .aspx and .cshtml view templates.
You can use multiple view engines within a single application – making it easy to choose whichever syntax feels best to you.
Summary
We think “Razor” provides a great new view-engine option that is streamlined for code-focused templating. It a coding workflow
that is fast, expressive and fun. It’s syntax is compact and reduces typing – while at the same time improving the overall
readability of your markup and code. It will be shipping as a built-in view engine with the next release of ASP.NET MVC. You
can also drop standalone .cshtml/.vbhtml files into your application and run them as single-pages – which also enables you to
take advantage of it within ASP.NET Web Forms applications as well.
Not surprisingly, the customer's requirement represents an excellent opportunity to use open
multi-tier software architecture. The possible tiers of this software are as follows.
The database. The customer wants latitude and longitude information about various cities
to be stored in a database. They don't specify a particular kind of database, but we know that the
odds are good that at some point in the life of our application the airline will migrate from one
database platform to another. At the very least, we want the ability to do our development and
testing under one kind of database before connecting our application to the airline's database
server. It seems like a good idea to treat our database and its server as a discrete unit—the
database layer.
The accessors. With a database layer that's distinct from everything else, we need a
collection of software elements that act as interfaces between the database and the software that
relies on its data. Structured query language (SQL) is the specific go-between, but we want to
abstract the SQL statements a bit. This is the function ofthe objects in the accessor layer. The
accessor layer should be easily reconfigured to
connect to a new kind of database server, as well. For that reason, it will make use of the PEAR
DB classes, which will be discussed further later in this chapter, and in Chapter 7 on database
access.
The business logic. The customer provided us with a statement of the business logic for
this application. The application is to calculate Great Circle distances. How? Based on the
latitudes and longitudes of the two endpoint cities. If we can find a mathematical formula that
takes such input and provides the required output, and can encode that algorithm into the PHP
language, we have a business logic layer.
The presentation mechanism. The user interface shouldn't be too complicated, and it
may even be possible to fit it all into one piece of software. The presentation layer has to first
present the user with lists of possible origin and destination cities and allow him or her to select
one of each. Upon submission of those values, the user interface should present the calculated
Great Circle distance, and make it easy for the user to do another calculation with a different pair
of cities.
** For further reference for this problem you have been given the text where this problem is
extracted. Their solution is given in PHP and services are third party catered which you should
create yourself.
Submission Guidelines
• SRS of the problem and infrastructure requirements for the software solution.
• Use case diagram and Component Diagram
• Software Architecture Design using VISIO or Visual paradigm for the above
mentioned problem.
• Source code of the solution using C#/Java/OO PHP.
• Deployment Diagram using VISIO or Visual Paradigm and deployment description
• Testing strategies – a document file.
The assignment is a group assignment and each group may have maximum four students. The
assignment is due on week 12 to the CSE executive course box or my office or final exam hall.
As we would like you to have the opportunity to finish the last assignment before the end of the
semester, we would like this date to be a final one. Your submission must include a description
of your answers in readme.txt file. All submission must be in a CD or DVD with a cover case.
No printed or hard copy will be accepted or mailed. I may allow multiple submissions in one
CD/DVD, in that case separate folder must be created with student’s ID as the folder name.
2. Class Diagram
3. Component Diagram
4. Deployment Diagram
---------------------End of Assignment---------------------------
chap
Desi^^^P^nmplementing
a M u | n l i P ^ n ) l i c a t i o n in PHP:
A Sue pie
I his chapter gets straight to the essence of multi-tier design under PHP by walking
through the design and implementation of a complete application. Though the application
is simple in some ways—its database consists of a single table, for example, and there is
no elsewhere layer—it illustrates some important points. The idea is that you'll get a taste
of these key concepts here, and explore them more fully in later chapters.
55
56 Chapter 5: Designing and Implementing a Multi-Tier Application in PHP
the North Pole. Federal Express has a freight hub in Anchorage, Alaska, for a reason: That
city is roughly equidistant from Tokyo, New York, and London.
In any case, the customer wants us to develop an application that takes latitude
and longitude values for a given city from a database and uses them to calculate the Great
Circle distance between the two places. The solution to the problem, as well as the interface
that allows the user to specify the two cities of interest, should be one or more browser-
renderable pages.
^ ^
Persistence Layer
cities
Business
Logic calcGreatCircle.php
Layer
Note that the default values given for the latitude and longitude columns are obviously
invalid. If we'd used 0 instead, we'd have run the risk of confusion because 0,0 is a real
location off the west coast of Africa.
To run that code on a typical MySQL server (assuming you had not created a database
to contain the cities table), you'd use a sequence of commands beginning with these:
mysql
mysql>create database cities;
Query OK, 1 row affected (0.05 seconds)
mysql>quit
Bye.
Those lines logged you in, created a database called cities (the database and the table will
have the same name), and logged you out. Then, at the operating system's command line,
you'd enter this:
mysql cities < cities.sql
That runs the SQL statements in cities.sql against the database called cities.
Continuing, there are some rules about the data that is to be stored in the cities table:
• The latitude column contains a decimal representation of degrees latitude, with 0
being the equator, positive numbers being north latitudes, and negative numbers
being south latitudes.
• The longitude column contains a decimal representation of degrees longitude,
with 0 being the prime meridian through Greenwich, positive numbers being west
longitudes, and negative numbers being east longitudes.
Both latitude and longitude values are therefore between -180 and 180.
Furthermore, PEAR DB requires a specific string that identifies the type of database server
being connected to the application. A list of various servers' key strings appears in the PEAR
DB documentation and in Chapter 7, but for now just know that the identifying string that
corresponds to a MySQL server is mysql.
Each program in the accessor layer will need all of these details. Because it's possible
that they'll change—that the server will move to a different machine, or that the username
and password will change—it makes sense to isolate all of the details in a single file. The
file can then be imported (using a require_once() statement, typically) into any piece of
software that will access the database.
Here is a listing of the most important lines from dbDetails.php:
Sphptype = 'mysql'; // Type of database server (PEAR-DB standard name string).
Shostspec = 'db2'; // Hostname of database server (or IP address).
Sdatabase = 'cities'; // Database name.
Susername = 'access'; // Database username.
Spassword = 'php'; // Database password.
The configuration details are all there and commented, ready for modification.
$s = new soap_server;
$s->register('getCities');
$s->service($HTTP_RAW_POST_DATA);
These lines refer to NuSOAP classes and establish a SOAP server to which other layers can
connect. The SOAP server is set up to catch HTTP requests, and the getCities() function,
to be declared momentarily, is made available for external access.
function getCities() {
5.3 The Accessor Layer 63
// Assemble Data Source Name (DSN) and connect, allowing for errors...
$dsn = "$phptype://$username:$password@$hostspec/$database";
$db = DB::connect($dsn);
if (DB::isError($db)) {
die ($db->getMessage());
}
The first part of the getCitiesO function concerns itself with connecting to the database
whose details are defined by the variables in dbDetails.php. The variables have to be made
available inside the function (that's what the five lines beginning with global are for). Then,
they can be used to assemble a datasource name (DSN), which is a uniform resource locator
(URL)-like string that PEAR DB uses to establish a connection to a database. An attempt to
connect is made; the attempt results in an object that has to be examined to see if it's an
error, in which case everything is off.
/ / Assemble and send SQL statement, allowing for e r r o r s . . .
Sresult = $db->query($sql);
if (DB::isError(Sresult))
{
SerrorMessage = $result->getMessage();
die (SerrorMessage);
}
With the connection to the database established, the function proceeds to set a variable
equal to an SQL query string (the decision to put the ORDER BY instruction here, rather than
in the presentation layer, certainly is debatable). The query then gets sent to the database,
which results in an object. That object has to be checked to see if it's an error. If it's not
an error, it's an object representing the results of the query.
/ / Extract rows from query results, fitting pieces of data into
64 Chapter 5: Designing and Implementing a Multi-Tier Application in PHP «
$db->disconnect();
return SreturnArray;
}
Having extracted all returned rows, the function terminates the database connection and
returns SreturnArray. Because this function is exposed as a SOAP service, SreturnArray
could be sent out across the network via the SOAP protocol. It's not a problem; SOAP
handles the transmission of arrays without any hassle.
Ss = new soap_server;
Ss->register('getLatLong');
Ss->service(SHTTP_RAW_POST_DATA);
• 5.3 The Accessor Layer 65
The program opens much like getCities.php, but with the getLatLongO function being
exposed this time.
function getLatLong($city) {
// Assemble Data Source Name (DSN) and connect, allowing for errors...
$dsn = "$phptype://$username:$password@$hostspec/$database";
$db = DB::connect($dsn);
if (DB::isError($db)) {
die ($db->getMessage());
}
Again, the sole function uses PEAR DB to hook up to a database, assembling a DSN out of
the pieces defined in the dbDetails.php file.
/ / Assemble and send SQL statement, allowing for e r r o r s . . .
i f (DB::isError($result)) {
SerrorMessage = $result->getMessage();
die (SerrorMessage);
}
Then, the function sends the SQL query to the database, and makes sure the result is
something other than an error.
// Extract rows from query results, fitting pieces of data into
// SreturnArray (an associative array) for returning.
Slatitude = $row[0];
Slongitude = $row[l];
$returnArray['city'] = $city;
$returnArray['latitude'] = Slatitude;
SreturnArray['longitude'] = Slongitude;
}
This function differs from getCitiesO in that it uses the query results, which comprise
three columns, to create an associative array. The code inside the while loop relies on the
fact that the sequence of the columns in the result set is known—a situation that results
from the explicit listing of column names in the SELECT statement.
/ / Disconnect from database and return SreturnArray...
$db->disconnect();
return SreturnArray;
}
When the work of querying the database and transferring the results to an associative array
is done, the function shuts down the database connection and returns the associative array
containing coordinate information.
$s = new soap_server;
$s->register('calculateGreatCircle');
$s->service($HTTP_RAW_POST_DATA);
Only the NuSOAP library is imported; there's no need for the database stuff here. The
c a l c u l a t e G r e a t C i r c l e ( ) function is exposed as a SOAP service.
function toRad($degrees) {
}
The function toRadO is a utility function that calculateGreatCircle() makes use of.
It converts a value expressed in degrees into an equivalent value expressed in radians. This
function is not exposed as a SOAP service; it's accessed only by calculateGreatCircle().
// Calculates Great Circle distance (in km) between Scityl and Scity2
// Establish Sparameters array and call Web Service to get latitude and
longitude for Scityl...
Sparameters = array('city'=>Scityl);
S soapclient = new soapclient('http://db2/greatCircle/getLatLong.php');
SreturnedArray = Ssoapclient->call('getLatLong',Sparameters);
Slatl = SreturnedArray[latitude];
Slongl = SreturnedArray[longitude];
// Establish Sparameters array and call Web Service to get latitude and
longitude for Scity2...
Sparameters = array('city'=>Scity2);
68 Chapter 5: Designing and Implementing a Multi-Tier Application in PHP
$lat2 = $returnedArray[latitude];
$long2 = $returnedArray[longitude];
$latl = toRad($latl);
$longl = toRad($longl);
$lat2 = toRad($lat2);
$long2 = toRad($long2);
// Calculate distance...
if (Sdistance < 0) {
$distance = $distance + pi();
}
return $distance;
}
The rest of calcGreatClrcIe.php has to do with the Great Circle calculation itself, which
isn't remarkable except for its extensive use of PHP's trigonometry functions.
your users should get, and so on) make up an elaborate field of programming specialty.
They're largely beyond the scope of this book, so we'll deal only with the characteristics
of the user interface that have to do with communicating with the rest of the application.
If the user is a machine, another software application of some kind, our program
should probably generate an extensible markup language (XML) document as output.
The beauty of the multi-tier architecture comes through when you consider that it would
be just as easy to provide XML, rather than HTML, documents at the presentation layer.
With XML results being generated, the application becomes, broadly speaking, more of
a Web service (to be used by other machines rather than by people) than a business appli-
cation. That means someone else could use your whole application as a module in his or
her project.
The presentation layer of the Great Circle application comprises a single page, which
perhaps not ideally, contains a combination of PHP and HTML code. Its "life cycle" has two
parts. First, it displays lists of candidate origin and destination cities, each with a cor-
responding radio button, and a master Submit button at the bottom of the page. That's
shown in Figure 5.2.
When the user chooses cities and clicks the Submit button, the page changes to
include the calculated distance between the two previously selected cities, as depicted
in Figure 5.3.
Here's a commentary on the presentation layer program, greatCircle.php (the name,
which makes no mention of the presentation layer, was chosen because the user may have
to type this filename as part of a URL):
require_once('nusoap-0.6/nusoap.php');
$cityl = $_POST['origin'];
$city2 = $_POST['destination'];
Variables $_POST[ ' o r i g i n ' ] and $_POST[destination] correspond to the name attributes
of the two sets of radio buttons in the HTML that appear later in greatCircle.php. When
a form is submitted to this program (it's submitted to itself, a process that's explained
later in this section), the value attribute of the selected radio button from each group is
the value of $_POST['origin'] and $_POST[destination]. Note that it's no longer good
practice to refer to Sorigin and S d e s t i n a t i o n directly, as was reasonable with the older
versions of PHP that shipped with the r e g i s t e r _ g l o b a l s option (in php.ini) on bydefault.
Modern versions of PHP have r e g i s t e r _ g l o b a l s off, so we must approach form contents
via the superglobal $_POST (or $_GET) array. See Chapter 4 for more information on HTTP
POST and HTTP GET operations.
/ / Establish Sparameters array and c a l l Web Service to get distance
M http://192.168.1.104/greatCircle/greatCircle.php
"3 ^^
Great Circle Calculator Great Circle Calculator
The great circle distance between Darwin and Pans is 14047 kilometers.
Choose the orighi.
Choose the orighu
r Cairo
C Cape Town C Cairo
<^ Copenhagen C Cj^e Town
<^ Darwin vy Copcnhsificii
f^ Hong Kong C Darwin
<~ Mumbai C Hong Kong
<~Pans O Mumbai
C Recife C Paris
<" San Francisco C Recfe
^ Santiago C San Francisco
<~ Seoul C Santiago
^ Shan^ai C Seoul
<~ Sydney C Shanghai
C Washington C Sydney
Choose the destlnatloii. C Washington
wmmmi^^^^m
Figure 5.2: The Great Circle presentation Figure 5.3: The Great Circle presentation
layer, before submission of a city pair. layer, after submission of a city pair and ready
for another challenge.
Sdistance = $soapclient->call('calculateGreatCircle',Sparameters);
Sdistance = round(Sdistance);
The function makes a call to the business logic layer, sending the two city names as para-
meters for calcGreatCircle to process. The round() function strips the fractional portion
from the result, because the algorithm used isn't accurate enough to merit such precision.
Sparameters = a r r a y O ;
5.5 The Presentation Layer 71
<head>
<title>Great Circle Calculator</title>
</head>
<body>
foreach ( S c i t i e s as Scity) {
echo "<input type='RADIO' name='origin'
value='$city'>$city <br>\n";
}
A simple PHP loop goes through the S c i t i e s array and generates the HTML radio buttons
representing origin cities.
<H3>Choose the destination.</H3>
foreach ( S c i t i e s as Scity) {
echo "<input type='RADIO' name='destination' value='$city'>$city <br>\n";
}
72 Chapter 5: Designing and Implementing a Multi-Tier Application in PHP •
A nearly identical loop, also operating on the Scities array, generates the HTML radio
buttons representing destination cities.
<P>
</form>
</body>
</html>
The remainder of the program is simple HTML code.