Saturday, March 27, 2010

Introduction to Object Oriented Programming Concepts (OOP)

1. Introduction
I have noticed an increase in the number of articles published in the Architect category in code-project during the last few months. The number of readers for most of these articles is also high, though the ratings for the articles are not. This indicates that readers are interested in reading articles on Architecture, but the quality does not match their expectations. This article is a constructive attempt to group/ define/ explain all introductory concepts of software architecture for well seasoned developers who are looking to take their next step as system architects.

One day I read an article that said that the richest 2 percent own half the world's wealth. It also said that the richest 1 percent of adults owned 40 percent of global assets in the year 2000. And further, that the richest 10 percent of adults accounted for 85 percent of the world's total wealth. So there is an unbalanced distribution of wealth in the physical world. Have you ever thought of an unbalanced distribution of knowledge in the software world? According to my view point, the massive expansion of the software industry is forcing developers to use already implemented libraries, services and frameworks to develop software within ever shorter periods of time. The new developers are trained to use (I would say more often) already developed software components, to complete the development quicker. They just plug in an existing library and some how manage to achieve the requirements. But the sad part of the story is, that they never get a training to define, design the architecture for, and implement such components. As the number of years pass by, these developers become leads and also software architects. Their titles change, but the old legacy of not understanding, of not having any architectural experience continues, creating a vacuum of good architects. The bottom line is that only a small percentage of developers know how to design a truly object oriented system. The solution to this problem is getting harder every day as the aggressive nature of the software industry does not support an easy adjustment to existing processes, and also the related online teaching materials are either complex or less practical or sometimes even wrong. The most of them use impractical, irrelevant examples of shapes, animals and many other physical world entities to teach concepts of software architecture. There are only very few good business-oriented design references. Unfortunately, I myself am no exception and am a result of this very same system. I got the same education that all of you did, and also referred to the same resource set you all read.

Coming back to the initial point, I noticed that there is a knowledge gap, increasing every day, between the architects who know how to architect a system properly and the others who do not know. The ones, who know, know it right. But the ones, who do not know, know nothing. Just like the world’s wealth distribution, it is an unbalanced distribution of knowledge.
2. Background
This article began after reading and hearing the questions new developers have, on basics of software architecture. There are some good articles out there, but still developers struggle to understand the basic concepts, and more importantly, the way to apply them correctly.

As I see it, newcomers will always struggle to understand a precise definition of a new concept, because it is always a new and hence unfamiliar idea. The one, who has experience, understands the meaning, but the one who doesn’t, struggles to understand the very same definition. It is like that. Employers want experienced employees. So they say, you need to have experience to get a job. But how the hell is one supposed to have that experience if no one is willing to give him a job? As in the general case, the start with software architecture is no exception. It will be difficult. When you start to design your very first system, you will try to apply everything you know or learned from everywhere. You will feel that an interface needs to be defined for every class, like I did once. You will find it harder to understand when and when not to do something. Just prepare to go through a painful process. Others will criticize you, may laugh at you and say that the way you have designed it is wrong. Listen to them, and learn continuously. In this process you will also have to read and think a lot. I hope that this article will give you the right start for that long journey.

“The knowledge of the actions of great men, acquired by long experience in contemporary affairs, and a continual study of antiquity” – I read this phrase when I was reading the book named “The Art of War”, seems applicable here, isn’t it?
3. Prerequisites
This article is an effort to provide an accurate information pool for new developers on the basics of software architecture, focusing on Object Oriented Programming (OOP). If you are a developer, who has a minimum of three or more years of continuous development experience and has that hunger to learn more, to step-in to the next level to become a software architect, this article is for you.
4. The Main Content
4.1. What is Software Architecture?
Software Architecture is defined to be the rules, heuristics and patterns governing:

* Partitioning the problem and the system to be built into discrete pieces
* Techniques used to create interfaces between these pieces
* Techniques used to manage overall structure and flow
* Techniques used to interface the system to its environment
* Appropriate use of development and delivery approaches, techniques and tools.

4.2. Why Architecture is important?



he primary goal of software architecture is to define the non-functional requirements of a system and define the environment. The detailed design is followed by a definition of how to deliver the functional behavior within the architectural rules. Architecture is important because it:

* Controls complexity
* Enforces best practices
* Gives consistency and uniformity
* Increases predictability
* Enables re-use.

4.3. What is OOP?
OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts.

In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.
4.4. What is an Object?
An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address.

In pure OOP terms an object is an instance of a class.
4.5. What is a Class?


A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.
Collapse

public class Student
{
}

According to the sample given below we can say that the student object, named objectStudent, has created out of the Student class.
Collapse

Student objectStudent = new Student();

In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles.

In the software world, though you may not have realized it, you have already used classes. For example, the TextBox control, you always used, is made out of the TextBox class, which defines its appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new instance of the TextBox class.
4.6. How to identify and design a Class?

This is an art; each designer uses different techniques to identify classes. However according to Object Oriented Design Principles, there are five principles that you must follow when design a class,

* SRP - The Single Responsibility Principle -
A class should have one, and only one, reason to change.
* OCP - The Open Closed Principle -
You should be able to extend a classes behavior, without modifying it.
* LSP - The Liskov Substitution Principle-
Derived classes must be substitutable for their base classes.
* DIP - The Dependency Inversion Principle-
Depend on abstractions, not on concretions.
* ISP - The Interface Segregation Principle-
Make fine grained interfaces that are client specific.

For more information on design principles, please refer to Object Mentor.

Additionally to identify a class correctly, you need to identify the full list of leaf level functions/ operations of the system (granular level use cases of the system). Then you can proceed to group each function to form classes (classes will group same types of functions/ operations). However a well defined class must be a meaningful grouping of a set of functions and should support the re-usability while increasing expandability/ maintainability of the overall system.

In software world the concept of dividing and conquering is always recommended, if you start analyzing a full system at the start, you will find it harder to manage. So the better approach is to identify the module of the system first and then dig deep in to each module separately to seek out classes.

A software system may consist of many classes. But in any case, when you have many, it needs to be managed. Think of a big organization, with its work force exceeding several thousand employees (let’s take one employee as a one class). In order to manage such a work force, you need to have proper management policies in place. Same technique can be applies to manage classes of your software system as well. In order to manage the classes of a software system, and to reduce the complexity, the system designers use several techniques, which can be grouped under four main concepts named Encapsulation, Abstraction, Inheritance, and Polymorphism. These concepts are the four main gods of OOP world and in software term, they are called four main Object Oriented Programming (OOP) Concepts.
4.7. What is Encapsulation (or information hiding)?
The encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do.


n order to modularize/ define the functionality of a one class, that class can uses functions/ properties exposed by another class in many different ways. According to Object Oriented Programming there are several techniques, classes can use to link with each other and they are named association, aggregation, and composition.

There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.
Collapse

