Saturday, May 8, 2010

Exercise 13: Shopping cart specifications

Develop the class diagram for the following shopping cart specifications:

A shoppingCart object is only associated with one creditCard and customer and to items in itemToBuy object. Persistent customer information such as name, billing address, delivery address, e-mail address and credit rating is stored in the customer object. The credit card object is associated with a frequentShopper discount object, if the credit rating for the customer is good. The customer can make or cancel orders as well as add and delete items to the shopping cart product. The credit card object contains the secure method for checking that the charge is authentic.






Reference

Wikipedia. (2010). Class Diagram. Retrieved at 8 May, 2010, from http://en.wikipedia.org/wiki/Class_diagram

Wednesday, May 5, 2010

Workshop 6: Enjoying the Ride: Web framework alternatives, scalability and flexibility

Topic objectives

Upon the completion of this workshop, developers or managers should be able to:
· Discuss and analyse the latest Web framework technologies based upon experiences so far with Ruby on Rails
· Identify and evaluate challenges and opportunities concerning the use of the latest Web 2.0 technologies and to ‘benchmark’ (compare) other alternatives;
· Discuss and evaluate current Ruby on Rails framework and the alternative emerging technologies.
· Evaluate and devise scalability, flexibility, capacity planning and performance testing strategies for conducting e-commerce.
· Deploy Web 2.0 or later technology in their business environments such as the ideas and methods of the ‘RailsSpace’ approach to the OTBS
· Think critically and analytically when exposed to new technologies.
· Share your findings with your peers and examine what the other team is doing.

DEVELOPER’S THREAD (RED team)

To Do:

Developers may continue to build upon work with the OTBS using the topic reading to help with user registration and advanced login features from Hartl et al (2008). Some examples of work to do includes:

o generating a controller and an action by adding a method(s) to a controller;
o creating a view template for each action and to link to actions from views;
o using AJAX to improve the user experience;

Share your success by posting progress comments and links etc to the Developers sub-forum site that has been set up for the Red team.

Step 1: Create the OTBS application with mySQL as database in Rails.

C:\Ruby>rails OTBS –d mysql
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


Step 2: Modify the database.yml to point to database “Taxi”

development:
adapter: mysql
encoding: utf8
database: taxi
pool: 5
username: root
password:
host: localhost

test:
adapter: mysql
encoding: utf8
database: taxi
pool: 5
username: root
password:
host: localhost

production:
adapter: mysql
encoding: utf8
database: taxi
pool: 5
username: root
password:
host: localhost


Step 3: Generate the “User” model

C:\Ruby\otbs>ruby script/generate model user --skip-migration
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/user.rb
create test/unit/user_test.rb
create test/fixtures/users.yml


Step 4: Generate the “User” controller with views “login”, “private” and “register”

C:\Ruby\otbs>ruby script/generate controller user login private register
exists app/controllers/
exists app/helpers/
create app/views/user
exists test/functional/
create test/unit/helpers/
create app/controllers/user_controller.rb
create test/functional/user_controller_test.rb
create app/helpers/user_helper.rb
create test/unit/helpers/user_helper_test.rb
create app/views/user/login.html.erb
create app/views/user/private.html.erb
create app/views/user/register.html.erb


Step 5: Modify the login.html.erb, private.html.erb and register.html.erb as follows:


Step 6: Modify the user_controller.rb as follows





Step 7: Create the database name “Taxi” in mySQL and table name “Users” with “id” as the primary key, “user_name” and “password” fields





Step 8: Start the web server

C:\Ruby\otbs>ruby script/server
=> Booting WEBrick
=> Rails 2.3.5 application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2010-05-26 09:45:56] INFO WEBrick 1.3.1
[2010-05-26 09:45:56] INFO ruby 1.8.7 (2010-01-10) [i386-mingw32]
[2010-05-26 09:45:56] INFO WEBrick::HTTPServer#start: pid=4848 port=3000



Step 9: Verfiy if the project successful connecting the database by visiting http://localhost:3000/




Step 10: Visit http://localhost:3000/user/login. Click register to go to the register page to register new account for first logon.




