Sunday, September 26, 2010

Three-Tier Architecture

In case of three-tier architecture all the three layers reside separately,either on the same machine or on different machine which is entirely different from single-tier and two-tier architecture.

Three-Tier Architecture

  • The user interface interacts with business logic
  • The business logic validates the data send by the interface and forwards it to the database if it confirms to the requirements
  • The front end interacts with business logic in turn interacts with the database

Two-Tier Architecture

In case of two-tier architecture, an application is broadly divided into two
  • Client:Implements the user interface
  • Server:Storage of data

In case of this architecture the user and data services are either on the same machine or on the different machines.In two-tier architecture,the business layers are implemented in either of the following methods:

Two-Tier Architecture

  1. Fat Client

    In this type of method business service layer is combined with user service layer.Clients execute the presentation logic and enforce business logic.server stores data and process transactions.this is used when server is loaded with transaction processing activities and is not equipped to process business logic

  2. Fat Server

    Here business service layer is combined with data service layer.As business service is stored on the server, most of the processing takes place on server.

  3. Dividing business services between the user and data services

    You can also implemented in such a way that business services are distributed between user and data services.Here processing of business logic is distributed between data and user services.

Single-Tier Architecture

Early we have discussed about the application architecture .On the basis of that we can explain what is single tier architecture?.In case of Single-tier architecture a single executable file handles all the functions relating to the user,business and data service layers.This is also called Monolithic application.

Single-Tier Architecture

Some of early COBOL programs using this architecture.

Types of Application architectures

Applications are developed to support the organisations in their business operations.Application receives input and accept it and process the data based on business rules and provides data as output.The functions performed by an application can be classified into three types
  1. User Service
  2. Business Service
  3. Data Service
  • User Service
This is regarded as the front end of the solution.This is also called presentation layer because it provides interactive user interface.
  • Business Service
It controls the enforcement of business rules of the data of an organisation. Business rules encircle those practices and activities that define the behaviour of an organisation. Eg: an organisation decides that the credit limit of all client cannot exceed $200000. Business service layer sets rules or validations to pertain these functions.This means the back end does not receive incorrect data
  • Data Service
It comprises the data and functions for manipulating this data.

These three layer form the base of models or architecture used in application development in an organisation.Applications can be

Wednesday, September 15, 2010

Active Record — Object-relation mapping put on rails

Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping.

Rails Active Record is the Object/Relational Mapping (ORM) layer supplied with Rails. It closely follows the standard ORM model, which is as follows:

  • tables map to classes,

  • rows map to objects and

  • columns map to object attributes

Rails Active Records provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.

Each Active Record object has CRUD (Create, Read, Update, and Delete) methods for database access. This strategy allows simple designs and straightforward mappings between database tables and application objects.

Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems:

  • lack of associations
  • lack of inheritance

By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach.

A short rundown of the major features are below, will be described in detail later
  • Automated mapping between classes and tables, attributes and columns.
  • Associations between objects controlled by simple meta-programming macros.
  • Aggregations of value objects controlled by simple meta-programming macros.
  • Validation rules that can differ for new or existing objects.
  • Callbacks as methods or queues on the entire lifecycle
  • Observers for the entire lifecycle
  • Inheritance hierarchies

Cross page posting in ASP.NET 2.0

Getting Control Values

The Page class exposes a property named PreviousPage. If the source page and target page are in the same ASP.NET application, the PreviousPage property in the target page contains a reference to the source page. (If the page is not the target of a cross-page posting, or if the pages are in different applications, the PreviousPage property is not initialized.) By default, the PreviousPage property is typed as Page. The following code example shows how you can get the value of the TextBox1 control on the source page.

if (Page.PreviousPage != null)
{
TextBox SourceTextBox =
(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
Label1.Text = SourceTextBox.Text;
}
}
}
The FindControl method finds controls in the current naming container. If the control you are looking for is inside another control (typically, inside a template), you must first get a reference to the container and then search the container to find the control you want to get. In the following code example, the source page contains a Login control with a LayoutTemplate container that in turn contains a TextBox control named UserName. The code gets the value of the UserName control.

Getting Public Property Values from the Source Page