IStudent myStudent = new LocalStudent();
IStudent myStudent = new ForeignStudent();

According to the sample above (let’s assume that LocalStudent and ForeignStudent are implemented by the IStudent interface) we can see how LocalStudent and ForeignStudent are hiding their, localize implementing information through the IStudent interface.

4.8. What is Association?

Association is a (*a*) relationship between two classes. It allows one object instance to cause another to perform an action on its behalf. Association is the more general term that define the relationship between two classes, where as the aggregation and composition are relatively special.
Collapse

public class StudentRegistrar
{
public StudentRegistrar ();
{
new RecordManager().Initialize();
}
}

In this case we can say that there is an association between StudentRegistrar and RecordManager or there is a directional association from StudentRegistrar to RecordManager or StudentRegistrar use a (*Use*) RecordManager. Since a direction is explicitly specified, in this case the controller class is the StudentRegistrar.


To some beginners, association is a confusing concept. The troubles created not only by the association alone, but with two other OOP concepts, that is association, aggregation and composition. Every one understands association, before aggregation and composition are described. The aggregation or composition cannot be separately understood. If you understand the aggregation alone it will crack the definition given for association, and if you try to understand the composition alone it will always threaten the definition given for aggregation, all three concepts are closely related, hence must study together, by comparing one definition to another. Let’s explore all three and see whether we can understand the differences between these useful concepts.
4.9. What is the difference between Association, Aggregation and Composition?
Association is a (*a*) relationship between two classes, where one class use another. But aggregation describes a special type of an association. Aggregation is the (*the*) relationship between two classes. When object of one class has an (*has*) object of another, if second is a part of first (containment relationship) then we called that there is an aggregation between two classes. Unlike association, aggregation always insists a direction.
Collapse

public class University
{
private Chancellor universityChancellor = new Chancellor();
}



In this case I can say that University aggregate Chancellor or University has an (*has-a*) Chancellor. But even without a Chancellor a University can exists. But a University cannot exist without Faculties, the life time of a University attached with the life time of its Faculty (or Faculties). If Faculties are disposed the University will not exist or wise versa. In that case we called that University is composed of Faculties. So that composition can be recognized as a special type of an aggregation.



Same way, as another example, you can say that, there is a composite relationship in-between a KeyValuePairCollection and a KeyValuePair. The two mutually depend on each other.

.Net and Java uses the Composite relation to define their Collections. I have seen Composition is being used in many other ways too. However the more important factor, that most people forget is the life time factor. The life time of the two classes that has bond with a composite relation mutually depend on each other. If you take the .net Collection to understand this, there you have the Collection Element define inside (it is an inner part, hence called it is composed of) the Collection, farcing the Element to get disposed with the Collection. If not, as an example, if you define the Collection and it’s Element to be independent, then the relationship would be more of a type Aggregation, than a Composition. So the point is, if you want to bind two classes with Composite relation, more accurate way is to have a one define inside the other class (making it a protected or private class). This way you are allowing the outer class to fulfill its purpose, while tying the lifetime of the inner class with the outer class.

So in summary, we can say that aggregation is a special kind of an association and composition is a special kind of an aggregation. (Association->Aggregation->Composition)



4.10. What is Abstraction and Generalization?
Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.

While abstraction reduces complexity by hiding irrelevant detail, generalization reduces complexity by replacing multiple entities which perform similar functions with a single construct. Generalization is the broadening of application to encompass a larger domain of objects of the same or different type. Programming languages provide generalization through variables, parameterization, generics and polymorphism. It places the emphasis on the similarities between objects. Thus, it helps to manage complexity by collecting individuals into groups and providing a representative which can be used to specify any individual of the group.

Abstraction and generalization are often used together. Abstracts are generalized through parameterization to provide greater utility. In parameterization, one or more parts of an entity are replaced with a name which is new to the entity. The name is used as a parameter. When the parameterized abstract is invoked, it is invoked with a binding of the parameter to an argument.
4.11. What is an Abstract class?
Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be used as a super-class for other classes that extend the abstract class. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties.

Abstract classes are ideal when implementing frameworks. As an example, let’s study the abstract class named LoggerBase below. Please carefully read the comments as it will help you to understand the reasoning behind this code.
Collapse

public abstract class LoggerBase
{
///
/// field is private, so it intend to use inside the class only
///

private log4net.ILog logger = null;

///
/// protected, so it only visible for inherited class
///

protected LoggerBase()
{
// The private object is created inside the constructor
logger = log4net.LogManager.GetLogger(this.LogPrefix);
// The additional initialization is done immediately after
log4net.Config.DOMConfigurator.Configure();
}

///
/// When you define the property as abstract,
/// it forces the inherited class to override the LogPrefix
/// So, with the help of this technique the log can be made,
/// inside the abstract class itself, irrespective of it origin.
/// If you study carefully you will find a reason for not to have “set” method here.
///

protected abstract System.Type LogPrefix
{
get;
}

///
/// Simple log method,
/// which is only visible for inherited classes
///

///
protected void LogError(string message)
{
if (this.logger.IsErrorEnabled)
{
this.logger.Error(message);
}
}

///
/// Public properties which exposes to inherited class
/// and all other classes that have access to inherited class
///

public bool IsThisLogError
{
get
{
return this.logger.IsErrorEnabled;
}
}
}

The idea of having this class as an abstract is to define a framework for exception logging. This class will allow all subclass to gain access to a common exception logging module and will facilitate to easily replace the logging library. By the time you define the LoggerBase, you wouldn’t have an idea about other modules of the system. But you do have a concept in mind and that is, if a class is going to log an exception, they have to inherit the LoggerBase. In other word the LoggerBase provide a framework for exception logging.

Let’s try to understand each line of the above code.

Like any other class, an abstract class can contain fields, hence I used a private field named logger declare the ILog interface of the famous log4net library. This will allow the Loggerbase class to control, what to use, for logging, hence, will allow changing the source logger library easily.

The access modifier of the constructor of the LoggerBase is protected. The public constructor has no use when the class is of type abstract. The abstract classes are not allowed to instantiate the class. So I went for the protected constructor.

The abstract property named LogPrefix is an important one. It enforces and guarantees to have a value for LogPrefix (LogPrefix uses to obtain the detail of the source class, which the exception has occurred) for every subclass, before they invoke a method to log an error.

The method named LogError is protected, hence exposed to all subclasses. You are not allowed or rather you cannot make it public, as any class, without inheriting the LoggerBase cannot use it meaningfully.

Let’s find out why the property named IsThisLogError is public. It may be important/ useful for other associated classes of an inherited class to know whether the associated member logs its errors or not.

Apart from these you can also have virtual methods defined in an abstract class. The virtual method may have its default implementation, where a subclass can override it when required.

All and all, the important factor here is that all OOP concepts should be used carefully with reasons, you should be able to logically explain, why you make a property a public or a field a private or a class an abstract. Additionally, when architecting frameworks, the OOP concepts can be used to forcefully guide the system to be developed in the way framework architect’s wanted it to be architected initially.
4.12. What is an Interface?
In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently. Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme.

Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.