Step 11: Type in User Name and Password and click REGISTER to verify the “adduser” controller


Step 12: Acknowledgement page checked for successful registration.



Step 13: Go mySQL to verify the new User Name and Password are created in the “User” table




Step 14: Type in a wrong User Name or Password to verify the “authenticate” function.




Step 15: Type in the correct User Name and Password and the taxi ordering page appears with greeting message “Welcome,




Step 16: After finish ordering a taxi, click logout to reset the session and redirect to login page with thank you message.





Reference

StackOverflow. (2010). Ruby on rails connection problem. Retrieved at 6 May, 2010, from http://stackoverflow.com/questions/1343500/ruby-on-rails-connection-problem

Devarticles. (2010). Ruby-on-Rails. Retrieved at 8 May, 2010, from http://www.devarticles.com/c/a/Ruby-on-Rails/Login-Systems-and-More-with-Ruby-on-Rails/

Visionmasterdesigns. (2010). Tutorial: Create a login system in Ruby on Rails Retrieved at May 8, 2010, from http://visionmasterdesigns.com/tutorial-create-a-login-system-in-ruby-on-rails/

Marklunds. (2010). Active Record Basics. Retrieved at 12 May, 2010, from http://marklunds.com/s5/rails101/html/active_record_basics.html

TheRegister. (2010). Ruby on Rails Part 2. Retrieved at 10 May, 2010, from http://www.theregister.co.uk/2006/07/17/ruby_rails_part2/


Sunday, May 2, 2010

Exercise 12: Modeling with UML or MVC?

Examine the Use Case in Figure 4 and explain the MVC architecture



Make Connection
Model: Logon model receives the logon command or enrollment command and pass to respective controllers.
View: Logon page which allow user to input the username and password or redirect new user to enrollment page.
Controller: The Logon Controller receives the user’s logon credential and verify if it is correct.

Lookup Books
Model: Books Lookup Model which receives the input from customer and pass to the Search Controller.
View: Search page which allows users to input the book name or author keyword. After searching, the result should be displayed in another view as a list with the most relevant and the latest on top.
Controller: The Search controller gets the search criteria and search the database with appropriate result and renders the result back to the result view page.

Shopping Cart
Model: Shopping Cart Model which receives the user’s book selection and pass to the Shopping Cart Controller.
View: Shopping cart page which allows users to checkout or take away the items in the shopping cart.
Controller: The Shopping Cart Controller receives the book selection and performs action either to checkout or get items removed from the cart.
If this is the customer’s first visit, it would pass the user to another controller to collect user’s information including the delivery address and payment details. Otherwise it would go straight to the checkout section.
If checkout command received, the items would be passed on to calculate transaction and verify the fund in user account. It would render the successful or fail transaction to let the user know the final status. Or if remove command executed, the controller would remove the selected items from the cart and render the updated list in the shopping cart.

Check Order Status
Model: The Status model gets user’s request and pass to the Check Order Status Controller.
View: Displays every item purchased and the status on whether it is processing or delivering.
Controller: The Check Order Status Controller would check for the database and renders the status to the view for the list of items purchased with the status details.

Friday, April 30, 2010

Exercise 11: TP monitors and transaction protocols

1. Give a description in your own words of the ACID properties of a transaction.

In computer science, ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably. The concept of ACID is to evaluate databases and application architecture. In the context of databases, a single logical operation on the data is called a transaction. For example, a transfer of funds from one bank account to another, even though that might involve multiple changes (such as debiting one account and crediting another), is a single transaction.

2. Describe a TP monitor environment. How can a TP monitor stop an operating system being overwhelmed?

TP monitor, short for transaction processing monitor, a program that monitors a transaction as it passes from one stage in a process to another. The TP monitor's purpose is to ensure that the transaction processes completely or, if an error occurs, to take appropriate actions.
TP monitors are especially important in three-tier architectures that employ load balancing because a transaction may be forwarded to any of several servers. In fact, many TP monitors handle all the load balancing operations, forwarding transactions to different servers based on their availability.



