Sunday, April 4, 2010

Workshop 5 - Part A

This particular Workshop gives us the choice to either carry on the role as a developer or swap to being an IT infrastructure manager. I have chosen to carry on the role as a developer as i am finding the use of Ruby on Rails to be quite interesting and useful to my current career.

Part A: View the action


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



















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/




















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
















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 ac
tion by editing and saving the mammal_controller.rb class in projects\animals\app\controllers using your text editor to add the method below:

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.










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
































(The output to the webpage for the Inhale and Exhale)

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:

Workshop 4 - Riding the Rails with Ruby

Now down to some actual ruby coding. This workshop provided an insight into the actual code of ruby with some great examples. It contrasted the various styles of java vs ruby in syntax, with some coding examples to figure out in ruby.

To Do
What are the syntax differences in the way that Ruby and Javascript use the If statement?


To code an If loop in javascript the following syntax is used:


if (object = condition)
{
'code to be executed
}

Whereas Ruby would use the following syntax:

if object = condition
'code to be executed
end
The differences are as follows:
  • javscript must contain the condition rule within brackets ()
  • javscript must have contain open and close {} squiggly line brackets for code to be executed
  • javascript uses else if
  • ruby doesn't need to have brackets around the condition
  • ruby doesn't need to contain {} squiggly line brackets for encapsulation of the code to be executed
  • ruby uses an elsif instead of else if
  • ruby to close of the if statement uses and 'end'

While Ruby and Python are quite similar, can you find some similarities between Ruby and Javascript?
  • Both are based on object-orientated principles
  • Both languages are dynamically typed
  • Both pass objects by reference
  • Both languages are garbage collected, as in they have memory management


Challenge Problems
Now here comes the coding parts of the workshops...

1. Create and test a Ruby program called dognames.rb

Here is the code of my program dognames.rb, as you can see i take in a name variable and assign each item into the array, once the array has been defined i sort the array and output the result.

#!/usr/bin/ruby

puts "What is your dog name?"
$dog1 = gets

puts "What is your dog name?"
$dog2 = gets
puts "What is your dog name?"
$dog3 = gets
array = [$dog1,$dog2,$dog3]
puts "your dog name"
puts array.sort


Test 1: ('Pearl', 'Coco', 'Butch')
Result 1:










Test 2: ('Pearl', 'Andy', 'Butch')
Result 2:











Test 3: ('Pearl', 'Andy', 'Fifi')
Result 3:











2. Write a Ruby program called fizzbuzz.rb that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are
multiples of both three and five print "FizzBuzz".

Here is the code below to be able to produce the expected result using Ruby, as we can see there is a loop involved going upto the number 100, then conditional if statements to replace numbers with the words if met.

#!/usr/bin/ruby

def fizzbuzz
1.upto(100) do |i|
if i % 5 == 0 and i % 3 == 0

puts "FizzBuzz"

elsif i % 5 == 0

puts "Buzz"

elsif i % 3 == 0

puts "Fizz"
else
puts i
end
end
end
fizzbuzz


Output is as follows from the command prompt when executed.
























3. Compare the Ruby and Python versions of the dog years calculator
  • Ruby doesn't need brackets () for declaring a method.
  • Python used an input() method for capturing data entered via the keyboard.
  • Ruby used a gets method for capturing data via the keyboard.
  • Ruby uses if statement without : at the end of statement but Python uses it.
  • Ruby uses a puts method or operator for screen output but Python uses print.
  • Python must have a main function in order for the program to run.

Workshop 3 - MySQL and Database Design

1. Setup the MySQL tools on your computer. Setup of MySQL tools was relatively easy, all that was needed was to download the tool from the MySQL site and run the default setup configuration install. Once install the application just needed to be launched.





















2. Setup InstantRails and setup a new application directory for each of your web application projects.