If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.

The sample below will provide an interface for our LoggerBase abstract class.
Collapse

public interface ILogger
{
bool IsThisLogError { get; }
}

4.13. What is the difference between a Class and an Interface?
In .Net/ C# a class can be defined to implement an interface and also it supports multiple implementations. When a class implements an interface, an object of such class can be encapsulated inside an interface.

If MyLogger is a class, which implements ILogger, there we can write
Collapse

ILogger log = new MyLogger();

A class and an interface are two different types (conceptually). Theoretically a class emphasis the idea of encapsulation, while an interface emphasis the idea of abstraction (by suppressing the details of the implementation). The two poses a clear separation from one to another. Therefore it is very difficult or rather impossible to have an effective meaningful comparison between the two, but it is very useful and also meaningful to have a comparison between an interface and an abstract class.
4.14. What is the difference between an Interface and an Abstract class?

There are quite a big difference between an interface and an abstract class, even though both look similar.

* Interface definition begins with a keyword interface so it is of type interface
* Abstract classes are declared with the abstract keyword so it is of type class
* Interface has no implementation, but they have to be implemented.
* Abstract class’s methods can have implementations and they have to be extended.
* Interfaces can only have method declaration (implicitly public and abstract) and fields (implicitly public static)
* Abstract class’s methods can’t have implementation only when declared abstract.
* Interface can inherit more than one interfaces
* Abstract class can implement more than one interfaces, but can inherit only one class
* Abstract class must override all abstract method and may override virtual methods
* Interface can be used when the implementation is changing
* Abstract class can be used to provide some default behavior for a base class.
* Interface makes implementation interchangeable
* Interface increase security by hiding the implementation
* Abstract class can be used when implementing framework
* Abstract classes are an excellent way to create planned inheritance hierarchies and also to use as non-leaf classes in class hierarchies.

Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class can be used to provide the default implementation of the services and all mandatory modules such as event logging and message handling etc. This approach allows the developers to develop the application within the guided help provided by the framework.

However, in practice when you come across with some application-specific functionality that only your application can perform, such as startup and shutdown tasks etc. The abstract base class can declare virtual shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, it can execute the method defined by the child class.
4.15. What is Implicit and Explicit Interface Implementations?

As mentioned before .Net support multiple implementations, the concept of implicit and explicit implementation provide safe way to implement methods of multiple interfaces by hiding, exposing or preserving identities of each of interface methods, even when the method signatures are the same.

Let's consider the interfaces defined below.
Collapse

interface IDisposable
{
void Dispose();
}

Here you can see that the class Student has implicitly and explicitly implemented the method named Dispose() via Dispose and IDisposable.Dispose.
Collapse

class Student : IDisposable
{
public void Dispose()
{
Console.WriteLine("Student.Dispose");
}

void IDisposable.Dispose()
{
Console.WriteLine("IDisposable.Dispose");
}
}

4.16. What is Inheritance?

Ability of a new class to be created, from an existing class by extending it, is called inheritance.


Collapse

public class Exception
{
}


public class IOException : Exception
{
}

According to the above example the new class (IOException), which is called the derived class or subclass, inherits the members of an existing class (Exception), which is called the base class or super-class. The class IOException can extend the functionality of the class Exception by adding new types and methods and by overriding existing ones.

Just like abstraction is closely related with generalization, the inheritance is closely related with specialization. It is important to discuss those two concepts together with generalization to better understand and to reduce the complexity.

One of the most important relationships among objects in the real world is specialization, which can be described as the “is-a” relationship. When we say that a dog is a mammal, we mean that the dog is a specialized kind of mammal. It has all the characteristics of any mammal (it bears live young, nurses with milk, has hair), but it specializes these characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As such, we expect it to share certain characteristics with the dog that are generalized in Mammal, but to differ in those characteristics that are specialized in cats.

The specialization and generalization relationships are both reciprocal and hierarchical. Specialization is just the other side of the generalization coin: Mammal generalizes what is common between dogs and cats, and dogs and cats specialize mammals to their own specific subtypes.

Similarly, as an example you can say that both IOException and SecurityException are of type Exception. They have all characteristics and behaviors of an Exception, That mean the IOException is a specialized kind of Exception. A SecurityException is also an Exception. As such, we expect it to share certain characteristic with IOException that are generalized in Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In other words, Exception generalizes the shared characteristics of both IOException and SecurityException, while IOException and SecurityException specialize with their characteristics and behaviors.

In OOP, the specialization relationship is implemented using the principle called inheritance. This is the most common and most natural and widely accepted way of implement this relationship.
4.17. What is Polymorphisms?
Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts.

In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading and method overriding,
4.18. What is Method Overloading?
The method overloading is the ability to define several methods all with the same name.
Collapse

public class MyLogger
{
public void LogError(Exception e)
{
// Implementation goes here
}

public bool LogError(Exception e, string message)
{
// Implementation goes here
}
}

4.19. What is Operator Overloading?
The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all of operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments.
Collapse

public class Complex
{
private int real;
public int Real
{ get { return real; } }

private int imaginary;
public int Imaginary
{ get { return imaginary; } }

public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}

public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}

I above example I have overloaded the plus operator for adding two complex numbers. There the two properties named Real and Imaginary has been declared exposing only the required “get” method, while the object’s constructor is demanding for mandatory real and imaginary values with the user defined constructor of the class.
4.20. What is Method Overriding?
Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.

A subclass can give its own definition of methods but need to have the same signature as the method in its super-class. This means that when overriding a method the subclass's method has to have the same name and parameter list as the super-class's overridden method.
Collapse

using System;
public class Complex
{
private int real;
public int Real
{ get { return real; } }

private int imaginary;
public int Imaginary
{ get { return imaginary; } }

public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}

public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}

public override string ToString()
{
return (String.Format("{0} + {1}i", real, imaginary));
}
}

In above example I have extended the implementation of the sample Complex class given under operator overloading section. This class has one overridden method named “ToString”, which override the default implementation of the standard “ToString” method to support the correct string conversion of a complex number.
Collapse

Complex num1 = new Complex(5, 7);
Complex num2 = new Complex(3, 8);

// Add two Complex numbers using the
// overloaded plus operator
Complex sum = num1 + num2;

// Print the numbers and the sum
// using the overriden ToString method
Console.WriteLine("({0}) + ({1}) = {2}", num1, num2, sum);
Console.ReadLine();

4.21. What is a Use case?

A use case is a thing an actor perceives from the system. A use case maps actors with functions. Importantly, the actors need not be people. As an example a system can perform the role of an actor, when it communicate with another system.



In another angle a use case encodes a typical user interaction with the system. In particular, it:

* Captures some user-visible function.

* Achieves some concrete goal for the user.