Reference

Wikipedia. (2010). ACID. Retrieved at 28 Apr, 2010, from http://en.wikipedia.org/wiki/ACID

Webopedia. (2010). TP monitor. Retrieved at 28 Apr, 2010, from http://www.webopedia.com/TERM/T/TP_monitor.html

Monday, April 26, 2010

Workshop 5: Admiring the scenery - Forms, AJAX screen layout and mobile interfaces

Topic objectives
• To reflect on what has been done so far with Ruby on Rails;
• To reflect on my role and decide to continue as EITHER a Developer OR as an IT infrastructure manager;
• To complete either the Developer’s Thread exercises or the IT Infrastructure manager’s Thread exercises below, according to my new role (NOT BOTH).
• To work with others in the same role via the subject forum or similar learning tool.
• To read and find out what those who chose the other role are doing each of the workshops 5 to 8 and discussing on the subject forum or learning tool.
• To be willing to change roles and share perspectives as developers learn from managers and vice versa.

DEVELOPERS THREAD (RED team)
• To create a Rails application framework with the WEBbrick or Mongrel Web server and:
o generate a controller and an action by adding a method(s) to a controller;
o create a view template for each action and to link to actions from views;
o use Rails for building applications with document requests, screen layouts and forms processing.
• To share your findings with others.

DEVELOPER’S THREAD

1. Introduction
By now you will have tackled the version problems with Rails and tools like InstantRails 2.0 and the scaffolding issues. Many developers get mixed up and annoyed to find that a tutorial does not match with changes to the framework or is for a different version. Even a lot of the Ruby language tutorials are years earlier than the first appearance of Ruby on Rails in 2005. Such lag is commonplace especially with new production tools like Ruby on Rails, so you need to work with a strategy to check each new resource and its version.

2. Building applications via document requests in Rails
The pre-packaged InstantRails 2.0 for Windows or Locomotive2 for MacOS can be treated as self-contained systems outside the Windows or MacOS environment, so interactions can be done via the Windows command (console) window or via the Terminal application in MacOS.

When you installed InstantRails, the “black I” symbol presents a menu which includes access to Rails Application>Open Ruby Console Window. This takes you to the command line in the base directory for issuing Rails commands. It is here that you add a new directory or folder for all your Rails applications. I call mine projects.

Inside the new projects folder, a new application is created. Lets us use the animals application from workshop 4. The new application animals is created within projects by the following command and Rails responds by creating files and directories:

C:\InstantRails\...\projects\>rails animals

The first folder of interest to examine here is app, which contains 4 sub-folders called models, views, controllers (according to the MVC architecture of a Rails application) and helpers which contains methods for helping with building the application.

Other folders of interest are script which contains more Ruby scripts to perform a variety of services, the most important script being generate as it is used to create the stub of an application controller and public which holds the HTML forms. The controller class can have methods added to perform certain actions. Each action or method such as forms processing, document requests or database editing will in turn require a view template.


To Do:
Part A: Viewing the action

1. Create the Rails application framework in the projects folder: C:\InstantRails\...\projects\>rails animals

C:\Ruby>rails animals
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

2. Running the application on localhost:3000 using the WeBrick ruby server (or Mongrel as alternative) and access via Web browser at http://localhost:3000/

C:\Ruby\animals>ruby script/server
=> Booting WEBrick
=> Rails 2.3.5 application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2010-05-23 13:48:59] INFO WEBrick 1.3.1
[2010-05-23 13:48:59] INFO ruby 1.8.7 (2010-01-10) [i386-mingw32]
[2010-05-23 13:48:59] INFO WEBrick::HTTPServer#start: pid=176 port=3000



3. Create the controller to make the application do an action. This is under the controller-action/model-view structure.

Stop the WEBrick server each time you edit Ruby classes and then re-start or refresh the views you are testing. Use the Ruby command below:

>ruby script/generate controller Mammal

The mammal_controller.rb contains just a bare class description:

class MammalController


and the ApplicationController class inherits from ActionController::Base class in the ActionController module under Rails.


