Monday, October 18, 2010

Craeting First application in rails

First of all navigate to the folder where we wanted to create our application in console then in the console paste the above command

mathew@mathew Aptana RadRails Workspace]$ rails cric

The result will be as below

[mathew@mathew Aptana RadRails Workspace]$ rails cric

create

create app/controllers

create app/helpers

create app/models

create app/views/layouts

create config/environments

create config/initializers

create config/locales

create db

create doc

create lib

create lib/tasks

create log

create public/images

create public/javascripts

create public/stylesheets

create script/performance

create test/fixtures

create test/functional

create test/integration

create test/performance

create test/unit

create vendor

create vendor/plugins

create tmp/sessions

create tmp/sockets

create tmp/cache

create tmp/pids

create Rakefile

create README

create app/controllers/application_controller.rb

create app/helpers/application_helper.rb

create config/database.yml

create config/routes.rb

create config/locales/en.yml

create db/seeds.rb

create config/initializers/backtrace_silencers.rb

create config/initializers/inflections.rb

create config/initializers/mime_types.rb

create config/initializers/new_rails_defaults.rb

create config/initializers/session_store.rb

create config/environment.rb

create config/boot.rb

create config/environments/production.rb

create config/environments/development.rb

create config/environments/test.rb

create script/about

create script/console

create script/dbconsole

create script/destroy

create script/generate

create script/runner

create script/server

create script/plugin

create script/performance/benchmarker

create script/performance/profiler

create test/test_helper.rb

create test/performance/browsing_test.rb

create public/404.html

create public/422.html

create public/500.html

create public/index.html

create public/favicon.ico

create public/robots.txt

create public/images/rails.png

create public/javascripts/prototype.js

create public/javascripts/effects.js

create public/javascripts/dragdrop.js

create public/javascripts/controls.js

create public/javascripts/application.js

create doc/README_FOR_APP

create log/server.log

create log/production.log

create log/development.log

create log/test.log

This will create a bunch of files as given above.So our next step to navigate to that project folder by giving the below command.

mathew@mathew Aptana RadRails Workspace]$ cd cric/

Inorder to check whether rails applicaion is set to work use the below command to start the server

[mathew@mathew cric]$ script/server

You can see this results on the console panel

[mathew@mathew cric]$ script/server

=> Booting WEBrick

=> Rails 2.3.4 application starting on http://0.0.0.0:3000

=> Call with -d to detach

=> Ctrl-C to shutdown server

[2010-10-18 15:33:16] INFO WEBrick 1.3.1

[2010-10-18 15:33:16] INFO ruby 1.8.6 (2007-09-24) [i386-linux]

[2010-10-18 15:33:16] INFO WEBrick::HTTPServer#start: pid=3435 port=3000

Since there is no error on console u can check the application by goin through this url http://localhost:3000/

The following screen appears infront of you

Craeting First application in rails

For all those who are beginner in programming aim to show Hallo world first,so lets also begin like that. So first of all lets start by creating controller Also our main aim is to create a team management system so we need to create a table to store the name of the team along with their ids.So the first step is to write a model called team.So go to the projects folder and run this below script to create a model for team.

mathew@mathew cric]$ script/generate model team

If the model is created successfully the following sub folders should be also createdas below

exists app/models/

exists test/unit/

exists test/fixtures/

create app/models/team.rb

create test/unit/team_test.rb

create test/fixtures/teams.yml

create db/migrate

create db/migrate/20101021043114_create_teams.rb

As a result of this migrations are created so what we need is to run a migration by mentioning the fields of the table teams in the migration file as below

class CreateTeams < limit ="">32
t.string :group, :limit =>32

t.timestamps
end
end

def self.down
drop_table :teams
end
end

After making proper changes to migrations save the migrations and we need to rake the migration in order to create the table called "teams".So use the below command to rake the migration

[mathew@mathew cric]$ rake db:migrate

If the migration is a successful one the result will be like this as below

[mathew@mathew cric]$ rake db:migrate

(in /home/mathew/Aptana RadRails Workspace/cric)

== CreateTeams: migrating ====================================================

-- create_table(:teams)

-> 0.2117s

== CreateTeams: migrated (0.2126s) ===========================================

So table is created,our next step is to print "hallo world",i think i had forgotten that, so next we need to create a controller to write our first method through which i can show you hallo world

Inorder to create a controller use the below command on the console,here admins is the name of the controller

mathew@mathew cric]$ script/generate controller admins

If it is created successfully we will get the below result on the console

mathew@mathew cric]$ script/generate controller admins

exists app/controllers/

exists app/helpers/

create app/views/admins

exists test/functional/

create test/unit/helpers/

create app/controllers/admins_controller.rb

create test/functional/admins_controller_test.rb

create app/helpers/admins_helper.rb

create test/unit/helpers/admins_helper_test.rb

Then open the routes.rb and make an entry like this below

map.resources :admins

This is where exact mapping take place.

Then go to the controller and write one method called index as given below
def index
puts"jasssssssssssssssssssssssssssssss"
end

Then create a view file called index.html.erb and write a label like this

>label<Hallo world>/label<

Then start the server by giving the below command

[mathew@mathew cric]$ script/server

Then give the following link in browser ans see the result

http://0.0.0.0:3001/admins

rubyonrailshalloworldapplication

SO Our first second wish come true.

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.