A complete set of use cases largely defines the requirements for your system: everything the user can see, and would like to do. The below diagram contains a set of use cases that describes a simple login module of a gaming website.



4.22. What is a Class Diagram?

A class diagrams are widely used to describe the types of objects in a system and their relationships. Class diagrams model class structure and contents using design elements such as classes, packages and objects. Class diagrams describe three different perspectives when designing a system, conceptual, specification, and implementation. These perspectives become evident as the diagram is created and help solidify the design.

The Class diagrams, physical data models, along with the system overview diagram are in my opinion the most important diagrams that suite the current day rapid application development requirements.
UML Notations:


4.23. What is a Package Diagram?
Package diagrams are used to reflect the organization of packages and their elements. When used to represent class elements, package diagrams provide a visualization of the name-spaces. In my designs, I use the package diagrams to organize classes in to different modules of the system.
4.24. What is a Sequence Diagram?
A sequence diagrams model the flow of logic within a system in a visual manner, it enable both to document and validate your logic, and are used for both analysis and design purposes. Sequence diagrams are the most popular UML artifact for dynamic modeling, which focuses on identifying the behavior within your system.
4.25. What is two-tier architecture?
The two-tier architecture is refers to client/ server architectures as well, the term client/ server was first used in the 1980s in reference to personal computers (PCs) on a network. The actual client/ server model started gaining acceptance in the late 1980s, and later it was adapted to World Wide Web programming.

According to the modern days use of two-tier architecture the user interfaces (or with ASP.NET, all web pages) runs on the client and the database is stored on the server. The actual application logic can run on either the client or the server. So in this case the user interfaces are directly access the database. Those can also be non-interface processing engines, which provide solutions to other remote/ local systems. In either case, today the two-tier model is not as reputed as the three-tier model. The advantage of the two-tier design is its simplicity, but the simplicity comes with the cost of scalability. The newer three-tier architecture, which is more famous, introduces a middle tier for the application logic.


4.26. What is three-tier architecture?
The three tier software architecture (also known as three layer architectures) emerged in the 1990s to overcome the limitations of the two tier architecture. This architecture has aggressively customized and adopted by modern day system designer to web systems.

Three-tier is a client-server architecture in which the user interface, functional process logic, data storage and data access are developed and maintained as independent modules, some time on separate platforms. The term "three-tier" or "three-layer", as well as the concept of multi-tier architectures (often refers to as three-tier architecture), seems to have originated within Rational Software.



The 3-Tier architecture has the following three tiers.

1. Presentation Tier or Web Server: User Interface, displaying/ accepting data/ input to/ from the user
2. Application Logic/ Business Logic/ Transaction Tier or Application Server: Data validation, acceptability check before being added to the database and all other business/ application specific operations
3. Data Tier or Database server: Simple reading and writing method to database or any other storage, connection, command, stored procedures etc

4.27. What is MVC architecture?
The Model-View-Controller (MVC) architecture separates the modeling of the domain, the presentation, and the actions based on user input into three separate classes.

Unfortunately, the popularity of this pattern has resulted in a number of faulty usages; each technology (Java, ASP.NET etc) has defined it in their own way making it difficult to understand. In particular, the term "controller" has been used to mean different things in different contexts. The definitions given bellow are the closes possible ones I found for ASP.NET version of MVC.


1. Model: DataSet and typed DataSet (some times business object, object collection, XML etc) are the most common use of the model.
2. View: The ASPX and ASCX files generally handle the responsibilities of the view.
3. Controllers: The handling of events or the controlling is usually done in the code-behind class.

In a complex n-tier distributed system the MVC architecture place the vital role of organizing the presentation tier of the system.
4.28. What is SOA?
A service-oriented architecture is essentially a collection of services. These services communicate with each other. The communication can involve either simple data passing or it could involve two or more services coordinating some activity. Some means of connecting services to each other is needed.

The .Net technology introduces the SOA by mean of web services.




The SOA can be used as the concept to connect multiple systems to provide services. It has it's great share in the future of the IT world.

According to the imaginary diagram above, we can see how the Service Oriented Architecture is being used to provide a set of centralized services to the citizens of a country. The citizens are given a unique identifying card, where that card carries all personal information of each citizen. Each service centers such as shopping complex, hospital, station, and factory are equipped with a computer system where that system is connected to a central server, which is responsible of providing service to a city. As an example when a customer enter the shopping complex the regional computer system report it to the central server and obtain information about the customer before providing access to the premises. The system welcomes the customer. The customer finished the shopping and then by the time he leaves the shopping complex, he will be asked to go through a billing process, where the regional computer system will manage the process. The payment will be automatically handled with the input details obtain from the customer identifying card.

The regional system will report to the city (computer system of the city) while the city will report to the country (computer system of the country).
4.29. What is the Data Access Layer?
The data access layer (DAL), which is a key part of every n-tier system, is mainly consist of a simple set of code that does basic interactions with the database or any other storage device. These functionalities are often referred to as CRUD (Create, Retrieve, Update, and Delete).

The data access layer need to be generic, simple, quick and efficient as much as possible. It should not include complex application/ business logics.

I have seen systems with lengthy, complex store procedures (SP), which run through several cases before doing a simple retrieval. They contain not only most part of the business logic, but application logic and user interface logic as well. If SP is getting longer and complicated, then it is a good indication that you are burring your business logic inside the data access layer.
4.30. What is the Business Logic Layer?
I know for a fact that this is a question for most, but from the other hand by reading many articles I have become aware that not everyone agrees to what business logic actually is, and in many cases it's just the bridge in between the presentation layer and the data access layer with having nothing much, except taking from one and passing to the other. In some other cases, it is not even been well thought out, they just take the leftovers from the presentation layer and the data access layer then put them in another layer which automatically is called the business logic layer. However there are no god said things that cannot be changed in software world. You can change as and when you feel comfortable that the method you apply is flexible enough to support the growth of your system. There are many great ways, but be careful when selecting them, they can over complicating the simple system. It is a balance one needs to find with their experience.

As a general advice when you define business entities, you must decide how to map the data in your tables to correctly defined business entities. The business entities should meaningfully define considering various types of requirements and functioning of your system. It is recommended to identify the business entities to encapsulate the functional/ UI (User Interface) requirements of your application, rather than define a separate business entity for each table of your database. For example, if you want to combine data from couple of table to build a UI (User Interface) control (Web Control), implement that function in the Business Logic Layer with a business object that uses couple of data object to support with your complex business requirement.
4.31. What is Gang of Four (GoF) Design Patterns?
The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.