C:\Ruby\animals>ruby script/generate controller Mammal
exists app/controllers/
exists app/helpers/
create app/views/mammal
exists test/functional/
create test/unit/helpers/
create app/controllers/mammal_controller.rb
create test/functional/mammal_controller_test.rb
create app/helpers/mammal_helper.rb
create test/unit/helpers/mammal_helper_test.rb


4. Test the controller by starting the WEBrick server and navaigatibng the browser to http://localhost:3000/mammal Note how the controller name is appended to the end of the URL and that no action resulted because there are no controller methods.








5. Create an action by editing and saving the mammal_controller.rb class in projects\animals\app\controllers using your text editor to add the method below:

class MammalController<>





6. Start the WEBrick server and browse at http://localhost:3000/mammals/breathe where you will get a “missing template” message since it is missing a view for the breathe method.


Rails is trying to connect the breathe method action of the mammal controller to a view, by using the action’s name – breathe. This view template is created as breathe.rhtml and stored in the \projects\animals\views\mammal directory.

7. Create and save a view in that directory by using a text editor to create a view called breathe.rhtml


Restart the WEBrick server and browse again at http://localhost:3000/mammals/breathe



8. Try Ruby code and HTML in the action view by using the wrapper around the inserted Ruby code. Here are some snippets to try from workshop 4:



NOTE: in practise you normally perform calculations in the action (method) and pass the results to the view.







Part B: The active view: passing data from an action too a view

1. Create a new application called scenery in the same projects directory to demonstrate the use of an active view.

> rails scenery
> cd scenery

C:\Ruby>rails scenery
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

C:\Ruby>cd scenery

C:\Ruby\scenery>


2. Create a controller called Demo in scenery\app\controllers
scenery> ruby script/generate controller Demo

C:\Ruby\scenery>ruby script/generate controller Demo
exists app/controllers/
exists app/helpers/
create app/views/demo
exists test/functional/
create test/unit/helpers/
create app/controllers/demo_controller.rb
create test/functional/demo_controller_test.rb
create app/helpers/demo_helper.rb
create test/unit/helpers/demo_helper_test.rb


3. Add an action to demo_controller.rb as the method called rubycobe


class DemoController<>

end




4. Add a view template - scenery\app\views\demo\rubycode.rhtml
We will edit this view in later steps but you may like to add your own test HTML code to the view at this stage.



5. Save and restart the Web server and navigate to http://localhost:3000/scenery/rubycode


6. Use the Time.now example to pass data from an action to a view.



7. Modify and save the rubycode action with a value for the time instance variable in the DemoController class in app\controllers\demo_controller.rb

class DemoController< time_now =" Time.now">
end
end



8. Then modify and save the corresponding view template in \app\views\demo\rubycode.rhtml by adding a call by reference to the action’s instance variable:



9. Restart the Web server and navigate the browser to http://localhost:3000/demo/rubycode



Data has been passed from the action to the view as it is done with SQL requests. The instance variables of a Ruby class are available to view templates by referencing the action’s instance variables by name in the view .rhtml template.





Part C: Screen layouts and forms processing with text fields, check boxes, radio buttons and multiple list controls

1. Create a new application called cabs in the same projects directory to demonstrate the use of an active view.

> rails cabs
> cd cabs

C:\Ruby>rails cabs
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

C:\Ruby>cd cabs

C:\Ruby\cabs>


2. Create a controller called Vehicle in cabs\app\controllers
cabs> ruby script/generate controller Vehicle

C:\Ruby\cabs>ruby script/generate controller Vehicle
exists app/controllers/
exists app/helpers/
create app/views/vehicle
exists test/functional/
create test/unit/helpers/
create app/controllers/vehicle_controller.rb
create test/functional/vehicle_controller_test.rb
create app/helpers/vehicle_helper.rb
create test/unit/helpers/vehicle_helper_test.rb