To get public members of the source page, you must first get a strongly typed reference to the source page. You can do so in a number of ways. The first is to include an @ PreviousPageType directive in the target page, which allows you to specify the source page, as in this example:

<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

In the target page of a cross-page posting, you can also get the values of public members of the source page. The most common scenario is that the source page defines public properties and you want to get their values on the target page.

public String CurrentCity
{
get
{
   return textCity.Text;
}
}
If the target page contains a PreviousPageType directive that points to the source page, you can access the source page's CurrentCity property using code such as the following
Label1.Text = PreviousPage.CurrentCity;

Polymorphism in C#

  • When a message can be processed in different ways is called polymorphism."Poly" means many
  • When you derive a class from a base class, the derived class will inherit all members of the base class except constructors, though whether the derived class would be able to access those members would depend upon the accessibility of those members in the base class
  • C# gives us polymorphism through inheritance. Inheritance-based polymorphism allows us to define methods in a base class and override them with derived class implementations. Thus if you have a base class object that might be holding one of several derived class objects, polymorphism when properly used allows you to call a method that will work differently according to the type of derived class the object belongs to
  • It allows you to invoke methods of derived class through base class reference during runtime
  • It has the ability for classes to provide different implementations of methods that are called through the same name
Polymorphism is of two types:
  • Compile time polymorphism/Overloading
  • Runtime polymorphism/Overriding
Compile Time Polymorphism
  • Compile time polymorphism is method and operators overloading. It is also called early binding
  • In method overloading method performs the different task at the different input parameters
  • Use method overloading in situation where you want a class to be able to do something, but here is more than one possibility for what information is supplied to the method that carries out the task
  • You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing
Example
 using System;
namespace method_overloading

{
class Program
{
public class Print
{
public void display(string name)

{
Console.WriteLine("Your name is : " + name);
}

public void display(int age, float marks)

{
Console.WriteLine("Your age is : " + age);

Console.WriteLine("Your marks are :" + marks);
}
}

static void Main(string[] args)

{
Print obj = new Print();

obj.display("George");

obj.display(34, 76.50f);

Console.ReadLine();
}
}
}
Main points to be remembered while overloading are
  • If you use overload for method, there are couple of restrictions that the compiler imposes
  • The rule is that overloads must be different in their signature, which means the name and the number and type of parameters
  • There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name
Here is an example to overload multiple methods
using System;
namespace method_overloading_polymorphism
{
class Program
{
public class Shape

{
public void Area(float r)
{
  float a = (float)3.14 * r;

  // here we have used funtion overload with 1 parameter.

  Console.WriteLine("Area of a circle: {0}",a);
}

public void Area(float l, float b)

{
  float x = (float)l* b;

  // here we have used funtion overload with 2 parameters.

  Console.WriteLine("Area of a rectangle: {0}",x);

}
public void Area(float a, float b, float c)

{
  float s = (float)(a*b*c)/2;

  // here we have used funtion overload with 3 parameters.

  Console.WriteLine("Area of a circle: {0}", s);
}
}
static void Main(string[] args)
{
Shape ob = new Shape();

ob.Area(2.0f);

ob.Area(20.0f,30.0f);

ob.Area(2.0f,3.0f,4.0f);

Console.ReadLine();
}
}
}
Runtime Time Polymorphism
  • Runtime time polymorphism is done using inheritance and virtual functions. Method overriding is called runtime polymorphism
  • It is also called late binding.
Let's assume the following simple class hierarchy with classes A, B and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.

Inherited Methods

A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses

using System;
namespace Polymorphism
{
class A
{
 public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A {}

class Test
{
 static void Main(string[] args)
 {
     A a = new A();
     a.Foo();  // output --> "A::Foo()"

     B b = new B();
     b.Foo();  // output --> "A::Foo()"
 }
}
}
The method Foo() can be overridden in classes B and C:
using System;
namespace Polymorphism
{
class A
{
     public void Foo() { Console.WriteLine("A::Foo()"); }
}
class B : A
{
     public void Foo() { Console.WriteLine("B::Foo()"); }
}
class Test
{
   static void Main(string[] args)
   {
       A a;
       B b;
       a = new A();
       b = new B();
       a.Foo();  // output --> "A::Foo()"
       b.Foo();  // output --> "B::Foo()"
       a = new B();
       a.Foo();  // output --> "A::Foo()"
   }
}
}
There are two problems with this code.
  • The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section
  • Although the code compiles and runs, the compiler produces a warning: ...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'

This issue will be discussed in section Hiding and Overriding Methods.

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

using System;
namespace Polymorphism
{
class A
{
    public virtual void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
    public override void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
    static void Main(string[] args)
    {
        A a;
        B b;

        a = new A();
        b = new B();
        a.Foo();  // output --> "A::Foo()"
        b.Foo();  // output --> "B::Foo()"

        a = new B();
        a.Foo();  // output --> "B::Foo()"
    }
}
}

Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System;
namespace Polymorphism
{
  class A
  {
      public void Foo() { Console.WriteLine("A::Foo()"); }
  }

  class B : A
  {
      public new void Foo() { Console.WriteLine("B::Foo()"); }
  }

  class Test
  {
      static void Main(string[] args)
      {
          A a;
          B b;

          a = new A();
          b = new B();
          a.Foo();  // output --> "A::Foo()"
          b.Foo();  // output --> "B::Foo()"

          a = new B();
          a.Foo();  // output --> "A::Foo()"
      }
  }
}

Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:

class A
       {
           public void Foo() {}
       }

       class B : A
       {
           public virtual new void Foo() {}
       }


A class C can now declare a method Foo() that either overrides or hides Foo() from class B:

       class C : B
       {
           public override void Foo() {}
           // or
           public new void Foo() {}
       }

Object Data Source in c#