InstantRails was an easy setup as this has all the necessary components needed to run ruby on rails. However, there was an issue for myself and running WAMPServer on the same machine as this also installed all the necessary components such as MySQL, Apache which conflicted with InstantRails. So I made an executive decision and went with setting up ROR on WAMP, which proved to be a little difficult at first but runs fine now.

3. Once Rails is running at http://localhost:3000, you need to configure database access. To start the internal webserver of WEBrick is pretty straightforward. What you needed to run is a command prompt from Windows and browse to the top directory of your newly created web application in Ruby. Once there you need to run this command to instantiate WEBrick 'ruby script/server'. This kicks of the local webserver running under a different port of the machine and serves various requests from that port (3000) which you can see below from the screen shots.













Going to http://localhost:3000/ in Firefox Web browser, shows this form which means the WEBrick webserver is operational and ruby is working correctly.






















To configure the database(s) for the web project. Yes database(s) as this creates a set of similar database configurations (i.e. one being the development one, testing one, and production one). These are stored in the config/database.yml file. When setting up the project however an explicit command needs to be run when creating the project in Rails so that the database.yml is setup to connect to a real MySQL database locally and not the SQLlite db it normally creates in the database.yml. This command is exactly the same as the creating the ruby project however there is one extra option which defines to use MySQL instead of SQLLite. 'rails OTBS -d mysql' This will update the database.yml file accordingly, and all thats needed to be done to the file is update it if you have any special security logins for the databases. Below is a screen shot of the database.yml i created of the Online Taxi Booking System.























4. Generate the Passenger model by creating the MySQL database and 'passengers' table from the information above.

To generate the passenger model in rails you can use the command scaffolding to do this.

ruby script/generate scaffold Passenger name:string contact_number:string
suburb_origin:string street:string street_number:string building:string
suburb_destination:string passenger_number:string taxi_type:string
date:date time_required:integer

Once the model has been created you need to run the command 'rake db:create' from the command line which will create the database into MySQL.

After the database has been created you need to create the table based on the scaffold generation of passengers. To do this run this command 'rake db:migrate', which will create the passengers table and populate it with all the fields specified earlier in the scaffold c
ommand.








Workshop 2 - Model View Controller design approach

Seeing how the previous workshop went into great detail of the MVC history and design pattern and how it works within Rails. I won't go into great detail of what it is, but only how Rails implements it.

1. How is Rails structured to follow the MVC pattern?

Ruby on Rails is based on the MVC design paradigm (as i said before). It implements this design pattern by breaking up the newly created
application into its separate parts as seen here in the image below: Once you have all the necessary components installed, go to the command line and run rails [projectname] command. This will create a new application directory structure which adheres to the principals of MVC.












As we can see Rails has created a directory call app which contains all the sub-components of the application (i.e. Views, Models, and Controllers). This helps to keep the distinct parts of the application separate, and easier to manage if and when the application becomes big.

























2. Apply the MVC design approach to our Project: Online Taxi Booking System.

To apply the MVC design approach to our Online Taxi Booking System is quite straightforward in Rails. First you need to create the application which was executed in the previous step. Next is to create Views, Models, and Controllers for the application. The way to do this is quite simple by using the command of ruby script/generate scaffold [object] which basically generates each component (i.e. View, Model, and Controller) for the object and places each item in the designated app folder of the projects directory.

As you can see the taxi object was created with all the corresponding model, view, and controller created as well.


Workshop 1 - Setting up the model railway

Well i managed to download InstantRails but what i found out is that it directly impacts with WAMPServer which i was using before for the PHP and MySQLAdmin exercises. Seeing as i didn't want to uninstall WAMPServer just to get Instant Rails running, i decided to get RubyOnRails running within WAMPServer. This took a bit of time, but i eventually found a website which helped me to setup WAMPServer and RubyOnRails to work as one. http://stmogilny.wordpress.com/2008/11/24/setting-up-ruby-on-rails-with-wamp/