Creational Patterns
o Abstract Factory Creates an instance of several families of classes
o Builder Separates object construction from its representation
o Factory Method Creates an instance of several derived classes
o Prototype A fully initialized instance to be copied or cloned
o Singleton A class of which only a single instance can exist
Structural Patterns
o Adapter Match interfaces of different classes
o Bridge Separates an object’s interface from its implementation
o Composite A tree structure of simple and composite objects
o Decorator Add responsibilities to objects dynamically
o Facade A single class that represents an entire subsystem
o Flyweight A fine-grained instance used for efficient sharing
o Proxy An object representing another object
Behavioral Patterns
o Chain of Resp. A way of passing a request between a chain of objects
o Command Encapsulate a command request as an object
o Interpreter A way to include language elements in a program
o Iterator Sequentially access the elements of a collection
o Mediator Defines simplified communication between classes
o Memento Capture and restore an object's internal state
o Observer A way of notifying change to a number of classes
o State Alter an object's behavior when its state changes
o Strategy Encapsulates an algorithm inside a class
o Template Method Defer the exact steps of an algorithm to a subclass
o Visitor Defines a new operation to a class without change

4.32. What is the difference between Abstract Factory and Builder design patterns?

The two design patterns are fundamentally different. However, when you learn them for the first time, you will see a confusing similarity. So that it will make harder for you to understand them. But if you continue to study eventually, you will get afraid of design patterns too. It is like infant phobia, once you get afraid at your early age, it stays with you forever. So the result would be that you never look back at design patterns again. Let me see whether I can solve this brain teaser for you.

In the image below, you have both design pattern listed in. I am trying to compare the two one on one to identify the similarities. If you observe the figure carefully, you will see an easily understandable color pattern (same color is used to mark the classes that are of similar kind).


Please follow up with the numbers in the image when reading the listing below.

Mark #1: Both patterns have used a generic class as the entry-class. The only difference is the name of the class. One pattern has named it as “Client”, while the other named it as “Director”.
Mark #2: Here again the difference is the class name. It is “AbstractFactory” for one and “Builder” for the other. Additionally both classes are of type abstract.
Mark #3: Once again both patterns have defined two generic (WindowsFactory & ConcreteBuilder) classes. They both have created by inheriting their respective abstract class.
Mark #4: Finally, both seem to produce some kind of a generic output.

Now, where are we? Aren’t they looking almost identical? So then why are we having two different patterns here?

Let’s compare the two again side by side for one last time, but this time, focusing on the differences.

* Abstract Factory: Emphasizes a family of product objects (either simple or complex)
* Builder: Focuses on constructing a complex object step by step

* Abstract Factory: Focus on *what* is made
* Builder: Focus on *how* it is made

* Abstract Factory: Focus on defining many different types of *factories* to build many *products*, and it is not a one builder for just one product
* Builder: Focus on building a one complex but one single *product*

* Abstract Factory: Defers the choice of what concrete type of object to make until run time
* Builder: Hide the logic/ operation of how to compile that complex object

* Abstract Factory: *Every* method call creates and returns different objects
* Builder: Only the *last* method call returns the object, while other calls partially build the object

Sometimes creational patterns are complementary: So you can join one or many patterns when you design your system. As an example builder can use one of the other patterns to implement which components get built or in another case Abstract Factory, Builder, and Prototype can use Singleton in their implementations. So the conclusion would be that the two design patterns exist to resolve two type of business problems, so even though they look similar, they are not.

I hope that this shed some light to resolve the puzzle. If you still don’t understand it, then this time it is not you, it has to be me and it is since that I don’t know how to explain it.
5. What is the Conclusion?
I don't think, that it is realistic trying to make a programming language be everything to everybody. The language becomes bloated, hard to learn, and hard to read if everything plus the kitchen sink is thrown in. In another word every language has their limitations. As system architect and designer we should be able to fully and more importantly correctly (this also mean that you shouldn’t use a ballistic missile to kill a fly or hire FBI to catch the fly) utilize the available tools and features to build usable, sustainable, maintainable and also very importantly expandable software systems, that fully utilize the feature of the language to bring a competitively advance system to their customers. In order to do it, the foundation of a system places a vital role. The design or the architecture of a software system is the foundation. It hold the system together, hence designing a system properly (this never mean an *over* desinging) is the key to the success. When you talk about designing a software system, the correct handling of OOP concept is very important. I have made the above article richer with idea but still kept it short so that one can learn/ remind all of important concept at a glance. Hope you all will enjoy reading it.

.NET Mobile Introduction

Background
Cell phones (mobile phones) have become part of our life style.

Today, mobile devices can connect to the Internet, and execute web applications.

Mobile applications can now be developed to deliver any types of data, to any user, any place in the world!

Different mobile devices support different programming languages. Some support WAP and WML, some support HTML or a limited version of HTML, and some support both or a different language.

To support all types of mobile devices, developers must create one different application for each language.

With .NET Mobile, Microsoft has introduced a new platform for developing mobile applications.

This tutorial is about how to develop applications with an extension to the .NET Framework, called the Microsoft Mobile Internet Toolkit (MMIT) or simply .NET Mobile.

What You Should Already Know

Before you continue you should have a basic understanding of the following:

* HTML / XHTML
* XML namespaces
* ASP .NET

.NET Mobile

.NET Mobile is an extension to Microsoft ASP.NET and the Microsoft's .NET Framework.

.NET Mobile is a set of server-side Forms Controls to build applications for wireless mobile devices.

These controls produce different output for different devices by generating WML, HTML, or compact HTML.

How Does It Work?

The following table shows how the .NET Mobile works:

Mobile Devices
The Internet
Internet Information Services - IIS
The .NET Framework
ASP.NET
.NET Mobile

* A web client requests a web page
* The request travels the Internet
* The request is received by IIS
* The request is handled by the .NET framework
* The requested page is compiled by ASP.NET
* .NET Mobile handles any mobile device requirements
* The page is returned to the client

Software Requirements
To develop mobile applications with .NET Mobile, you must have the following components:

1. Windows 2000 Professional/Server with IIS 5
2. All Windows 2000 service packs
3. The ASP.NET framework
4. Microsoft Mobile Internet Toolkit (MMIT)
5. Internet Explorer 5.5 or later
6. A WAP simulator

You will need Windows 2000 to develop .NET applications (IIS 5 (Internet Information Services) is a part of Windows 2000).

How To Start

Developing a mobile web application with ASP.NET is very easy:

1. Create an ASP.NET page
2. Include System.Mobile.UI
3. Add Mobile Controls to the page


.NET Mobile Example


The Mobile ASP.NET Page

Mobile Controls are the main building blocks of mobile applications.

Mobile Controls are similar to Web Controls in ASP.NET.

The following ASP.NET page displays "Hello W3Schools" as a WML card in a WML enabled cell phone:
<%@ Page
Inherits="System.Web.UI.MobileControls.MobilePage" %>
<%@ Register
TagPrefix="mob"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>


Hello W3Schools


The Page directive tells ASP to use (inherit) mobile page handling instead of regular page handling (like the one used for traditional browsers).
The Register directive defines the prefix that will be used for mobile controls. We have used "mob", but you can use any prefix you like.

The element tells the server to create a mobile form control.