  • Create App_Code Folder in your Project root.
  • right-click on the App_Code and select Add->Add New Item to add a new DataSet called "Sample.xsd" to the project.
  • Double click on DataSet Sample.xsd . You will get a tool box for your Data set.
  • Grab a Table Adapter control .You may see another Table Adapter as shown below .
  • Create appropriate connection string or select already created one.
  • Click Next and tick Use Sql Statements and Write a Query to select the rows.You can use the Query Builder for automatic queries and check the results there itself.
  • Rename DataTable1 to Sample (for an example) . Which renames the adapter also.
  • After successful creation of the sql query which creates a Method by default say GetData().
  • Right-click on the App_Code and select Add->Add New Item to add a new Class file called "AssignValues.cs" to the project. Double Click on the class and create a method in it
public class AssignValues

{
public void Fill(GridView gdv)

{
gdv.ID = string.Empty;

SampleTableAdapters.MemberTableAdapter mtadptr = null;        

mtadptr = new SampleTableAdapters.MemberTableAdapter();

Sample.MemberDataTable dt=null;

dt=mtadptr.GetData();

gdv.DataSourceID=string.Empty;

gdv.DataSource=dt;

gdv.DataBind();
}

}
Explanation for the above code is given below Grid view is an object parameter you passing it from in which event you need to fill the data.Then creating an object of Sample data set dt and filling the data into it and bind it. After that you can make an instance of the class and call the method in any other c# code page of the Project files. Pass the parameter Grid View say GridView1 after grabbing a Grid view from the Tool Box.

Sunday, September 12, 2010

Don't repeat yourself

The DRY (Don't Repeat Yourself) Principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

This is regarded as the fundamental principle of rails development.The principle was formulated by Andy Hunt and Dave Thomas in The Pragmatic Programmer, and underlies many other well-known software development best practices and design patterns.Inorder to explain the principle in detail lets derive the following aspects

  • Duplication is waste

Every line of code that goes into an application must be maintained, and is a potential source of future bugs. Duplication needlessly bloats the codebase, resulting in more opportunities for bugs and adding accidental complexity to the system. The bloat that duplication adds to the system also makes it more difficult for developers working with the system to fully understand the entire system, or to be certain that changes made in one location do not also need to be made in other places that duplicate the logic they are working on. DRY requires that "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."

  • Repetition in process calls for automation

Many processes in software development are repetitive and easily automated. The DRY principle applies in these contexts as well as in the source code of the application. Manual testing is slow, error-prone, and difficult to repeat, so automated test suites should be used, if possible. Integrating software can be time consuming and error-prone if done manually, so a build process should be run as frequently as possible, ideally with every check-in. Wherever painful manual processes exist that can be automated, they should be automated and standardized. The goal is to ensure there is only one way of accomplishing the task, and it is as painless as possible.

  • Repetition in logic calls for abstraction

Repetition in logic can take many forms. Copy-and-paste if-then or switch-case logic is among the easiest to detect and correct. Many design patterns have the explicit goal of reducing or eliminating duplication in logic within an application. If an object typically requires several things to happen before it can be used, this can be accomplished with an Abstract Factory or a Factory Method. If an object has many possible variations in its behavior, these behaviors can be injected using the Strategy pattern rather than large if-then structures. In fact, the formulation of design patterns themselves is an attempt to reduce the duplication of effort required to solve common problems and discuss such solutions. In addition, DRY can be applied to structures, such as database schema, resulting in normalization.

Convention over configuration

This is actually coding by conventions.This software design paradigm which ensures the following things
  • This decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility
  • The developer only needs to specify unconventional aspects of the application for example if there is a class called user in the model then its curresponting table will be Users
General-purpose frameworks usually require one or more configuration files in order to set up the framework. A configuration file provides a mapping between a class and a resource (a database) or an event (a URL request). As the size and complexity of applications grow, so do the configuration files, making them harder to maintain.

A Valid example in rails is as below

An example should show you how the conventions work together: You have a database table called users with the primary key id. The matching model is called user and the controller, that handles all the logic is named users_controller. The view is split in different actions: if the controller has a new and edit action, there is also a new- and edit-view.

class NamesValidator

# Checks that first_name and last_name are within certain length
def self.valid_length?(name)
 name.first_name.length < 20 and name.last_name.length < 10
end

# Checks that first_name and last_name have the first character capitalized
# capitalize turns HELLO into Hello; hello into Hello; etc
def self.valid_case?(name)
 name.first_name == name.first_name.capitalize and
 name.last_name == name.last_name.capitalize
end

def self.non_conforming_method
 # This method will not be called during validation
end

end

class Name < Validatable

attr_accessor :first_name, :last_name # create getters and setters for instance variable name

def initialize(first_name, last_name)
 @first_name, @last_name = first_name, last_name
end

end

Name is just a simple class that has two fields: first_name and last_name. The NamesValidator has two class methods that check if the name is of valid length and if it has the right case. The method non_conforming_method is left there to show that our validation system does not call that method since it does not conform to the naming convention we agreed upon.

Saturday, September 11, 2010

The MVC Architecture (MVC)

I am happy to know that you all get a good knowledge about the rails Introduction post.So lets move to the working principle action in rails application Model–View–Controller (MVC) is a software architecture,currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" (the application logic for the user) from input and presentation (UI), permitting independent development, testing and maintenance of each.For instance, as depicted in the figure below, you may refer to "controller" as "input", "model" as "processor" or "processing" and "view" as "output". The MVC Architecture (MVC) So in other words, controller receives the input, passes it to the model for processing, or to the view for output. So MVC benefits include:
  • Isolation of business logic from the user interface
  • Ease of keeping code DRY
  • Making it clear where different types of code belong for easier maintenance
Let Us explain each in detail mentioning each functionalities

1) Model

A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.

2) View

The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. A viewport typically has a one to one correspondence with a display surface and knows how to render to it.

3) Controller

The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input.

The MVC Architecture (MVC)

