Web 2.0 Overview: Web 2.0 Overview An Overview of the Evolution of the WWW
Slide2: This course has been produced under the USAID Enterprise Development & Strengthening project implemented by CHF International
Course Overview: 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 1: Course Schedule – Day 1
Course Schedule – Day 2: Course Schedule – Day 2
The Traditional Web - “1.0”: 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?: 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: Web 1.x: Producer-Consumer Producers live in the universe of the Consumers
Web 2.0: Consumer feeds self: Web 2.0: Consumer feeds self Producers create the universe in which Consumers feed themselves
Forces Driving the Shift: 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: 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: 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: 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: 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: 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: Section Complete Questions?
In-Room Experiences: In-Room Experiences Describe yourself and your Projects
Course Schedule – Day 1: Course Schedule – Day 1
Tell us about…: 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?
Ajax: Ajax Finally, we see some code!
Course Schedule – Day 1: Course Schedule – Day 1
What is AJAX?: 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: 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: 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
Synchronous vs. Asynchronous: Synchronous vs. Asynchronous
What is Ajax a solution to?: 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?: 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?: 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: 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: XMLHttpRequest - Methods getAllReponseHeaders()
Returns a delimited string of all the HTTP headers (names and values) from the response
Examples: Content-Type: text/html, Referer:
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: 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: 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: 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
}
}
Creating a Request: Creating a Request Check the response code of your request function myCallbackFunction() { if (http_request.readyState == 4) {
if (http_request.status == 200) { // perfect!
} else {
// there was a problem with the request
} } else { // still not ready }
}
Creating a Request: Creating a Request Retrieve the contents of the server’s response http_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: Call the function Send the request to the server http_request.open(‘GET’,’page.htm’, true);
http_request.send(null);
Data Exchange – XML: 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: 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: 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: 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: 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): 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): 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: 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: 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: 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: 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: 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: 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: 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: 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: Section Complete Questions?
Debugging Ajax: Debugging Ajax Various tools that can help you develop with AJAX productively
Course Schedule – Day 1: Course Schedule – Day 1
DOM Inspectors: 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: 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: 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: 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: 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: 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: 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: Section Complete Questions?
Web 2.0 Solutions: Web 2.0 Solutions Build a web 2.0 style solution for a client
Course Schedule – Day 1: Course Schedule – Day 1
Instructions: 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…: 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.0: Microsoft .NET and Web 2.0 Microsoft’s initiatives in Web 2.0 and Rich-Client development
Course Schedule – Day 1: Course Schedule – Day 1
Microsoft’s History with AJAX: 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: 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: .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: 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
Ajax.NET Professional Library: 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 “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: 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: 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: Atlas’ Layers Browser Compatibility Layer
Abstracts support for browsers
Eliminates (if browser == firefox) type code
Supports various versions of IE, Firefox, Safari
Atlas’ Layers: 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: 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: 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: 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: 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: Just one more thing… Demo Microsoft Virtual Earth
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: Section Complete Questions?
Infrastructure “2.0” andOpen Source: Infrastructure “2.0” and Open Source How many Web 2.0 sites are hosted
Course Schedule – Day 2: Course Schedule – Day 2
Goals of a good Infrastructure: 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: 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: “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: “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: “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: “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: 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: 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: 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: 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: 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: 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: 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: FiveRuns
Section Complete: Section Complete Questions?
Web 2.0 Rich Client - Banking: Web 2.0 Rich Client - Banking Build web 2.0 style Improvements into online banking
Course Schedule – Day 2: Course Schedule – Day 2
Develop web 2.0 improvements for…: 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
Ruby: Ruby The Agile New Language.
Course Schedule – Day 2: Course Schedule – Day 2
What is Ruby?: 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 : Standard language design goals Running Efficiency
Simpler Parsing
Maintainability
Make managers happy
Make compilers happy
Slide111: The author of Ruby, Yukihiro Matsumoto set out to create a language that would "make programmers happy."
The “benevolent dictator” of Ruby
Objects: 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: Some Ruby-isms puts 'hello'.length # Unless you have multiple statements on same line puts -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: 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 Hashes: Arrays and Hashes reptiles = ['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: 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 Structures: Control Structures if (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: Loops while (condition) ... end until (condition) ... end Standard while loops
Or the opposite…
Iterators: Iterators books = ['ruby', 'java', 'python'] for b in books puts b end for n in 0..3 puts n end 4.upto(8) do |i| puts i end 3.times do print 'Ja! ' end Iterators make your life simple!
Iterators in Java?: 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: 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
Methods: Methods def just_do_it(n) n.times do puts 'just do it!' end end
puts just_do_it 2 def convert(args) if (args[:kg]) args[:kg]*2.2 else args[:lb]/2.2 end end puts convert(:lb => 110) def square(n) n*n end puts square(3)
Classes and Accessors: Classes and Accessors class Aircraft attr_reader :model attr_accessor :manufacturer def initialize(model) @model = model end end 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.model puts fighter_jet.manufacturer
Class Inheritance: Class Inheritance class PassengerJet < Aircraft attr_accessor :seats def initialize(model, seats) super(model) @seats = seats end end airbus = PassengerJet.new('A380', 800) airbus.manufacturer = 'Airbus Industries' airbus.seats = 600 puts airbus.model puts airbus.manufacturer puts airbus.seats
Modules: 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: 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: 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 Handling: File Handling animals = %w{cow elephant parrot monkey}
# Writing file = 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: 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...: 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: Demo Google Maps
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: 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: Section Complete Questions?
Slide135: Ruby on Rails The Agile New Framework
Course Schedule – Day 2: Course Schedule – Day 2
Model-View-Controller: 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 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: 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 RoR Model View Controller Model DB Controllers
Actions
Sessions
Flash
Filters
ActiveRecords
Validators RHTML
Helpers
Layouts
Partials
Presentation Layer Application Logic Business Model
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: 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: 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: 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: Active Record Ruby uses finder methods with SQL-like conditions syntax. RoR Model products = Product.find(:all, :conditions => "title = 'RubyBook' and price 10, :order => 'title DESC')
products = Product.find(:all, :conditions => ["title = ? and price 'RubyBook', :price => 20}
products = Product.find(:all, :conditions => ["title = :title and price < :price", params])
products.each { |product| pp product }
RoR View: 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: RHTML Embed Ruby in HTML
Similar to JSP/PHP tags:
ERb - Lightweight Templating System RoR View
RHTML: RHTML Sample: RoR View
Embedded Ruby expression inside HTML:
The time is
Embedded Ruby code inside HTML:
Helpers: Helpers Share reusable code.
Helper modules. RoR View
Status:
module ShoppingCartHelper def items_in_cart nitems = get_number_of_items_in_cart if nitems == 0 return “Your shopping cart is empty” else return “You have #{ntems}” in your cart” end end end
Built-in Helpers: Built-in Helpers Formatting Helpers RoR View
true, :delimiter=>'-') %>
1 KB
$161.80
(111)222-3333
111,222,333
Built-in Helpers: Built-in Helpers Form Helpers RoR View
Layouts: 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: Layouts Sample layout template: RoR View
Book Store
Partials: 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: 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 RoR Controller View Controller Model DB Controllers
Actions
Sessions
Flash
Filters
ActiveRecords
Validators RHTML
Helpers
Layouts
Partials
Presentation Layer Application Logic Business Model
Controllers: 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: 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 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 'list_products')
rescue
flash[:notice] = “Failed to add product”
redirect_to(:action => 'show_error')
end
end
Filters: Filters Filters are a powerful feature. It is a method that is invoked before any action is invoked. RoR Controller class AdminController “login”, :action => “login”) end end
And much more...: And much more... Emphasis on test driven development
Interactive console for fast debugging
Emphasis on Elegance of APIs RoR Controller
Demo: Demo Del.icio.us
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: Section Complete Questions?
Ajax on Rails: Ajax on Rails Redefining Web Development.
Let's code...: Let's code... Assume a form has this tag: We're going to change this text using Ajax!
Let's change the text using Ajax (that is, without submitting the form).
We can do that by adding the Ajax'ed link: 'mydiv',
:url => {:action => :test_ajax}) %>
Straight to the code...: 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). Text has changed! Time on the server is
Let's try it!: Let's try it! Initial Page: Upon clicking the link:
Behind the scenes...: 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 should include:
Ajax any Form: Ajax any Form You can ajax any form by using the form_remote_tag() instead of the form_tag() “mydiv”,
:url => {:action => :guess}) %>
Observers: Observers Monitors the specified field in a form
Calls an Ajax action when user changes the data in that field. Search: 0.5, :update => :results, :url => {:action => :search}) %>
Periodic Updates: Periodic Updates Periodically call an Ajax action. 2 :update => :results, :url => {:action => :server_time}) %> def server_time
render(:text => Time.now)
end
Special Effects: 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. {:action => :add_item}, :update => “items”, :position => “bottom”, :complete => “item_added(request)”,) %>
Special Effects: Special Effects Note that the Ajax action add_item returns the id of the item via the header. def add_item item = Item.new(:name => params[:name]) item.save! headers.['x-item-id'] = item.id render(:partial => “item”, :object => item) end ”>
The _item.rhtml should have the id= field
Special Effects: 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. function item_added(request) { var id = request.getResponseHeader('x-item-id'); new Effect.Highlight('item_' + id); $('new_item').value = '';
And more... : 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: 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: Section Complete Questions?
Web 2.0 Solutions: Web 2.0 Solutions Build a web 2.0 style solution for a client
Course Schedule – Day 2: Course Schedule – Day 2
More web 2.0 brainstorming! : 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 Rails: Ajax on Rails Redefining Web Development.
Course Schedule – Day 2: Course Schedule – Day 2
Let's code...: Let's code... Assume a form has this tag: We're going to change this text using Ajax!
Let's change the text using Ajax (that is, without submitting the form).
We can do that by adding the Ajax'ed link: 'mydiv',
:url => {:action => :test_ajax}) %>
Straight to the code...: 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). Text has changed! Time on the server is
Let's try it!: Let's try it! Initial Page: Upon clicking the link:
Behind the scenes...: 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 should include:
Ajax any Form: Ajax any Form You can ajax any form by using the form_remote_tag() instead of the form_tag() “mydiv”,
:url => {:action => :guess}) %>
Observers: Observers Monitors the specified field in a form
Calls an Ajax action when user changes the data in that field. Search: 0.5, :update => :results, :url => {:action => :search}) %>
Periodic Updates: Periodic Updates Periodically call an Ajax action. 2 :update => :results, :url => {:action => :server_time}) %> def server_time
render(:text => Time.now)
end
Special Effects: 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. {:action => :add_item}, :update => “items”, :position => “bottom”, :complete => “item_added(request)”,) %>
Special Effects: Special Effects Note that the Ajax action add_item returns the id of the item via the header. def add_item item = Item.new(:name => params[:name]) item.save! headers.['x-item-id'] = item.id render(:partial => “item”, :object => item) end ”>
The _item.rhtml should have the id= field
Special Effects: 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. function item_added(request) { var id = request.getResponseHeader('x-item-id'); new Effect.Highlight('item_' + id); $('new_item').value = '';
And more... : 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: 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: Section Complete Questions?