I have created my first RubyOnRails application through the command line, and have begun work on the online taxi system.

Responses to Challenge Questions:

1. Make a list of all programming languages and Web development tools used by you in prior experiences. Describe what you know about Web application frameworks before we begin.

I have just moved away from the web development space of my career into business analysis, but some of the languages and frameworks i have used are as follows: C#.NET, VB.NET, PHP, Perl, Python, Javascript. In terms of web application frameworks, the main one i have used extensively is .NET 2.0, which is more than a web framework, but a whole entire development framework (for both web client apps and windows client apps)

Development framework such as .NET is there to support the developer in providing the common framework to produce applications alot easier and faster, by alleviating the need for the developer to create the most common functions most web and windows client applications need (i.e. session management, database access, security the list goes on)

Ruby on Rails i have heard of but not really had much to do with when i was working as a developer, But im really looking forward to moving into this space and to learn alot about this particular framework.

2. Ruby is “an interpreted scripting language” for quick and easy object-oriented programming”. Find out about the Ruby language and discover what this means.

At this very moment in time there are 2 categories of programming languages: one being interpreted scripted language and the other being compiled language. Ruby is an interpreted scripted language that relies on a piece of software/program which interprets the executing code in which it translates it to machine code for the computer to understand. Compiled languages such as C and C++ must be compiled into machine code before they can be executed, meaning no use for a interpreter as the running code is already readable by the machine executing it.

With both these types there are however advantages and disadvantages with each one:

Advantages of Interpreted Scripting
Language
1. Platform independence
2. Can change a specific part of code without full recompilation of the code

Disadvantages of Interpreted Scripting Language
1. Slower than compiled as the code needs to be interpreted before being executed by the host machine

Advantages of Compiled Language
1. Faster than interpreted languages as the code is compiled to machine code, and no need for interpretation

Disadvantages of
Compiled Language
1. Changing a specific part in code requires a full recompilation before it can be used.

Object orientated programming (OOP) is a programing paradigm that uses "objects" - data structures consisting of datafields and methods together with their interactions - to design applications and computer programs ("Wikipedia", 2010a). Ruby is a fully-fledged object orientated language as all items that you create at runtime are objects which have attributes and behaviours on which actions can be performed.

This gives Ruby really the best of both world, one being interpreted which makes it quick to update and change and machine independent. But also all the benefits of OO which has all the benefits of inheritance, encapsulation etc. This is the reason why Ruby is so powerful as its focus is on simplicity through easy to read code, but also has its roots in making development easier and faster through OO and interpreted scripting language features.

3. What is Rails and how does it work with Ruby?

Whilst i understand the .NET framework, i believe the Rails Framework to be something very similar for Ruby. According to Tatum (2003), Ruby on Rails or ROR for short is a web application framework that uses logical steps to help create workable code for the creation of websites. Ruby on Rails uses a design pattern called MVC (Model-View-Controller) to help benefit the developer by guiding them to a design pattern which is applicable to web applications. This helps the developer because they dont need to erect all the scaffolding of the application or have to completely code every aspect of their application as rails provides a blueprint of a website with all common functionality.

Basically, Rails provides the architecture of web applications from which developers can build their Ruby applications much faster and easier.

4. What is meant by “convention over configuration” in regards to the use of Rails in Web application development?

Convention over configuration is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility (Wikipedia, 2010b). This is very apparent in Rails as it enforces a naming convention that maps database table names to programming classes. An example of this is a table named Cars, then the associated class will be named Car. This means a programmer can rely on the default of naming conventions built into Rails, which inturn also speeds up development and prototyping as the developer is not wasting precious time on convention and configuration, but actual code for the web application.

5. When did Model-View-Controller begin and where is it used?

Model View Controller or MVC for short was invented at Xerox Parc in 1978 by Trygve Reenskaug. The first implementation of this approach was implemented in SmallTalk-80. The reason for this particular type of pattern was to solve the general problem of giving users control over their information as seen from multiple perspectives (Reenskaug, n.d). Here is a website i found about the author Trygve Reenskaug