The element tells the server to create a mobile label control with the text "Hello W3Schools".

When the ASP .NET page executes, it will produce the following output to a WAP enabled mobile phone:

'-//WAPFORUM//DTD WML 1.1//EN'
'http://www.wapforum.org/DTD/wml_1.1.xml'>



Hello W3Schools





and this output will be produced for a Pocket PC:



action="example.aspx">
Hello W3Schools






Conclusion

.NET Mobile will generate WML code for WAP enabled cell phones and HTML code for devices like the Pocket PC.

By detecting the browser, .NET Mobile will output correct content, providing developers with a powerful tool to develop single applications that will serve many different mobile devices.

.NET Mobile Emulators

Mobile applications can be tested and viewed with different emulators.
Using your Browser

Since mobile web pages detect your browser, you can test your mobile applications with a standard browser.

When a mobile web page detects a web browser it will produce HTML output.
Openwave Simulators

The Openwave mobile browser is the most common browser used in Internet-enabled cellphones.

An emulator can be downloaded from http://www.openwave.com
The Nokia Mobile Internet Toolkit

This toolkit contains emulators for most of the different Nokia devices.

This toolkit can be downloaded from http://forum.nokia.com
Windows Mobile Development Platform

Here you'll find answers to basic questions regarding the Windows Mobile development platform, along with different downloads:

http://msdn.microsoft.com/en-us/windowsmobile/bb250560.aspx

.NET Mobile Forms

.NET Mobile Forms are specialized web forms designed to work on different mobile devices.
Mobile Pages

A mobile page is much the same as an ordinary .NET web page. It is a text file with an aspx extension, and it can contain a variety of web controls.

The difference is the page directive that identifies the page as a mobile page, and the controls used on the page, which are mobile controls.

The mobile controls can be programmed device-independently, and the page will produce an output that suits the device that access it.
Mobile Forms

Each mobile page must have at least one mobile form, and each mobile form can have a number of mobile controls.

Note that mobile pages can have multiple mobile forms. This is due to the nature of mobile devices. Mobile devices have small screens and it is very normal to navigate between screens with a simple link.
Automatic Paging

.NET Mobile supports automatic paging for different mobile devices.

The paging is handled differently for each control. For example when paging takes place the controls included in a panel control will stay together.
Displaying Text

This mobile page uses a TextView control to display a large amount of text:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>



This is a very long text to demonstrate
how text can be displayed over several screens.
This is a very long text to demonstrate
how text can be displayed over several screens.
This is a very long text to demonstrate
how text can be displayed over several screens.
This is a very long text to demonstrate
how text can be displayed over several screens.



When this page is displayed on a mobile device, the navigation and display functions of the page will be compiled differently for different devices with different display characteristics.

When the text is displayed on a pocket PC with a small display, the user will be able to scroll the text with a scroll bar, but on a cell phone the text will be displayed over several screens with proper navigation tools added.

Note that all mobile controls must have the runat attribute set to "server", in order to secure proper rendering of the page for different devices.
Single Forms

This mobile page has one form:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>


Hello W3Schools



Multiple Forms

This mobile page has two forms:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>


Hello W3Schools

2




Hello Again

1



.NET Mobile Events

Mobile Controls exposes device independent programmable events.
Programming Events

Mobile controls have an object model with programmable properties, methods and events.

For a complete overview please refer to the reference section.
Submitting Text

This page has two forms:
<%@ Page
Inherits="System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>




Age?








When a page has two forms, the first form is always opened by default.

The first form has a label with the text "Age?", an input box to input the age, and a submit button.

The second page is activated by the submit button on the first page, and displays a response.

When the application runs on a mobile device, the two pages will display like this:

Form 1
Age?




Form 2
You are 11 years old








.NET Mobile Input

Input Controls are used to collect input from the mobile user.
Input Controls

There is a number of mobile controls that support user input.

The most common input control is perhaps the TextBox control, which was demonstrated in the previous chapter. The TextBox control is perfect for simple user input like names, numbers, identifications and keywords.

For larger amount of input a TextView control is a better choice. The TextView control allows long multi-line input like the one you need for SMS or other messages.
Numeric Input

The numeric attribute of the textbox control can be set to true or false to specify whether the textbox should accept only numeric input.

Note: This behavior will normally work on cell phones by changing the input mode from letters to numbers. For HTML browsers however, this behavior is normally not supported.
Password Input

The password attribute of the textbox control can be set to true or false to specify whether the textbox should be treated as a password field.

A password field will hide the input by displaying * (stars) instead of ordinary text.
List Controls

TextBox and TextView controls are well suited for entering input, but sometimes you want the user to select from a list of predefined values.

The SelectionList Control supports drop down lists, check boxes and radio buttons. This topic is covered in another chapter.

The List Control supports selection from menus and lists. The List Control is covered in another chapter.

User Interface Controls

User Interface Controls are controls which display the user interface:

Name Function
Command Performs an action
Form Defines a container for mobile controls
Image Defines an image
Label Defines a text
Link Defines a hyperlink
List Defines a list
MobilePage Defines a container for mobile controls
ObjectList Defines a list of data objects
Panel Defines a container for other controls
SelectionList Defines a list to select from
StyleSheet Defines styles to be applied to other controls
TextBox Defines a single line input box
TextView Defines a multi-line input box

For a full control reference, including properties methods, events, and more examples, please look at the "Mobile Reference" page.

.NET Mobile Input Validation

Validation Controls are used to validate the data entered by a user.
Validation Controls

Validation controls are used to validate the data entered by a user.

Validation controls allow you to validate an input control (like a TextBox), and display a message when validation fails.

Each validation control performs a specific type of validation (like validating against a specific value or a range of values).

By default, page validation is performed when a command control is clicked. You can prevent validation when a control is clicked by setting the CausesValidation property to false.
Validating Input

This page has two forms:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>





ControlToValidate="age"
Type="Integer"
ValueToCompare="18"
Operator="GreaterThanEqual">
You must be at least 18


Age?


Submit







The first form has a label with the text "Age?", an input box to input the age, and a submit button.

The second page is activated by the submit button on the first page, and displays a response.

If the input validates as error, an error message is displayed.

When the application runs on a mobile device, the two pages will display like this:

Form 1
Age?




Form 2
You are 21 years old







The ValidationSummary Control

The previous example used a CompareValidator control to validate an input field. The field to validate was defined by the attribute ContolToValidate.

You can also use a ValidationSummary control with the attribute FormToValidate, to validate all the input of a form.

This way you can display a summary of errors instead of one error at the time.
Validation Controls Reference
Name Function
CompareValidator Compares two values
CustomValidator Provides custom validation
RangeValidator Validates a range
RegularExpressionValidator Validates an expression
RequiredFieldValidator Validates required data
ValidationSummary Displays a validation summary

.NET Mobile Lists

The Mobile List Control supports different input and display properties.
Selecting from a List