3. Add an action to vehicle_controller.rb as the method called cabtype
class VehicleController< id="BLOGGER_PHOTO_ID_5475605928490243650" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 190px; TEXT-ALIGN: center" alt="" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFFTsvLg4uUKFpBH4n3lbi1tWFcujLnn3hXJZl69ViaYjGnMC4XX1bOKcOpbILNKQL_0mcCfdY09jCT4Z1Ml_cOFLHhwmlYO6eyznKZ2Vwfcg89DsfBeTkavpqWUuJ149uanMzRuLpVANe/s320/wk5_p17.JPG" border="0">

4. Add a view template - cabs\app\views\vehicle\cabtype.rhtml We will edit this view in later steps but you may like to add your own test HTML code to the view at this stage.



5. Save the view and restart the Web server and navigate to http://localhost:3000/cabs/cabtype



6. Create a file in the public directory - \cabs\public called input.html



7. Edit the vehicle_controller.rb here is a start. The data in each form element in the Rails application can be accessed via its name and a hash called params

class VehicleController< data1 =" params[:text1]" data2 =" params[:check1]" data3 =" params[:radios1]" data4 =" params[:building1]" id="BLOGGER_PHOTO_ID_5475608956186520114" style="DISPLAY: block; MARGIN: 0px auto 10px; WIDTH: 320px; CURSOR: hand; HEIGHT: 154px; TEXT-ALIGN: center" alt="" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGixhYi0cAUsPc_bGU8F5dtw3oE7hd07l91-bnzKHtwsEjddGB3N7ZHDgw1bOhgule9bokSQdEH8NdFDrJvue26krI8gmuookk124OpRU_VV_HCNs6xrdOgyy9gGQ-h-o7s9go7w6UKa9L/s320/wk5_p21.JPG" border="0">
8. Edit the view template cabtype.rhtml




9. Start the Web server and go to the opening page of this application at http://localhost:3000/input.html





10. Submit the forms data. What do you find?



How it works

When you use the params method in Rails, it implements the details of the parameter hash to be changed without breaking existing code. For example, the params hash for radios1 will contain the value of the radio button and the data is extracted in the cabtype action. With the multiple list box example in Rails, using the select controls, the params hash of building1 is an associative array (dictionary) holding the users multiple selections and is not just a drop-down list.

Rails supports other HTML controls for forms processing via text fields, check boxes, radio buttons and list select controls etc. As an example start_form_tag abd stop_form_tag as well as methods for each item such as the create field method text_field_tag

11. Report your progress or findings in your Developers Blog.

The controller cannot perform any action until the application_controller.rb inserted with following entry:
Protect_from_forgery :only => [create, :update, :destroy]

And with the following commented:
#protect_from_forgery

The input.html not function properly until the follow is modified:

form action =”vehicle/cabtype”


Saturday, April 24, 2010

Exercise 10: Concurrency and Threading demonstration in Python

1. Find definitions for eight terms and concepts used in threaded programming:

1. Thread Synchronisation
Thread synchronization refers to the act of shielding against multithreading issues such as data- races, deadlocks and starvation. You have to determine properly the objects and methods to synchronize as failure to do so would lead to situations like deadlocks

2. Locks
In computer science, a lock is a synchronization mechanism for enforcing limits on access to a resource in an environment where there are many threads of execution. Locks are one way of enforcing concurrency control policies.

3. Deadlock
Deadlock is where the threads stop responding, each waiting for the other to complete

4. Semaphores
A semaphore is a protected variable or abstract data type that constitutes a classic method of controlling access by several processes to a common resource in a parallel programming environment. A semaphore generally takes one of two forms: binary and counting. A binary semaphore is a simple "true/false" (locked/unlocked) flag that controls access to a single resource. A counting semaphore is a counter for a set of available resources. Either semaphore type may be employed to prevent a race condition.

5. Mutex (mutual exclusion)
Mutual exclusion (often abbreviated to mutex) algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections. A critical section is a piece of code in which a process or thread accesses a common resource. The critical section by itself is not a mechanism or algorithm for mutual exclusion. A program, process, or thread can have the critical section in it without any mechanism or algorithm which implements mutual exclusion.