Currently in most web applications out there MVC is the most widely used architectural pattern for a majority of the websites out on the internet and intranets of corporations.

6. Describe the steps involved with the MVC design approach.

The MVC architectural pattern is one that breaks up an application into 3 distinct parts: model, view, and controller.

Controller - The controller itself is used for handling events that either affect the model or the view.
View - The Views are for displaying all or a portion of the data to the user.
Model - The models are for maintaining data

There is a good explaination of the inner workings of the MVC pattern on eNode


References

Wikipedia (2010a) http://en.wikipedia.org/wiki/Object-oriented_programming
Malcolm Tatum (2003)
http://www.wisegeek.com/what-is-ruby-on-rails.htm
Wikipedia (2010b) http://en.wikipedia.org/wiki/Convention_over_configuration
Reenskaug (n.d.) http://heim.ifi.uio.no/~trygver/index.html

Exercise 6 - Web form design and processing: A basis for e-commerce interaction

1. Design the form
'Retrofit' the form data string above:
name=Evan+Burke&card=Visa&number=844326134489554&order=French+perfume


Below is the code for the retrofitted form in HTML which captures all the items listed above. The editor which was used to design the HTML code was Notepad++:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Order Cosmetics Here!</title>
</head>
<body>


<h1>Online Cosmetics</h1>
<p>
Please fill out the form below to purchase your choice of cosmetic.</p>
<p>
<form name="perfume" action="cgi-bin/anyform.py" method="POST">
<table>

<tr>
<td><label for="name" />Name:</td>
<td><input type="text" name="name" size="40" /></td>
</tr>
<tr>
<td><label for="card" />Card Type:</td>
<td><select name="card">
<option>Mastercard</option>
<option selected="selected">Visa</option>
<option>American Express</option>

</select>
<p /><label for="number" />Number: <input type="text" name="number" size ="40" /></td>
</tr>
<tr>
<td><label for="order" />Products</td>
<td><select name="order">
<option selected="selected">French perfume</option>
<option>Skin Care</option>
</select></td>
</tr>
<tr>
<td colspan="2"><p /><input type="submit"
name="submit" value="Click to Order!" /></td>
</tr>
</table>


</form>
</p>
</body>
</html>




















2. Write the script which processes the forms data. Read the code and list the steps involved in processing the form.


After some research on the internet i came across a generic python script which processes all the form data posted to it, and re-displays it in HTML to the browser.

Setup of CGI Python Script
1. To use the python script you must configure cgi on the apache webserver
2. You must install the python libraries to the machine
3. Place python script in designated cgi-bin directory of apache

Call CGI/Python Script from HTML page to process the form
1. Must change method in the FORM tag to 'POST'
2. Change the action in the 'FORM' tag to "cgi-bin/anyform.py"
3. Ensure in the python script the local python libraries are imported at the start of the script using this line of code at the very beginning if windows '#!c:/Python26/python.exe -u' and if unix '#!/usr/local/bin/python'

How the Python script works
1. Looks at all the forms data using the function 'cgi.FieldStorage()' which gathers all the form data
2. Sorts out all the form data by key names 'nameList = form.keys() nameList.sort()
3. Loops through each of the form items, and displays the value associated with each of the form items.
4. Once this is complete the HTML is the rendered back to the webserver then onto the browser for display to the client.



Below is the script which was gathered from http://infohost.nmt.edu/tcc/help/lang/python/anyform.txt and modified to work on a Windows machine:

#!c:/Python26/python.exe -u
#--
# anyform.cgi: Generic Python CGI forms handler
#--

import cgi # Main CGI handler