This page has two forms:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>




OnItemCommand="Show_Price">










The first form has a list of cars.

The second page displays a price. This page is activated when a car is selected on the first page.

When the application runs on a mobile device the two pages will display like this:

Form 1
Volvo
BMW
Audi


Form 2
Volvo=$30,000







.NET Mobile Selections

The SelectionList Control supports drop down lists, check boxes and radio buttons.
The SelectionList

This mobile page uses a SelectionList to let the user select a car:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>








OnClick="Car_Click" Text="Submit" />






When this page is displayed on a mobile device, the navigation and display functions of the page will be compiled differently for different devices with different display characteristics.

Fore some devices, like a handheld PC, it might display a dropdown list to choose from. For a cell phone it might display a list of options to select from.

.NET Mobile Images

.NET Mobile displays different types of images for different types of devices.
The Image Control

Different mobile devices have different display capabilities.

The Image Control allows the developer to specify different types of images for different types of devices.
Image Types

Some mobile devices will display GIF images. Other mobile devices will display BMP images or WBMP images. The Image Control allows you to specify different images for each preferred image type.

This mobile page displays an image:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>











When this page is displayed on pocket PC, a GIF image will be displayed. On a cell phone a WBMP image or a BMP image will be displayed, according to the characteristics of the cell phone.

.NET Mobile Utilities

Utility controls support complicated user interfaces with minimum of code.
The AdRotator Control

This mobile page displays different advertisements:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>


AdvertisementFile="advertisements.xml">



This is the ad file called "advertisements.xml":

&br version="1.0" ?>



image1.gif
image1.bmp
image1.wbmp
http://www.1.com
Visit 1



image2.gif
image2.bmp
image2.wbmp
http://www.2.com
Visit 2



image3.gif
image3.bmp
image3.wbmp
http://www.3.com
Visit 3




The Calendar Control

This mobile page displays a calendar:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>




OnSelectionChanged="CalChanged" runat="server" />






In this example a calendar is displayed in the first form. When the user select a date from the calendar, the selected date is displayed in a new form.
The PhoneCall Control

This mobile page will display the text "Tove's number" and dial the number (555) 555-5555 when the user selects the text:
<%@ Page
Inherits=
"System.Web.UI.MobileControls.MobilePage"%>
<%@ Register
TagPrefix="Mobile"
Namespace="System.Web.UI.MobileControls"
Assembly="System.Web.Mobile" %>



PhoneNumber="(555) 555-5555"
Text="Tove's number"
AlternateFormat="{0}" />



The attribute "AlternateFormat" has the value "{0}". This displays the text from the attribute "Text".

If you use the value "{1}" it will display the text from the attribute "PhoneNumber".

You can also use a construct like this: AlternateFormat="{0} is {1}". This will display the text "Tove's number is (555) 555-5555".

Utility Controls
Name Function
AdRotator Displays advertisements
Calendar Displays a calendar
PhoneCall Calls a telephone number

For a full control reference, including properties methods, events, and more examples, please refer to the "Mobile Reference" page.

ASP.NET Mobile Controls Reference

Main Mobile Objects

.NET Mobile supports three main objects:

* The Mobile Page
* The Mobile Form
* The Mobile Panel

The Mobile Page is the container for the application.

Each Mobile Page can have one or more Mobile Forms.

Each Mobile Form can have zero or more Mobile Panels.

Mobile Forms and Mobile Panels are used to group Mobile Controls.
Mobile Controls

Mobile Controls are grouped into:

* User interface controls
* Validation controls
* Utility controls

UI Controls

UI controls are controls that displays the user interface:

Name Function
Command Performs an action
Form Defines a container for mobile controls
Image Defines an image
Label Defines a text
Link Defines a hyperlink
List Defines a list
MobilePage Defines a base class for all mobile pages
ObjectList Defines a list of data objects
Panel Defines a container for other controls
SelectionList Defines a list to select from
StyleSheet Defines styles to apply to other controls
TextBox Defines a single line input box
TextView Defines a multi-line input box

Validation Controls

Validation controls are used to validate the data entered by a user:
Name Function
CompareValidator Compares the value of one input control to the value of another input control or to a fixed value
CustomValidator Allows you to write a method to handle the validation of the value entered
RangeValidator Checks that the user enters a value that falls between two values
RegularExpressionValidator Ensures that the value of an input control matches a specified pattern
RequiredFieldValidator Makes an input control a required field
ValidationSummary Displays a report of all validation errors occurred in a page

Utility Controls

Utility controls support complicated user interfaces with minimum of code:
Name Function
AdRotator Displays advertisements
Calendar Displays a calendar
PhoneCall Calls a telephone number


INTRODUCTION TO SQL

Introduction to SQL

SQL is a standard language for accessing and manipulating databases.
What is SQL?

* SQL stands for Structured Query Language
* SQL lets you access and manipulate databases
* SQL is an ANSI (American National Standards Institute) standard

What Can SQL do?

* SQL can execute queries against a database
* SQL can retrieve data from a database
* SQL can insert records in a database
* SQL can update records in a database
* SQL can delete records from a database
* SQL can create new databases
* SQL can create new tables in a database
* SQL can create stored procedures in a database
* SQL can create views in a database
* SQL can set permissions on tables, procedures, and views

SQL is a Standard - BUT....

Although SQL is an ANSI (American National Standards Institute) standard, there are many different versions of the SQL language.

