Upload
sampetruda
View
2.299
Download
0
Tags:
Embed Size (px)
Citation preview
Web 2.0 OverviewAn Overview of the Evolution of the WWW
This course has been produced under the USAID Enterprise Development & Strengthening project
implemented by CHF International
Course Overview
Web 2.0 a concept, not a technology
Open Source and Agile Development Quick releases
AJAX Toolkits MS Atlas
Ruby on Rails Rapid Development and Prototyping
Course Schedule – Day 1Lecture Introduction to Web 2.0
Exercise In-Room ExperiencesLecture AJAX Introduction
Lunch Break
Lecture Debugging AJAXExercise Build a Web 2.0 SolutionLecture Microsoft .NET and Web 2.0
Breaks 10-15 minute breaks each hour1 Hour for Lunch
Course Schedule – Day 2
Lecture Infrastructure “2.0” and Open SourceExercise Rich Client User Interface - BankingLecture RubyLecture Ruby on rails
Lunch Break
Lecture Building an Application using RailsExercise Redesign your solution for Web 2.0Lecture “Ajaxifying” our Rails ApplicationLecture Wrap-Up, Web “3.0”, Humor
The Traditional Web - “1.0”
Mostly static pages Centrally controlled Traditional producer-consumer model Minimal Participation by the users Passive consumers Web “1.5”
More dynamic, data-driven content Some Flash-based rich clients
What is Web 2.0?
Web 2.0 is not AJAX! Not any particular technology
A new approach, attitude, way of thinking Coined by O’Reilly Media and MediaLive
Brainstorming session after the dot-com bubble burst Trying to figure out where the post-bubble web was headed
Web 1.x: Producer-Consumer
Producers live in the universe of the Consumers
Web 2.0: Consumer feeds self Producers create the universe in which Consumers feed
themselves
Forces Driving the Shift
Success of Free, Open Source Software (FOSS) Increasing user self-moderation Increasing need for collaboration over the internet Availability of Broadband (high-speed) connections
Proliferation of peer-to-peer networks Instant access to a large audience Rise of online communities and social networks
Technologies Driving the Shift
Open Source Languages, Formats, Protocols Freely available for anyone to setup a powerful website
Rich-Client platforms (AJAX, Flash) Proliferation of Broadband connections
Increasing demand for richer content More content digitally captured
Syndication (RSS, ATOM)
Web 2.0 Characteristics
Built on any platform (open or closed source) “Hackability”
Allows its functionality to be utilized in new ways by “hacking” through the code
Example: Google Maps Mashups
Experience is Emergent Users’ intentions are not predetermined Experience constantly tweaked based on feedback
Trust your users Trust users with content and moderation, and self-policing
Web 2.0 Characteristics
Loosely Coupled Open APIs exposed through Web Services
SOAP/REST
Modularized Specific Services can be leveraged
Example: Google API, AdWords API
Rich User Experience Rich-Clients using technologies such as AJAX, Flash, DHTML Design interfaces around high responsiveness Allow the user to actively participate in the growth of the site
Web 2.0 Characteristics
Constant Development Concept of a perpetual beta Flickr makes fun of this by calling their site a “gamma”
Not a Traditional Software Development Lifecycle Agile, quick iterations, constant redesigns and optimizations
Demo Website - Writely
Web-based Word Processor Purely a rich-client platform based on AJAX Allows for real-time, collaborative editing Built-in revision control with diff file capability
like a source control repository Export your document to open (PDF, RTF, HTML,
OpenOffice) and closed (MS Word) formats
Section Complete
Questions?
In-Room ExperiencesDescribe yourself and your Projects
Course Schedule – Day 1
Lecture Introduction to Web 2.0Exercise In-Room Experiences
Lecture AJAX IntroductionLunch Break
Lecture Debugging AJAXExercise Build a Web 2.0 SolutionLecture Microsoft .NET and Web 2.0
Tell us about…
Yourself Technical/Non-Technical Background
Project you have worked on Did it succeed/fail? Why?
Technologies and Platforms you have used Have your clients talked about Web 2.0?
AjaxFinally, we see some code!
Course Schedule – Day 1
Lecture Introduction to Web 2.0
Exercise In-Room Experiences
Lecture AJAX Introduction
Lunch Break
Lecture Debugging AJAX
Exercise Build a Web 2.0 Solution
Lecture Microsoft .NET and Web 2.0
What is AJAX?
Asynchronous JavaScript And XML AJAX isn’t one technology A combination of existing technologies
JavaScript, XML, and XHTML A naming concept similar to Dynamic HTML
HTML, JavaScript, CSS
Elements of AJAX
standards-based presentation using XHTML and CSS dynamic display and interaction using the document
object model data interchange and manipulation using XML and XSLT Asynchronous data retrieval using XMLHttpRequest JavaScript binding everything together.
History of AJAX
Microsoft created XMLHttpRequest Early AJAX Applications
Microsoft Outlook Web Access (Exchange 2000, 2003) MSNBC Polls
Other browsers gradually followed with native implementations
Opera Mozilla Firefox Apple Safari
Synchronous vs. Asynchronous
Synchronous vs. Asynchronous
What is Ajax a solution to?
Decreases bandwidth between client and server Most content is loaded only once
MacRumors.com Rumor site for Apple Computer’s products Live coverage of CEO Steve Jobs’ Keynote speeches 100,000+ unique users in a 1 hour span Everyone refreshes the page once a minute (if not more often) Estimated bandwidth, 196 GB (in about 2 hours) Moved live feed system to Ajax
Observed bandwidth usage drop to 32 GB, a 6x decrease
What is Ajax a solution to?
Roundtrips and delays Traditional HTTP requires a full roundtrip between the client-
server User has to wait longer
System is not as responsive Users prefer rich client applications for higher responsiveness
What is XMLHttpRequest?
A mechanism that allows for asynchronous GET and POST requests to the server
Minimal Feedback to the User Ideal for background tasks
Allows you to specify a callback method Handle changes in the state of the connection
Allows for multiple simultaneous connections Traditional synchronous browser model allows for only one
connection (browser threads initiate parallel connections to download images, but all happens only once during loading)
XMLHttpRequest - Methods
open(“method”, “URL”) Opens a request using the method (GET, POST) to URL
open(“method”, “URL”, async, username, password) Same as above, with optional arguments:
async – (boolean) to tell the browser to wait (or not) for a response username – username for the URL (if authentication required) password – password for the URL (if authentication required)
send(content) Initiates connection and sends DOM data or string
abort() Terminates HTTP Request
XMLHttpRequest - Methods
getAllReponseHeaders() Returns a delimited string of all the HTTP headers (names and values) from
the response Examples: Content-Type: text/html, Referer: <url>
getResponseHeader(“header”) Returns the value of the header (such as Content-Type)
setRequestHeader(“name”,”value”) Allows you to specify certain HTTP headers to send to the server
XMLHttpRequest - Properties
onreadystatechange The function invoked when the request status changes
status HTTP status returned from the server
200 OK, 404 Not Found, 500 Internal Server Error
responseText A raw string of all the response content
responseXML DOM Document of XML data returned
statusText Status text returned from the server
Creating a Request
Initialize the XMLHttpRequest object Slightly Simplified Version
if (window.XMLHttpRequest) { // Mozilla, Safari,
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
Creating a Request
Set the callback function Specifies which function to call when the request status changes
Write the callback function
http_request.onreadystatechange = myCallbackFunction;
function myCallbackFunction() {if (http_request.readyState == 4) { // everything is good, the response is received} else { // still not ready}
}
Request Status Codes
0 Uninitialized
1 Loading
2 Loaded
3 Interactive
4 Complete
Creating a Request
Check the response code of your requestfunction myCallbackFunction() { if (http_request.readyState == 4) { if (http_request.status == 200) { // perfect! } else { // there was a problem with the request } } else { // still not ready }}
Request Status Codes
200 OK
404 Not Found
500 Internal Server Error
Creating a Request
Retrieve the contents of the server’s responsehttp_request.responseText// will return the server response as a string of text
http_request.responseXML// will return the response as an XMLDocument object// you can traverse using the JavaScript DOM functions
Call the function
Send the request to the serverhttp_request.open(‘GET’,’page.htm’, true);http_request.send(null);
Data Exchange – XML
XHR designed to send and receive XML payloads Structured data (objects, not just primitives) Fully formed and valid xml document trees Built in parser can be used to validate structures
Data Exchange – JSON
JSON – Javascript Object Notation Text-based way of serializing objects
Platform-independent Easy use
Pass the serialized object string through eval() eval() returns the object
Data Exchange – Text
XHR can also be used to exchange plain text Response can be taken as one string Effective when no parsing is required Minimal overhead
Security and Limitations
Requests can only be made to the same domain
Not used to access web services because of lack of cross-domain access
IFRAMEs can be used to get around this limitation
Frameworks – Easy Ajax wrappers
Prototype Lightweight JavaScript library that allows for simplified Ajax
calls. Provides convenience, cleanup, etc Used in Ruby on Rails
All invocation code generated automatically
Frameworks – Backend (Java)
DWR – Direct Web Remoting (Java) Converts Java classes to JavaScript classes JavaScript code can be made to look like Java More like XML-RPC
Frameworks – Backend (.NET)
Microsoft Ajax Scripting Library (Atlas) Microsoft’s AJAX framework for ASP.NET Makes client/server calls
Generates all invocation code automatically Part of Visual Studio 2005, Web Developer Express We’ll cover more of this on Day 2
Ajax.NET Professional Third-party Ajax library for ASP.NET Minimal setup
Frameworks – Visual Effects
OpenRico Used by FiveRuns and other client libraries for effects
(BlindDown, Drag and Drop, etc) Script.aculo.us
Used by Ruby on Rails and Prototype for Drag ‘n Drop effects, and various PowerPoint slide transition-type effects (wipe, shrink, grow)
Moo.fx A super-lightweight (3kb file size) effects library that allows for
the building of custom effects too
Frameworks – Widget Toolkits
Zimbra Makers of a rich client “Outlook” type application Toolkit still in development (removing all zimbra-specific code
from the widget toolkit) Google Widget Toolkit (GWT)
Utilizes Java Swing-like methodology to build web-based Ajax widgets
Build classes and interfaces like you would in Swing GWT converts to Javascript and HTML code
Yahoo! User Interface Library
Drawbacks of AJAX
Browser Incompatibility Unless you use a toolkit, you have to worry about DOM
differences in each browser XMLHttpRequest Inconsistency
XHR is not standardized JavaScript Different Browsers have different implementations ActiveX Object in IE 5.x, 6 Native Object in Firefox, Opera, Safari, etc
Requires different initializations
Drawbacks of AJAX
Accessibility Breaks the traditional browser back button Problems with screen readers
Fallback to static pages What if JavaScript is disabled? What if ActiveX is disabled? Dual-development needed
Presentation and flow has to be duplicated and modified for a static page, non-Ajax page
Drawbacks of AJAX
Development Backend developers now need to know presentation logic Frontend developers/designers must have JavaScript skills
Debugging Difficult because you are debugging two languages Debugging two environments (Server, Client)
Drawbacks of AJAX
Limited Audience Only supported on modern browsers
XML, XSLT Javascript enabled ActiveX enabled (in the case of Internet Explorer 4 – 6)
Internet Explorer 7 makes XMLHttpRequest a native JS object Similar to Firefox, Safari, and Opera ActiveX will not be required for XHR from IE7 onwards
Demo Website - Flickr
Users (owners) can upload and organize photos Peer Reviewed Owner applies licensing (Creative Commons, etc) Rated by other users Users comment on each photo Users also tag photos
Rich Client (one of the best examples)
Flickr
Hackability Flickr has a robust API that allows for uploading, replacing, and
organizing photos http://www.flickr.com/services/api
Uses open formats SOAP/REST/XML-RPC API Kits in every major platform (.NET/Java/Perl/PHP/Ruby)
The key is for easy “mash-ups.” Others may come up with ideas to use Flickr that they couldn’t come up
with
Section Complete
Questions?
Debugging AjaxVarious tools that can help you develop with AJAX productively
Course Schedule – Day 1
Lecture Introduction to Web 2.0
Exercise In-Room Experiences
Lecture AJAX Introduction
Lunch Break
Lecture Debugging AJAX
Exercise Build a Web 2.0 Solution
Lecture Microsoft .NET and Web 2.0
DOM Inspectors
Internet Explorer IE Developer Toolbar
Released by Microsoft Allows you to traverse the DOM tree of any page loaded in IE Allows you to find where a DOM object is in the page (highlights the
object when you select it) Any values or attributes can be modified Allows developers to render/test on various resolutions
History of Tools
Old Javascript Debugging Tools Regular JavaScript Editors Notepad! Visual InterDev had some debugging TCP/IP proxy Our best friend, alert();
JS Debuggers
Firefox Javascript Console Part of all Firefox installations
Venkman (Firefox JS Debugger) Setting breakpoints Triggering breakpoints based on variable values and
exceptions Watching variable values Profiling of Javascript code
DOM Inspectors
Mozilla/Firefox Can be optionally installed as part of the Firefox developer
tools Very similar to IE’s DOM inspector (many identical features)
Traffic Monitors
Fiddler Tracks HTTP traffic between the client (browser) and server Can break down each request/response
HTTP Headers Session information HTTP Request data
Add breakpoints Request can be paused, modified, and resumed Great for debugging HTTP traffic
IDEs
Eclipse Ajax tools Eclipse Foundation Project to build tools to simplify Ajax
development VS.NET
Through “Atlas,” increased support for Ajax style development Powerful Javascript debugger provided by Microsoft
Demo Website - Digg
User-edited News site All articles are submitted by users Users vote on whether an article is
good/important/interesting More votes push an article up the ladder, eventually to
the front page Comments are also user-moderated
Good comments get a vote and are pushed up the comment chain
Section Complete
Questions?
Web 2.0 SolutionsBuild a web 2.0 style solution for a client
Course Schedule – Day 1
Lecture Introduction to Web 2.0Exercise In-Room ExperiencesLecture AJAX Introduction
Lunch Break
Lecture Debugging AJAXExercise Build a Web 2.0 Solution
Lecture Microsoft .NET and Web 2.0
Instructions
Discuss within your group for the time the instructor has given you to design a solution together based on the problem assigned to you
Present a high-level description of your solution that you would give to a business manager, not a technical person
Your clients… Group 1 - Newspaper wants to encourage more user
participation Group 2 - Ice Cream Store with 8 branches across the
country, would like to branches to collaborate in designing their brochures and notices
Group 3 - Investment bank wants to pool their researchers’ web resources together in a meaningful way
Group 4 - University wants a way that students can trade textbooks and other second-hand materials with each other
Microsoft .NET and Web 2.0Microsoft’s initiatives in Web 2.0 and Rich-Client development
Course Schedule – Day 1
Lecture Introduction to Web 2.0
Exercise In-Room Experiences
Lecture AJAX Introduction
Lunch Break
Lecture Debugging AJAX
Exercise Build a Web 2.0 Solution
Lecture Microsoft .NET and Web 2.0
Microsoft’s History with AJAX
XMLHttpRequest Microsoft invented it – they were early adopters Some of the earliest applications to use them
Microsoft Outlook Web Access (OWA) Microsoft Developer Network (MSDN) Library Tree-View MSNBC Live Voting (votes updated instantaneously)
Part of the MSXML libraries since 1998
Windows Live
Microsoft’s web strategy to deal with Google/Yahoo Web based rich client versions of popular windows
applications Windows Live Search Windows Live Mail
Ajax version of Hotmail (looks like Outlook 2003) Response to rich email clients like GMail and Yahoo
Windows Live Local (Beta, of course) Includes Microsoft Virtual Earth
.NET AJAX Development
A few robust frameworks available Different architectures and Implementations Allow for ASP.NET pages to use Ajax Integrate perfectly with Visual Studio.NET
Ajax.NET Professional Library
Available as a compiled library Steps for easy implementation
Add a reference in Visual Studio Wire up Ajax.NET Pro library in the Web.Config file
Add an HTTP Handler under <system.web>
<httpHandlers>
<add verb=“POST, GET” path=“AjaxPro/*.ashx” type=“AjaxPro.AjaxHandlerFactory,AjaxPro” />
</httpHandlers>
Ajax.NET Professional Library
Write a method to be called by the client, to perform certain steps and return output
Code-Behind Page Register the method as an Ajax-enabled method (available to
Ajax.NET pro) Add [AjaxPro.AjaxMethod] above the method
Tells AjaxPro to create a Javascript wrapper around that method
Main Page Call the method from Javascript
Microsoft “Atlas”
Microsoft’s Javascript-related tools Ajax Library and support functions
Library to support the generation of code that uses XmlHttpRequest for asynchronous operations
Browser-based components and widgets Similar to server-side components, but generated by the
browser as xhtml/javascript
Atlas’ Layers
Web Parts and Gadgets AtlasWebParts.js, GadgetRuntime.js
Component Model and UI Support for component based rich animations and effects, drag
‘n drop AtlasUIDragDrop.js
Source: Beginning Ajax with ASP.NET (beginningajax.com)
Atlas’ Layers
Base Class Library (BCL) Modeled after the .NET BCL Provides StringBuilder, Debug, Event, WebRequest,
WebResponse Provides support for ASP.NET services like authentication and
profile
Source: Beginning Ajax with ASP.NET (beginningajax.com)
Atlas’ Layers
Browser Compatibility Layer Abstracts support for browsers Eliminates (if browser == firefox) type code Supports various versions of IE, Firefox, Safari
Atlas’ Layers
Controls and Components Support for some Windows and Windows Live controls
converted to XHTML/CSS/JS ListView MapControl
Allows you to embed Microsoft Virtual Earth controls in your webpages
AtlasUIMap.js
Atlas’ Layers
Script Core Language extensions to Javascript Support for Namespaces, classes, interfaces, inheritance,
enumerations, delegates Brings JS closer to .NET in functionality and concept
Javascript Extensions Support for objects, functions, data types that are not natively
in Javascript
Client-Side Framework – Sarissa
sarissa.sourceforge.net Client-side Javascript library
Provides a browser-independent API for common JS tasks XML DOM manipulation XMLHttpRequest, XSLT, XPath Object serialization and deserialization
Why need an abstraction? Some browsers natively support these functionalities, others
don’t
Client-Side Framework – Sarissa
var xmlhttp = new XMLHttpRequest();
xmlhttp.open(“GET”, “http://www.YourServer.com/DataDocument.xml”, true);
xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4) alert(“Finished loading!”);}
xmlhttp.send(null);
XMLHttpRequest() is actually a sarissa class Abstracts creation between Firefox/IE/Safari
Client-Side Framework – Sarissa
Check for various browser features IS_ENABLED_SELECT_NODES
Whether the browser supports XPath queries IS_ENABLED_XMLHTTP
If we can use Ajax
Just one more thing… Demo
Microsoft Virtual Earth
Microsoft Virtual Earth
Rich client Mapping from Microsoft Includes “birds-eye views,” extremely hi-resolution
imagery of larger cities Drag ‘n drop Local Search Fully dynamic, allows user to store “notes”
Section Complete
Questions?
Infrastructure “2.0” andOpen SourceHow many Web 2.0 sites are hosted
Course Schedule – Day 2
Lecture Infrastructure “2.0” and Open Source
Exercise Web 2.0 Rich Client - Banking
Lecture Ruby
Lecture Ruby on rails
Lunch Break
Lecture Building an Application using Rails
Exercise Redesign your solution for Web 2.0
Lecture “Ajaxifying” our Rails Application
Lecture Wrap-Up, Web “3.0”, Humor
Goals of a good Infrastructure
Cost Adding more infrastructure should incur a minimal cost
Scalability Site should be designed from the ground up for scalability
Rapid Deployment Steps for deployment must be fast and easy, new iterations
can sometimes come out daily
Rapid Deployment - Facebook
Allowed users to track the movements of other users across the site
Seen as a Privacy Violation by thousands of users Many campaigns launched (inside Facebook) against the new
feature Facebook responded by quickly adding permissions
systems to control how much data is disclosed New features were deployed within days Users were happy!
“Big Iron” – the old way
Traditional, Monolithic Mainframes Name given to the traditional supercomputer systems
Everything centralized in one box Proprietary hardware
Very high quality Expensive Drivers developed/customized by Vendor
Proprietary/commercial administration products Highly customized and tuned OS Very high cost, due to R&D budgets required to develop
a line of Mainframes
“Little Iron” – the web 2.0 way
Highly decentralized clusters No master slave relationship “All nodes are equal,” except for load balancers, etc
No single point of failure If any server dies, the rest of the servers pick up the workload
Not designed to prevent failure Designed around acceptable rate of failure Software designed to retry if it encounters
If one server is “not available,” just send your request to another
“Little Iron” – the web 2.0 way
Use of commodity parts Standard “build your own” boxes from OEM parts
Standard x86 (or x86-64) Intel or AMD chips Google uses this for their entire cluster (~100,000 servers)
Open source OS (Linux/Unix) Fully customizable kernel, no license restrictions
Simplified Scalability Buy more servers and connect! An effective load balancer will automatically redistribute the
load when new nodes are added
“Little Iron” – the web 2.0 way
Extreme redundancy When servers fail, others pick up the workload since they are
all identical Maintainability
Instead of taking down the entire mainframe for maintenance, sections of the cluster can be upgraded
Zero Downtime By never taking down the entire cluster, the site is never down
for maintenance
Commercial Platforms
Advantages Products from same vendor work perfectly together Unified solution, solves many design challenges Little to no time spent getting pieces of a solution to
communicate with each other Staffing is easier (looking for people with a certain combination
of skills)
Commercial Platforms
Disadvantages Dependence on a single vendor
Patches, Updates, Official Support Constrained market – can not propose solutions where the
customer requires a different platform
Open Source Platforms
Advantages Use the best tool for each problem Vendors compete with each other Products are constantly improved Can fix-it-yourself (fill security holes, etc) Customize any level of the system to your own needs
Linux kernel being open source even allows you to customize the memory management
Open Formats and Protocols If a tool to perform a task is not available, you can build one
Open Source Platforms
Disadvantages Software will not always communicate well together Longer initial setup time Staffing - can be difficult to find people with a certain
combination of skills
Free/Open Source Licensing
Allows for the unrestricted use of software (usually free of charge)
Source Code is publicly available Many different licenses (vary in
restrictions for code disclosure MIT, GPL, LGPL, Apache, Ruby
GPL GNU Public License
Unrestricted commercial or non-commercial use Modifiable source code, as long as you publish changes
Richard Stallman
Free/Open Source Licensing
Source Code is publicly available Many different licenses (vary in restrictions for code
changes disclosure) MIT, GPL, LGPL, Apache, Ruby
GPL GNU Public License
Unrestricted commercial or non-commercial use Modifiable source code, as long as you publish changes
Demo - FiveRuns
Systems Administration meets Web 2.0 Web-based rich client for administering servers Allows for same responsiveness as a regular systems
management solution, but totally centralized Near-zero setup
Just install the “agents” on each server, and they send encrypted data back to FiveRuns periodically
The real web2.0 reason - allows for collaboration Systems administrators apply solutions to metrics, these
solutions are publicized and rated
FiveRuns
Section Complete
Questions?
Web 2.0 Rich Client - BankingBuild web 2.0 style Improvements into online banking
Course Schedule – Day 2
Lecture Infrastructure “2.0” and Open SourceExercise Web 2.0 Rich Client - Banking
Lecture RubyLecture Ruby on rails
Lunch Break
Lecture Building an Application using RailsExercise Redesign your solution for Web 2.0Lecture “Ajaxifying” our Rails ApplicationLecture Wrap-Up, Web “3.0”, Humor
Develop web 2.0 improvements for… Online Banking, including
How customers could possibly share data (without sharing personal data)
Rich Client Applications for Personal Banking Better distribution of account information
RubyThe Agile New Language.
Course Schedule – Day 2
Lecture Infrastructure “2.0” and Open SourceExercise Web 2.0 Rich Client - BankingLecture Ruby
Lecture Ruby on railsLunch Break
Lecture Building an Application using RailsExercise Redesign your solution for Web 2.0Lecture “Ajaxifying” our Rails ApplicationLecture Wrap-Up, Web “3.0”, Humor
What is Ruby?
Hottest new language that is taking on the Java and .NET community.
Takes on the following and does it one better: The objected-orientedness of Java The expressiveness of Perl The simplicity of Python
Invented by Yukihiro Matsumoto Developed by a world-wide network of open source
developers.
Standard language design goals
Running Efficiency Simpler Parsing Maintainability Make managers happy Make compilers happy
The author of Ruby, Yukihiro Matsumoto set out to create a language that would "make programmers happy."
The “benevolent dictator” of Ruby
Objects
'hello'.upcase
-42.abs
3.times {puts 'Ni!'}
x = ['vubee', 'java', 'python', 'monty']
x.length
Everything in Ruby is an object
Some Ruby-isms
puts 'hello'.length
# Unless you have multiple statements on same lineputs -42.abs; puts 'hello'
No need for semi-colons:
No curly brackets for control structures:if (condition) ...end
puts 'hello' if x > 0
# Is same as
puts('hello') if (x > 0)
Braces are optional for expressions and methods calls:
if (condition) { ...}
Naming Conventions
GeeForce = 9.80665 # Constant
account_value = 3141592654 # Local variable
Book my_book # Class name (Book)
Math::PI # Module name (Math)
Local variables start with lowercase or underscore. Constants start with uppercase (and do not use
underscores) Class names and module names start with
uppercase (and do not use underscores). Instance variables start with an @ sign.
Arrays and Hashesreptiles = ['lizard', 'crocodile', 'turtle']
reptiles = %w{lizard crocodile turtle}
amphibians = Array.new
amphibians.push 'frog'
amphibians.push 'salamander'
ectotherms = reptiles + amphibians
puts ectotherms.sort
h = {'name' => 'yoda', 'age' => 1000, 'hobby' => 'yoga'}
puts h['name']
h = {:name => 'yoda', :age => 1000, :hobby => 'yoga'}
puts h[:name]
Regular Expressions
puts 'facetious'.gsub(/[aeiou]/, '*')
puts 'anthropomorphic'.gsub(/(o.){3}/, '*')
alphabet = 'the quick brown fox jumped over the lazy dog'
puts alphabet.gsub(/\s/, '').split(/\s*/).uniq.sort.to_s
Supports Perl-like regular expressions and most methods.
Control Structuresif (condition) ...elsif (condition) ...else ...end
unless (condition) ...else ...end
case (interest_rate) when 0..9 puts 'low' when 10..99 puts 'high' else puts 'invalid' end
interest_category = (interest_rate > 9) ? 'high' : 'low'
Loops
while (condition) ...end
until (condition) ...end
Standard while loops
Or the opposite…
Iterators
books = ['ruby', 'java', 'python']
for b in booksputs b
end
for n in 0..3puts n
end
4.upto(8) do |i|puts i
end
3.times do print 'Ja! '
end
Iterators make your life simple!
Iterators in Java?
List bookList;
Iterator iter = bookList.iterator();
while (iter.hasNext()){
book = (Book)bookList.next();// yada yada
}
Using an iterator in Java looks like:
Blocks A block is a chunk of code (enclosed in curly brackets)
passed to a method. Internally the method calls the block using “yield”
command, optionally passing variables. These variables are available to the block by assigning
them in between the pipes (||).
books = ['ruby', 'java', 'python']
books.each { |x| puts x}
blockmethod
blockvariable
block
Methodsdef just_do_it(n)
n.times do puts 'just do it!'
endend
puts just_do_it 2
def convert(args) if (args[:kg]) args[:kg]*2.2 else args[:lb]/2.2 endend
puts convert(:lb => 110)
def square(n)n*n
end
puts square(3)
Classes and Accessorsclass Aircraft attr_reader :model attr_accessor :manufacturer
def initialize(model) @model = model endend
fighter_jet = Aircraft.new('F-16')
fighter_jet.model = 'MiG-29' # This will throw an error
fighter_jet.manufacturer = 'out-sourced to Romania'
puts fighter_jet.modelputs fighter_jet.manufacturer
Class Inheritance
class PassengerJet < Aircraft attr_accessor :seats
def initialize(model, seats) super(model) @seats = seats endend
airbus = PassengerJet.new('A380', 800)
airbus.manufacturer = 'Airbus Industries'airbus.seats = 600
puts airbus.modelputs airbus.manufacturerputs airbus.seats
Modules Modules are classes that cannot be instantiated. Consider it like a library class.
module Geometry
def Geometry.degrees2radians(degrees)
degrees/180.0 * Math::PI
end
end
puts Geometry.degrees2radians(90)
Logging Built-in logging functions with trace levels. Trace levels can be changed at run-time.
log = Logger.new(STDOUT)
log.level = Logger::DEBUG
log.datetime_format = '%H:%M:%S'
log.info 'starting logging'
log.debug 'testing logging'
log.warn 'possible system failure!'
Exception Handling
file = File.open('tmp.txt')
begin
# do stuff
raise 'Error: bad file!'
rescue
# handle error
ensure
file.close unless file.nil?
end
File Handlinganimals = %w{cow elephant parrot monkey}
# Writingfile = File.open('tmp.txt', 'w')
animals.each do |a|
file.puts a
end
file.close
# Reading
File.open('tmp.txt').each { |line|
puts line
}
Database Access Perl-like database abstraction library
require 'dbi'
db = DBI.connect('DBI:mysql:database=test')
stmt = db.execute('select * from products')
stmt.fetch_hash do |row|puts row['description']
end
stmt.finish
db.disconnect
And much more... Reflection Threads Dynamic Loading Tons of built-in library modules:
Net::FTP, Net::HTTP, Net::WebServices Encryption Process, Kernel
Mixins Garbage collection Marshelling
Demo
Google Maps
Google Maps
First high-profile mapping sites that utilized AJAX Enabled Rich-Client mapping More attractive maps using their implementation
Google Maps - Hackability
Initial release had no public API JavaScript is inherently open source Many community-created GMap toolkits were created
Mashups were created (housingmaps.com)
Google released a Google Maps API, free for all non-commercial use
Enabled more mashups, including Google’s own (“Green” environmentally friendly sites mashup for Earth Day,
etc)
Section Complete
Questions?
Ruby on RailsThe Agile New Framework
Course Schedule – Day 2
Lecture Infrastructure “2.0” and Open SourceExercise Web 2.0 Rich Client - BankingLecture RubyLecture Ruby on rails
Lunch Break
Lecture Building an Application using RailsExercise Redesign your solution for Web 2.0Lecture “Ajaxifying” our Rails ApplicationLecture Wrap-Up, Web “3.0”, Humor
Model-View-Controller
MVC is an architecture that separates out the business model (Model), the presentation (View), and the application logic (Controller).
There have been many frameworks that have attempted to achieve this:
Struts Framework (w/EJB) (2000-2004) Tapestry (2003-2007?) Spring Framework (w/Hibernate) (2004-2008?) Ruby + Rails (2004-2012?)
Why Java/EJB failed... Why are many veteran J2EE developers switching to Ruby on
Rails?
Complexity of EJB. Complexity of Java based MVC frameworks (like Struts) Repetitiveness of code. For example, the Model (definition and
relationships) have to be redefined in 3 places: SQL, XML, and Java.
Maintenance nightmare. Inflexible to change – not Agile.
What is Ruby on Rails
Ruby on Rails is an MVC Framework created by David Heinemeier Hansson, supported by the open source community.
Developers around the world have experienced that it cuts down development by at least 40%
It does so by the DRY principle – Don't Repeat Yourself. A great breakthrough from the Java based frameworks – where every change involves touching N files.
RoR Model
RoR Model
View Controller Model DB
•Controllers•Actions•Sessions•Flash•Filters
•ActiveRecords•Validators
•RHTML•Helpers•Layouts•Partials
Presentation Layer Application Logic Business Model
Model
RoR Model
create table products ( id int not null auto_increment, title varchar(50) not null, price decimal(10, 2) not null, primary key (id));
create table reviews ( id int not null auto_increment, product_id int not null, reviewer varchar(50) not null, comments text, published_date datetime, constraint fk_product_id foreign key (product_id)
references products(id), primary key (id));
Books to Reviews is a one-to-many relation.
Active Record
RoR Model
class Product < ActiveRecord::Base
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :product
end
Knows which table, based on class name. No need to define any class attributes! Automatically determines it from database. Need to define type of relationship.
Active Record
RoR Model
product = Product.new(:title => 'RubyBook', :price => '15.00')product.save!
review = Review.new(:reviewer => 'Rama', :product => product)review.comments = 'Very good book.'review.save!
review = Review.new(:reviewer => 'Krishna', :product => product)review.comments = 'Great book.'review.save!
product.reviews.each { |review|pp review
}
Creating and saving.
Validation
RoR Model
class Product < ActiveRecord::Base
has_many :reviews
validates_presence_of :title, :price
validates_numericality_of :price
end
class Review < ActiveRecord::Base
belongs_to :product
validates_presence_of :reviewer, :product
end
Several built-in validation methods
Active Record Ruby uses finder methods with SQL-like conditions
syntax.
RoR Model
products = Product.find(:all, :conditions => "title = 'RubyBook' and price < 20", :limit => 10, :order => 'title DESC')
products = Product.find(:all, :conditions => ["title = ? and price < ?", 'RubyBook', 20])
params = {:title => 'RubyBook', :price => 20}
products = Product.find(:all, :conditions => ["title = :title and price < :price", params])
products.each { |product|pp product
}
RoR View
RoR View
View Controller Model DB
•Controllers•Actions•Sessions•Flash•Filters
•ActiveRecords•Validators
•RHTML•Helpers•Layouts•Partials
Presentation Layer Application Logic Business Model
RHTML
Embed Ruby in HTML Similar to JSP/PHP tags:
<% ruby code %> <%= ruby expression %>
ERb - Lightweight Templating System
RoR View
RHTML Sample:
RoR View
<html>
Embedded Ruby expression inside HTML:<br/>
The time is <%= Time.now %> <br/>
Embedded Ruby code inside HTML:
<p>
<%
books = ['ruby', 'java', 'python']
books.each { |x|
puts “#{x} “
}
%>
</p>
</html>
Helpers Share reusable code. Helper modules.
RoR View
<html>
<h3> Status: <%= items_in_cart %> </h3>
</html>
module ShoppingCartHelperdef items_in_cart
nitems = get_number_of_items_in_cartif nitems == 0
return “Your shopping cart is empty”else
return “You have #{ntems}” in your cart”end
endend
Built-in Helpers Formatting Helpers
RoR View
<html>
<%= human_size(1024) %> <br/>
<%= number_to_currency(161.80) %> <br/>
<%= number_to_phone(1112223333, :area_code=>true, :delimiter=>'-') %>
<%= number_with_delimiter(111222333) %>
</html>
1 KB
$161.80
(111)222-3333
111,222,333
Built-in Helpers Form Helpers
RoR View
• <%= form_tag(:action, :class) %>
• <%= end_form_tag %>
• <%= text_field(:variable, :attribute, :options %>
• <%= hidden_field(:variable, :attribute, :options %>
• <%= password_field(:variable, :attribute, :options %>
• <%= radio_button(:variable, :attribute, tag_value, option %>
• <%= check_box(:variable, :attribute, options, on_value, off_value %>
• <%= select(:variable, :attribute, choices, options, html_options %>
• <%= date_select(:variable, :attribute, options) %>
Layouts Many pages share the same header, footer,
sidebars, and other layouts. To give all pages a consistent look and feel this
layout is separated out... Into a layout template. Rails renders views by wrapping them with the
layout template. Makes all views simpler – focusing only the chunk of
code that concerns them.
RoR View
Layouts Sample layout template:
RoR View
<html>
<head>
<title>Book Store</title>
<%= stylesheet_link_tag 'bookstore' %>
</head>
<body>
<!-- Header HTML code here -->
<%= @content_for_layout %>
<!-- Footer HTML code here -->
</body>
</html>
Partials Are chunks of reusable view templates. For example, list of products may be displayed in
multiple areas of the application; that code can be reused.
It is like any other view template, except that its name starts with an underscore.
Example, _blog_entry.rhtml
RoR View
Controllers Following the MVC paradigm, RoR applications are
invoked through the controllers.
RoR Controller
http://localhost/bookstore/admin/add_product
Identifies the action/method to invoke (add_product)
Identifies the controller (AdminController)
Identifies the application (bookstore)
RoR Controller
RoR Controller
View Controller Model DB
•Controllers•Actions•Sessions•Flash•Filters
•ActiveRecords•Validators
•RHTML•Helpers•Layouts•Partials
Presentation Layer Application Logic Business Model
Controllers The Controller
RoR Controller
class AdminController < ApplicationController
def add_product
...
end
end
When the action has finished it renders the corresponding view (default: same name as action - add_product.rhtml).
It also passes parameters to the view.
Sessions Session information is stored in hash called session. It is available across all the controllers.
RoR Controller
# Helper method, available to all controllers to retrieve the# current shopping cart from the session.
def get_shopping_cart
session[:cart] ||= Cart.new
end
The Flash The flash is a convenient hash you can store stuff in,
and is visible to the view. Useful for displaying error messages.
RoR Controller
class AdminController < ApplicationController
def add_product
# ...
product.save
redirect_to(:action => 'list_products')
rescue
flash[:notice] = “Failed to add product”
redirect_to(:action => 'show_error')
end
end
Filters Filters are a powerful feature. It is a method that is
invoked before any action is invoked.
RoR Controller
class AdminController < ApplicationControllerbefore_filter :authorize
# ...end
# This should go in app/controllers/application.rb
def authorizeunless session[:user_id]
flash[:notice] = “Please login in”redirect_to(:controller => “login”, :action => “login”)
endend
And much more... Emphasis on test driven development Interactive console for fast debugging Emphasis on Elegance of APIs
RoR Controller
Demo
Del.icio.us
Del.icio.us
Social Bookmarking Users store lists of URLs that they find interesting Tags can be added to each bookmark (folksonomy) Multiple users add bookmarks and tags
These combinations are grouped together Algorithms are used to pool tags that are joined by bookmark,
by user, or by other shared common tags
Section Complete
Questions?
Ajax on RailsRedefining Web Development.
Let's code... Assume a form has this <div> tag:
<div id=”mydiv”>We're going to change this text using Ajax!</div>
Let's change the text using Ajax (that is, without submitting the form).
We can do that by adding the Ajax'ed link:<%= link_to_remote(“Ajax demo!”,
:update => 'mydiv',
:url => {:action => :test_ajax}) %>
Straight to the code... Define the action. Tell it not to use layouts wrapper.
def test_ajax
render(:layout => false)
end
Define the view (test_ajax.rhtml).<em>Text has changed! Time on the server is <%= Time.now %></em>
Let's try it! Initial Page:
Upon clicking the link:
Behind the scenes... Rails accomplishes this by:
prototype.js – a JavaScript library that includes prototype, effects, dragdrop, and controls.
JavaScriptHelper module – wraps JavaScript in Ruby code.
The <head> should include:
<%= javascript_include_tag “prototype” %>
Ajax any Form You can ajax any form by using the form_remote_tag()
instead of the form_tag()
<%= form_remote_tag(:update => “mydiv”,
:url => {:action => :guess}) %>
Observers Monitors the specified field in a form Calls an Ajax action when user changes the data in that
field.<label for=”search”>Search:</label>
<%= text_field_tag :search %>
<%= observe_field(:search, :frequency => 0.5, :update => :results, :url => {:action => :search}) %>
<div id=”results”/>
Periodic Updates Periodically call an Ajax action.
<%= periodically_call_remote( :frequency => 2 :update => :results, :url => {:action => :server_time}) %>
<div id=”results”></div>
def server_time
render(:text => Time.now)
end
Special Effects Effects to convey something has been changed or
added. The following snippet calls item_added action to update
items when the submit action (add_item) is completed.
<%= form_remote_tag(:url => {:action => :add_item},:update => “items”,:position => “bottom”,:complete => “item_added(request)”,) %>
<%= end_form_tag %>
Special Effects Note that the Ajax action add_item returns the id of the
item via the header.
def add_itemitem = Item.new(:name => params[:name])item.save!headers.['x-item-id'] = item.idrender(:partial => “item”, :object => item)
end
<li id=”item_<%= item.id%>”>
</li>
The _item.rhtml should have the id= field
Special Effects The following JavaScript (added to the forms layout),
determines the effect. It uses built-in special effects Effect.Highlight Also uses the built-in helper $(id) which returns the
DOM element with given id.<script>
function item_added(request) {var id = request.getResponseHeader('x-item-id');new Effect.Highlight('item_' + id);$('new_item').value = '';
</script>
And more... Effect.Appear – Changes the opacity from 0% to 100%
making it come into visibility smoothly Effect.Fade – Fades out an element smoothly Effect.Highlight – Smoothly highlights an element. Effect.Puff – Elements gently disappear in a cloud of
smoke. Effect.Squish – Elements disappear by getting squished
out.
Wikipedia
Collaborative Encyclopedia Anyone can edit ANY article Actively moderated by other users Growing to be as prominent as Encyclopedia Britannica
Constant comparisons made between both Researchers found about the same number of factual
accuracy as Britannica Published in the Journal “Nature”
Section Complete
Questions?
Web 2.0 SolutionsBuild a web 2.0 style solution for a client
Course Schedule – Day 2
Lecture Infrastructure “2.0” and Open SourceExercise Web 2.0 Rich Client - BankingLecture RubyLecture Ruby on rails
Lunch Break
Lecture Building an Application using RailsExercise Redesign your solution for Web 2.0
Lecture “Ajaxifying” our Rails ApplicationLecture Wrap-Up, Web “3.0”, Humor
More web 2.0 brainstorming! Within each group, pick a project that one member
implemented in their organization
Knowing what you’ve learned from the course, how would you re-implement it to be more “Web 2.0”
Whether you would use rails, etc
Just adding AJAX is not enough!!!
Ajax on RailsRedefining Web Development.
Course Schedule – Day 2
Lecture Infrastructure “2.0” and Open SourceExercise Web 2.0 Rich Client - BankingLecture RubyLecture Ruby on rails
Lunch Break
Lecture Building an Application using RailsExercise Redesign your solution for Web 2.0Lecture “Ajaxifying” our Rails Application
Lecture Wrap-Up, Web “3.0”, Humor
Let's code... Assume a form has this <div> tag:
<div id=”mydiv”>We're going to change this text using Ajax!</div>
Let's change the text using Ajax (that is, without submitting the form).
We can do that by adding the Ajax'ed link:<%= link_to_remote(“Ajax demo!”,
:update => 'mydiv',
:url => {:action => :test_ajax}) %>
Straight to the code... Define the action. Tell it not to use layouts wrapper.
def test_ajax
render(:layout => false)
end
Define the view (test_ajax.rhtml).<em>Text has changed! Time on the server is <%= Time.now %></em>
Let's try it! Initial Page:
Upon clicking the link:
Behind the scenes... Rails accomplishes this by:
prototype.js – a JavaScript library that includes prototype, effects, dragdrop, and controls.
JavaScriptHelper module – wraps JavaScript in Ruby code.
The <head> should include:
<%= javascript_include_tag “prototype” %>
Ajax any Form You can ajax any form by using the form_remote_tag()
instead of the form_tag()
<%= form_remote_tag(:update => “mydiv”,
:url => {:action => :guess}) %>
Observers Monitors the specified field in a form Calls an Ajax action when user changes the data in that
field.<label for=”search”>Search:</label>
<%= text_field_tag :search %>
<%= observe_field(:search, :frequency => 0.5, :update => :results, :url => {:action => :search}) %>
<div id=”results”/>
Periodic Updates Periodically call an Ajax action.
<%= periodically_call_remote( :frequency => 2 :update => :results, :url => {:action => :server_time}) %>
<div id=”results”></div>
def server_time
render(:text => Time.now)
end
Special Effects Effects to convey something has been changed or
added. The following snippet calls item_added action to update
items when the submit action (add_item) is completed.
<%= form_remote_tag(:url => {:action => :add_item},:update => “items”,:position => “bottom”,:complete => “item_added(request)”,) %>
<%= end_form_tag %>
Special Effects Note that the Ajax action add_item returns the id of the
item via the header.
def add_itemitem = Item.new(:name => params[:name])item.save!headers.['x-item-id'] = item.idrender(:partial => “item”, :object => item)
end
<li id=”item_<%= item.id%>”>
</li>
The _item.rhtml should have the id= field
Special Effects The following JavaScript (added to the forms layout),
determines the effect. It uses built-in special effects Effect.Highlight Also uses the built-in helper $(id) which returns the
DOM element with given id.<script>
function item_added(request) {var id = request.getResponseHeader('x-item-id');new Effect.Highlight('item_' + id);$('new_item').value = '';
</script>
And more... Effect.Appear – Changes the opacity from 0% to 100%
making it come into visibility smoothly Effect.Fade – Fades out an element smoothly Effect.Highlight – Smoothly highlights an element. Effect.Puff – Elements gently disappear in a cloud of
smoke. Effect.Squish – Elements disappear by getting squished
out.
Wikipedia
Collaborative Encyclopedia Anyone can edit ANY article Actively moderated by other users Growing to be as prominent as Encyclopedia Britannica
Constant comparisons made between both Researchers found about the same number of factual
accuracy as Britannica Published in the Journal “Nature”
Section Complete
Questions?