def valueCheck(form, name):
""" This function should be called once for each named element
on the form. It will display the element name and the value
or values. The (name) argument is the element name.

The `form' argument is a dictionary where the keys are the
names of the items, and each item is either:
- If there is only value for a single name, the item is
an object whose .value member is the text of the item; or
- If there are multiple values for the name, the item is
a list of objects whose .value members are the item texts.
"""
if form.has_key(name): # Is there an item for this name?
item = form[name] # Yes, get the item (or list of items)
if type(item) is list: # Is it a list of containers?
#--
# List: display in brackets with commas. First form
# the list of .value attributes from item, then
# concatenate them with commas between them and
# brackets around them.
#--
valueList = [i.value for i in item]
text = "[%s]" % ", ".join(valueList)
else: # Single value
text = item.value
print "%s = %s<br>" % (name, `text`)
else: # No value: say so
print "%s is undefined<br>" % name

#--
# Main program starts here
#--

form = cgi.FieldStorage() # Get the form object

print "Content-type: text/html" # Print the required header for HTML
print # Blank line to signify end of headers

print "<html>"
print "<head>"
print " <title>Results of your form submittal</title>"
print "</head>"
print "<body>"
print "<h1>Results of your form submittal</h1>"

print "<p>Here are your results:\n<p>"

nameList = form.keys()
nameList.sort()
for name in nameList:
valueCheck(form, name)

print "</body>"
print "</html>"

3. Can you modify the script to process the form?

In regards to modification of the script, this can be easily done as the code resides on the your local web server. The modifications which can happen to this file depends on the requirements of the HTML form. Some examples include saving the form data to a database, a flat file, emailing the data to a certain email address, or instantiating another process. These are just a few of the modifications which can occur to this particular python script, it just depends on the requirements needed.

4. Improve the user experience by adding a Javascript feature.

The javascript function i added to the form involves the shaking/resizing of the submission button, below is the script which must be added to the header of the HTML form:

<SCRIPT LANGUAGE="JavaScript">

pos = 15;
TO = null;
function shake_funct2(object,speed)
{
obj = eval(object)
txt = clear_space(obj.value);
if (pos == 15)
{
txt = txt + " ";
pos = -15;
}
else
{
txt = " " + txt;
pos = 15;
}
obj.value = txt;
obj.style.width = parseInt(obj.style.width) + pos;
obj = object
sp = speed
TO = setTimeout("shake_funct2(obj,sp)",speed);
}

function clear_space(text)
{
while (text.substring(0,1) == " ")
{
text = text.substring(1,text.length);
}
while(text.substring(text.length-1,text.length) == " ")
{
text = text.substring(0,text.length-1);
}
return text;
}

function end_shake_funct2(object)
{
clearTimeout(TO);
obj = eval(object);
txt = clear_space(obj.value);
obj.value = txt;
//alert(pos);
if (pos == -15)
{
obj.style.width = parseInt(obj.style.width) +15;
}
pos = 15
}
// End -->
</script>




Last but not least the onmouseover and onmouseout event must be populated on the submit button as per below:


<input type="submit" name="submit" value="Click to Order!" style="font-size:10;width:150"onmouseover="shake_funct2(this,100)" onmouseout="end_shake_funct2(this)" />


Saturday, April 3, 2010

Exercise 5 - Database Servers

Case Study B (PHP, MySQL, PHPMyAdmin Tool)

In this particular exercise I went with Case Study B which was with PHP and MySQL. At first getting PHP and Apache running on a Windows machine was quite frustrating when installing separately. But i came across a tool which embedded MySQL, Apache, PHP and PHPMyAdmin together called WAMPSERVER, and this was alot easier to get up and running on my machine.

1.







2.







3.








4.






5a.









5b.











5c.








5d.









Findings

Most of the exercises were staright forward. Setting up of the machine was a bit of a nightmare, however once i found WAMPServer all was fine. The only issues i came across in the exercises were to do with PostBack values not being picked up as these had to either be declared using $_POST[x] or $_GET[x] which worked better than $myvariable.