However, to be compliant with the ANSI standard, they all support at least the major commands (such as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.

Note: Most of the SQL database programs also have their own proprietary extensions in addition to the SQL standard!
Using SQL in Your Web Site

To build a web site that shows some data from a database, you will need the following:

* An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
* A server-side scripting language, like PHP or ASP
* SQL
* HTML / CSS

RDBMS

RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

The data in RDBMS is stored in database objects called tables.

A table is a collections of related data entries and it consists of columns and rows.

SQL Syntax

Database Tables

A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data.

Below is an example of a table called "Persons":
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

The table above contains three records (one for each person) and five columns (P_Id, LastName, FirstName, Address, and City).
SQL Statements

Most of the actions you need to perform on a database are done with SQL statements.

The following SQL statement will select all the records in the "Persons" table:
SELECT * FROM Persons

In this tutorial we will teach you all about the different SQL statements.
Keep in Mind That...

* SQL is not case sensitive

Semicolon after SQL Statements?

Some database systems require a semicolon at the end of each SQL statement.

Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.

We are using MS Access and SQL Server 2000 and we do not have to put a semicolon after each SQL statement, but some database programs force you to use it.
SQL DML and DDL

SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition Language (DDL).

The query and update commands form the DML part of SQL:

* SELECT - extracts data from a database
* UPDATE - updates data in a database
* DELETE - deletes data from a database
* INSERT INTO - inserts new data into a database

The DDL part of SQL permits database tables to be created or deleted. It also define indexes (keys), specify links between tables, and impose constraints between tables. The most important DDL statements in SQL are:

* CREATE DATABASE - creates a new database
* ALTER DATABASE - modifies a database
* CREATE TABLE - creates a new table
* ALTER TABLE - modifies a table
* DROP TABLE - deletes a table
* CREATE INDEX - creates an index (search key)
* DROP INDEX - deletes an index


SQL SELECT Statement


This chapter will explain the SELECT and the SELECT * statements.
The SQL SELECT Statement

The SELECT statement is used to select data from a database.

The result is stored in a result table, called the result-set.
SQL SELECT Syntax
SELECT column_name(s)
FROM table_name

and
SELECT * FROM table_name

Note Note: SQL is not case sensitive. SELECT is the same as select.
An SQL SELECT Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the content of the columns named "LastName" and "FirstName" from the table above.

We use the following SELECT statement:
SELECT LastName,FirstName FROM Persons

The result-set will look like this:
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

SELECT * Example

Now we want to select all the columns from the "Persons" table.

We use the following SELECT statement:
SELECT * FROM Persons

Tip: The asterisk (*) is a quick way of selecting all columns!

The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Navigation in a Result-set

Most database software systems allow navigation in the result-set with programming functions, like: Move-To-First-Record, Get-Record-Content, Move-To-Next-Record, etc.

Programming functions like these are not a part of this tutorial. To learn about accessing data with function calls, please visit our ADO tutorial or our PHP tutorial.


SQL SELECT DISTINCT Statement

The SQL SELECT DISTINCT Statement

In a table, some of the columns may contain duplicate values. This is not a problem, however, sometimes you will want to list only the different (distinct) values in a table.

The DISTINCT keyword can be used to return only distinct (different) values.
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s)
FROM table_name

SELECT DISTINCT Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the distinct values from the column named "City" from the table above.

We use the following SELECT statement:
SELECT DISTINCT City FROM Persons

The result-set will look like this:
City
Sandnes
Stavanger


SQL WHERE Clause

The WHERE clause is used to filter records.
The WHERE Clause

The WHERE clause is used to extract only those records that fulfill a specified criterion.
SQL WHERE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator value

WHERE Clause Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons living in the city "Sandnes" from the table above.

We use the following SELECT statement:
SELECT * FROM Persons
WHERE City='Sandnes'

The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Quotes Around Text Fields

SQL uses single quotes around text values (most database systems will also accept double quotes).

Although, numeric values should not be enclosed in quotes.

For text values:
This is correct:

SELECT * FROM Persons WHERE FirstName='Tove'

This is wrong:

SELECT * FROM Persons WHERE FirstName=Tove

For numeric values:
This is correct:

SELECT * FROM Persons WHERE Year=1965

This is wrong:

SELECT * FROM Persons WHERE Year='1965'

Operators Allowed in the WHERE Clause

With the WHERE clause, the following operators can be used:
Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern
IN If you know the exact value you want to return for at least one
of the columns

Note: In some versions of SQL the <> operator may be written as !=


SQL AND & OR Operators


The AND & OR operators are used to filter records based on more than one condition.
The AND & OR Operators

The AND operator displays a record if both the first condition and the second condition is true.

The OR operator displays a record if either the first condition or the second condition is true.
AND Operator Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select only the persons with the first name equal to "Tove" AND the last name equal to "Svendson":

We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove'
AND LastName='Svendson'

The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes

OR Operator Example

Now we want to select only the persons with the first name equal to "Tove" OR the first name equal to "Ola":

We use the following SELECT statement:
SELECT * FROM Persons
WHERE FirstName='Tove'
OR FirstName='Ola'

The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes

Combining AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).

Now we want to select only the persons with the last name equal to "Svendson" AND the first name equal to "Tove" OR to "Ola":

We use the following SELECT statement:
SELECT * FROM Persons WHERE
LastName='Svendson'
AND (FirstName='Tove' OR FirstName='Ola')

The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes


SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set.
The ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set by a specified column.

The ORDER BY keyword sort the records in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

ORDER BY Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger

Now we want to select all the persons from the table above, however, we want to sort the persons by their last name.

We use the following SELECT statement:
SELECT * FROM Persons
ORDER BY LastName

The result-set will look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
4 Nilsen Tom Vingvn 23 Stavanger
3 Pettersen Kari Storgt 20 Stavanger
2 Svendson Tove Borgvn 23 Sandnes

ORDER BY DESC Example

Now we want to select all the persons from the table above, however, we want to sort the persons descending by their last name.

We use the following SELECT statement:
SELECT * FROM Persons
ORDER BY LastName DESC

The result-set will look like this:
P_Id LastName FirstName Address City
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Tom Vingvn 23 Stavanger
1 Hansen Ola Timoteivn 10 Sandnes


SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.
The INSERT INTO Statement

The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two forms.

The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)

The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

SQL INSERT INTO Example

We have the following "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to insert a new row in the "Persons" table.

We use the following SQL statement:
INSERT INTO Persons
VALUES (4,'Nilsen', 'Johan', 'Bakken 2', 'Stavanger')

The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger

Insert Data Only in Specified Columns

It is also possible to only add data in specific columns.

The following SQL statement will add a new row, but only add data in the "P_Id", "LastName" and the "FirstName" columns:
INSERT INTO Persons (P_Id, LastName, FirstName)
VALUES (5, 'Tjessem', 'Jakob')

The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob


SQL UPDATE Statement


The UPDATE statement is used to update records in a table.
The UPDATE Statement

The UPDATE statement is used to update existing records in a table.
SQL UPDATE Syntax
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
SQL UPDATE Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob

Now we want to update the person "Tjessem, Jakob" in the "Persons" table.

We use the following SQL statement:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes

SQL UPDATE Warning

Be careful when updating records. If we had omitted the WHERE clause in the example above, like this:
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'

The "Persons" table would have looked like this:
P_Id LastName FirstName Address City
1 Hansen Ola Nissestien 67 Sandnes
2 Svendson Tove Nissestien 67 Sandnes
3 Pettersen Kari Nissestien 67 Sandnes
4 Nilsen Johan Nissestien 67 Sandnes
5 Tjessem Jakob Nissestien 67 Sandnes


SQL DELETE Statement


The DELETE statement is used to delete records in a table.
The DELETE Statement

The DELETE statement is used to delete rows in a table.
SQL DELETE Syntax
DELETE FROM table_name
WHERE some_column=some_value

Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
SQL DELETE Example

The "Persons" table:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger
5 Tjessem Jakob Nissestien 67 Sandnes

Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.

We use the following SQL statement:
DELETE FROM Persons
WHERE LastName='Tjessem' AND FirstName='Jakob'

The "Persons" table will now look like this:
P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
4 Nilsen Johan Bakken 2 Stavanger

Delete All Rows

It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name

or

DELETE * FROM table_name

Note: Be very careful when deleting records. You cannot undo this statement!