6. Event
Events includes all sensor outputs or user actions (mouse clicks, key presses) or messages from other programs or threads.

7. Waitable timer
A waitable timer object is a synchronization object whose state is set to signaled when the specified due time arrives. There are two types of waitable timers that can be created: manual-reset and synchronization. A timer of either type can also be a periodic timer.



2. A simple demonstration of the threading module in Python (threaddemo.py) that uses both a lock and semaphore to control concurrency is by Ted Herman at the University of Iowa. The code and sample output below are worth a look. Report your findings.

threaddemo.py
# Create a bunch of threads, let each do some work, wait until all are done
import random
import threading
import time
# This takes about n/3 seconds to run (about n/3 clumps of tasks, times
# about 1 second per clump).
numtasks = 10
# no more than 3 of the 10 can run at once
# create a semaphore bounded up to 3
sema = threading.BoundedSemaphore(value=3)
# create a Read Lock
mutex = threading.RLock()
# running is a global variable to keep track
# of how many threads are running
running = 0
# the TestThread class is a subclass of threading.Thread,
# so it should supply the standard methods: run, ...
class TestThread(threading.Thread):
def run(self):
# tell python we access the global variable
global running
# introduce a random delay between 0 and 2
delay = random.random() * 2
print 'task', self.getName(), 'will run for', delay, 'sec'
# first, wait on the semaphore (limited to three threads)
sema.acquire()
# but only one of these three at a time should update
# the running variable
mutex.acquire()
running = running + 1
print running, 'tasks are running'
# release lock so another can update "running"
mutex.release()
# now sleep for a while (yawn....zzzzzzz)
time.sleep(delay)
# after wakeup, say we are done
print 'task', self.getName(), 'done'
# time to decrement "running"
mutex.acquire()
running = running - 1
print self.getName(), 'is finished.', running, 'tasks are running'
mutex.release()
# and finally, exit the group of three tasks
sema.release()
# main program: build and start all the threads
threads = []
# done in a function just for convenience
def starttasks():
for i in range(numtasks):
# show off Python's formatting feature
# by building a name for each thread
t = TestThread(name=""%i)
# add new name to list
threads.append(t)
# start thread
t.start()
starttasks()
print 'waiting for all tasks to complete'
# next statement waits for all threads to finish
for t in threads: t.join()
print 'all tasks done'


Here is the output window when you can run the threaddemo.py script:


PythonWin 2.3.2 (#49, Nov 13 2003, 10:34:54) [MSC v.1200 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - see 'Help/About PythonWin' for further copyright information.
>>> task will run for 0.120358615571 sec
1 tasks are running
task will run for 0.763990116379 sec
2 tasks are running
task will run for 0.207353153515 sec
3 tasks are running
task will run for 1.55806365714 sec
task will run for 0.776083733579 sec
task will run for 0.336440216469 sec
task will run for 1.55779500185 sec
task will run for 1.96896800957 sec
task will run for 1.57596561512 sec
task will run for 0.634052702735 sec
waiting for all tasks to complete
task done
is finished. 2 tasks are running
3 tasks are running
task done
is finished. 2 tasks are running
3 tasks are running
task done
is finished. 2 tasks are running
3 tasks are running
task done
is finished. 2 tasks are running
3 tasks are running
task done
is finished. 2 tasks are running
3 tasks are running
task done
is finished. 2 tasks are running
3 tasks are running
task done
is finished. 2 tasks are running
3 tasks are running
task done
is finished. 2 tasks are running
task done
is finished. 1 tasks are running
task done
is finished. 0 tasks are running
all tasks done

After examining the code and the output, I discovered that there are 10 threads (from 0 to 9) executed with no more than 3 tasks (controlled by semaphore) could run at the same time. Those threads are introduced with random delays (0-2 seconds) and the running variable is locked by the mutex until there are less than 3 tasks running and could release to other threads. The program ends until all threads are finished running.


Reference

C Sharp Corner. (2010). Multithreading Part 3: Thread Synchronization. Retrieved at 24 Apr, 2010, from http://www.c-sharpcorner.com/UploadFile/mmehta/Multithreading311162005045743AM/Multithreading3.aspx

Wikipedia. (2010). Semaphore (programming). Retrieved at 24 Apr, 2010, from http://en.wikipedia.org/wiki/Semaphore_(programming)

Wikipedia. (2010). Event-driven programming. Retrieved at 25 Apr, 2010, from http://en.wikipedia.org/wiki/Event-driven_programming

MSDN. (2010). Waitable Timer Object. Retrieved at 26 Apr, 2010, from http://msdn.microsoft.com/en-us/library/ms687012(VS.85).aspx

Wikipedia. (2010). Lock (computer science). Retrieved at 26 Apr, 2010, from http://en.wikipedia.org/wiki/Lock_(computer_science)

Tuesday, April 20, 2010

Exercise 9: Electronic payments and security

1. Find out about SET and the use of RSA 128-bit encryption for e-commerce.

SET stands for Secure Electronic Transaction which is a standard protocol developed by SETco, led by VISA and MasterCard

RSA 128-bit is to employ an asymmetric encryption system in public-key cryptography. It is the first algorithm know to be suitable for signing as well as encryption, and was one of the first great advances in public key cryptography. RSA is widely used in electronic commerce protocol and is believed to be secure given sufficiently long keys and the use of up-to-date implementations.

2. What can you find out about network and host-based intrusion detection systems?

Network intrusion detection system (NIDS) is an independent platform that identifies intrusions by examining network traffic and monitors multiple hosts. In a NIDS, the sensors are located at choke points in the network to be monitored, often in the demilitarized (DMZ) or at network borders. The sensor captures all network traffic and analyzes the content of individual packets for malicious traffic.

While the host-based intrusion detection system (HIDS) consists of an agent on a host that identifies intrusions by analyzing system calls, application logs, file-system modification (binaries, password files, capability/ACL databases) and other host activities and state

3. What is ‘phishing’?

Phishing is the criminally fraudulent process of attempting to acquire sensitive information such as usernames, passwords and credit card details by masquerading as a trustworthy entity in an electronic communication.

Communication purporting to be from popular social web sites, auction sites, online payment processors or IT administrators are commonly used to lure the unsuspecting public. Phishing is typically carried out by email or instant messaging, and it often directs users to enter details at a fake website whose look and feel are almost identical to the legitimate one.

4. What is SET and how does it compare to SSL as a platform for secure electronic transaction? Is SET in common use?

SET is a standard protocol for securing credit card transactions over insecure networks. SET was intended to become the standard of payment method on the Internet between the merchants, the buyers and the credit-card companies. However, it failed to win market share for its cost and complexity which needs to install client software. It also requires client-side certificate distribution.

Secure Socket Layer (SSL) is cryptographic protocols that provide security for communications over networks such as Internet. SSL encrypts the segments of network connections at the Transport Layer end-to-end. Comparing to the low cost and simplicity of SSL, SET failed to win the market share.

5. What are cookies and how are they used to improve security? Can the use of cookies be a security risk?

Cookies which are know as web cookies, browser cookies and HTTP cookies, is a text string stored by a user’s web browser. A cookie consists of one or more name-value pairs containing bits of information, which may be encrypted for information privacy and data security purpose.

Cookies are supposed to be stored and sent back to the server unchanged, an attacker may modify the value of cookies before sending them back to the server. If, for example, a cookie contains the total value a user has to pay for the items in their shopping basket, changing the value exposes the server to the risk of making the attacker pay less than the supposed price. The process of tampering with the value of cookies is called “cookie poisoning”, and is sometimes used after cookie theft to make an attack persistent.

6. What makes a firewall a good security investment? Accessing the Internet, find two or three firewall vendors. Do they provide hardware, software or both?

A firewall is a dedicated appliance, or software running on a computer, which inspect network traffic passing through it, and denies or permits passage based on a set of rules. There are several techniques employed by firewall that makes it a good security device:

 Packet filter: Packet filtering inspects each packet passing through the network and accepts or rejects it based on user-defined rules.
 Application gateway: Applies security mechanisms to specific applications, such as FTP an Telnet servers. This is very effective but may impose performance degradation.
 Circuit-level gateway: Applies security mechanisms to specific applications, such as FTP or UDP connection is established. Once the connection has been made, packets can flow between the hosts with further checking.
 Proxy server: Intercepts all messages entering and leaving the network. The proxy server effectively hides the true network addresses.

The two big firewall vendors are Cisco, Checkpoint. They provide both hardware firewalls and software firewall applications.

7. What measures should e-commerce provide to create trust among their potential customers? What measures can be verified by the customer?

The most common security measures to establish trust among their potential customers are digital signatures and certificates.

Digital signatures meet the need for authentication and integrity. To vastly simplify matters, a plan text message is run through a hash function and so given a value: the message digest. This digest, the hash function and the plan text encrypted with recipient’s public key is sent to the recipient. The recipient decodes the message with their private key, and runs the message through the supplied has function to that the message digest value remains unchanged.

Sensitive information has to be protected through at least three transactions:

 Credit card details supplied by the customer, wither to the merchant or payment gateway. Handled by the server’s SSL and merchant/server’s digital certificates.
 Credit card details passed to the bank for processing. Handled by the complex security measures of the payment gateway.
 Order and customer details supplied to the merchant, either directly or from the payment gateway/credit card processing company. Handled by SSL, server security, digital certificates.

8. Get the latest PGP information from http://en.wikipedia.org/wiki/Pretty_Good_Privacy
The use of digital certificates and passports are just two examples of many tools for validating legitimate users and avoiding consequences such as identity theft. What others exist?

PGP which stands for Pretty Good Privacy is a computer program that provides cryptographic privacy and authentication. PGP is often used for signing, encrypting and decrypting emails to increase the security of email communications. Other than digital certificates and passports, there are some tools that can help users to avoid identity theft:

 Verification Engine – it is an easy tool to provide an extra layer of protection which double checks websites’ digital certificates. It checks to ensure that the name that the certificate was issued to matches the name in the web address.
 Stronger Authentication – dual authentication is a way to verify that you are logging onto the correct website. You will need to answer some additional question if you try to log on from a different location. This is called a security seal to help customers avoid pharming or phishing attacks.
Another kind of strong two-factor authentication is the one-time password token now being offered by PayPal. The key chain-sized token generates a 6-digit number that is used in combination with a user ID and password to log on to the account, which makes it very difficult for phishers to gain access to an online account.
 Security toolbars – it works as part of your web browsers which block fraudulent sites and allow users to easily report suspicious sites.
 Anti-Spyware and Anti-Rootkits – it searches and destroys any free software that identifies the most common kinds of software that track your online activity and helps you to remove them. It can also avoid your computer from remote hacker to control your machine.


Reference

Wikipedia. (2010). Secure Electronic Transaction. Retrieved Apr 18, 2010, from http://en.wikipedia.org/wiki/Secure_Electronic_Transaction

Wikipedia. (2010). RSA. Retrieved Apr 18, 2010, from http://en.wikipedia.org/wiki/RSA

Wikipedia. (2010). Intrusion Detection System. Retrieved Apr 18, 2010, from http://en.wikipedia.org/wiki/Intrusion_detection_system

Wikipedia (2010). Transport Layer Security. Retrieved Apr 20, 2010, from http://en.wikipedia.org/wiki/Transport_Layer_Security

Wikipedia. (2010). HTTP cookie. Retrieved Apr 20, 2010, from http://en.wikipedia.org/wiki/HTTP_cookie

Wikipedia. (2010). Firewall (Computing). Retrieved Apr 20, 2010, from http://en.wikipedia.org/wiki/Firewall_(computing)

Ecommerce –Digest.Com. (2010). Ecommerce Security Issues. Retrieved Apr 21, 2010, from http://www.ecommerce-digest.com/ecommerce-security-issues.html

Phishinginfo.org. (2010). Tips and Tools for Avoiding Online Identity Theft. Retrieved Apr 22, 2010, from http://www.phishinginfo.org/tips.html