So the steps involved in the working of MVC is as follows

  • The browser makes a request, such as http://rubyonrailslink.blogspot.com/2010/09/what-is-rails.html
  • web server (mongrel, WEBrick, etc.) receives the request. It uses routes to find out which controller to use: the default route pattern is “/controller/action/id” as defined in config/routes.rb. In our case, it’s the “video” controller, method “show”, id “15″. The web server then uses the dispatcher to create a new controller, call the action and pass the parameters.
  • Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”. They’re the pointy-haired manager that orders employees around. It gives orders without knowing (or caring) how it gets done. In our case, the show method in the video controller knows it needs to lookup a video. It asks the model to get video 15, and will eventually display it to the user.
  • Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting. In this case, the model retrieves video 15 from the database.
  • Views are what the user sees: HTML, CSS, XML, Javascript, JSON. They’re the sales rep putting up flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the controller gives them. They don’t know what exactly happening in the back room. In our example, the controller gives video 15 to the “show” view. The show view generates the HTML: divs, tables, text, descriptions, footers, etc.
  • The controller returns the response body (HTML, XML, etc.) & metadata (caching headers, redirects) to the server. The server combines the raw data into a proper HTTP response and sends it to the user.

Thursday, September 9, 2010

Ruby Introduction

  • Ruby was introduced by Yukihiro Matsumoto (known widely as “Matz”) in 1993
  • Ruby is a dynamic interpreted language which has many strong features of various languages
  • It is a strong Object oriented programming language which also has single inheritance as in Java
  • It also provides us with the feature called as mixins. Using mixins we can easily import methods from multiple classes using modules. Ruby also has the scripting feature similar to the Python and Perl
  • The Object oriented concept from C++ and Java also maintains the reliability of programming in addition to maintaining the security of code
  • Ruby is open source which means that it is free to be used; one does not need to pay anything to use it. Because of this feature of Ruby it is used worldwide by everyone
Ruby Introduction

Why learn Ruby

  • Ruby can easily recognize variable types all by itself. Due to this feature coders are not required to define variable types as we have to do in several other programming languages. Ruby's dynamic typing saves a lot of time for programmers
  • Ruby has been provided to programmers with various class libraries which are bundled together. These class libraries start from the basic data types to advanced level thread and network programming. These class libraries have not been saturated yet and Ruby still is in the process of getting more libraries with time to make programming more simple and efficient
  • Ruby also comes with an effective garbage collector which avoids the problem of memory leaks to a great extent and takes care of the misuse and unnecessary occupancy of the memory
  • Ruby provides us with familiar syntaxes which are known to C++,Eiffel, Perl, and Python programmers. These syntaxes are composed of all the common features available for the programming like the comments, identifiers, reserved words, literals, arrays, Regular expressions etc

Wednesday, September 8, 2010

What is Rails?

Rails is a web application development framework written in the Ruby language. It allows you to write less code while accomplishing more than many other languages and frameworks.Rails is opinionated software. It makes the assumption that there is a “best” way to do things, and it’s designed to encourage that way.

Some key points regarding rails is below

  • An extremely productive web-application framework.
  • Written in Ruby by David Heinemeier Hansson
  • You could develop a web application at least ten times faster with Rails than you could with a typical Java framework
  • An open source Ruby framework for developing database-backed web applications
  • Your code and database schema are the configuration
  • No compilation phase required

The Rails philosophy includes several guiding principles:

  • DRY – “Don’t Repeat Yourself” – suggests that writing the same code over and over again is a bad thing.
  • Convention Over Configuration – means that Rails makes assumptions about what you want to do and how you’re going to do it, rather than requiring you to specify every little thing through endless configuration files.
  • REST is the best pattern for web applications – organizing your application around resources and standard HTTP verbs is the fastest way to go.
This will be discussed in depth later.

Rails Strengths

Rails is packed with features that make you more productive, with many of the following features building on one other.

1) Metaprogramming

Other frameworks use extensive code generation from scratch. Metaprogramming techniques use programs to write programs. Ruby is one of the best languages for metaprogramming, and Rails uses this capability well. Rails also uses code generation but relies much more on metaprogramming for the heavy lifting.

2) Active Record

Rails introduces the Active Record framework, which saves objects to the database. The Rails version of Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming.

3) Convention over configuration

Most web development frameworks for .NET or Java force you to write pages of configuration code. If you follow suggested naming conventions, Rails doesn't need much configuration.

4) Scaffolding

You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need.

5) Built-in testing

Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run. Ruby can then execute all your automated tests with the rake utility.

6) Three environments

Rails gives you three default environments: development, testing, and production. Each behaves slightly differently, making your entire software development cycle easier. For example, Rails creates a fresh copy of the Test database for each test run.