Title: Web 2'0 Overview
1Web 2.0 Overview
- An Overview of the Evolution of the WWW
2This course has been produced under the USAID
Enterprise Development Strengthening project
implemented by CHF International
3Course 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
4Course Schedule Day 1
5Course Schedule Day 2
6The 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
7What is Web 2.0?
- Web 2.0 is not AJAX!
- Not any particular technology
- A new approach, attitude, way of thinking
- Coined by OReilly Media and MediaLive
- Brainstorming session after the dot-com bubble
burst - Trying to figure out where the post-bubble web
was headed
8Web 1.x Producer-Consumer
- Producers live in the universe of the Consumers
9Web 2.0 Consumer feeds self
- Producers create the universe in which Consumers
feed themselves
10Forces 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
11Technologies 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)
12Web 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
13Web 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
14Web 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
15Demo 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
16Section Complete
17In-Room Experiences
- Describe yourself and your Projects
18Course Schedule Day 1
19Tell 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?
20Ajax
- Finally, we see some code!
21Course Schedule Day 1
22What is AJAX?
- Asynchronous JavaScript And XML
- AJAX isnt one technology
- A combination of existing technologies
- JavaScript, XML, and XHTML
- A naming concept similar to Dynamic HTML
- HTML, JavaScript, CSS
23Elements 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.
24History 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
25Synchronous vs. Asynchronous
26Synchronous vs. Asynchronous
27What is Ajax a solution to?
- Decreases bandwidth between client and server
- Most content is loaded only once
- MacRumors.com
- Rumor site for Apple Computers 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
28What 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
29What 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)
30XMLHttpRequest - 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
31XMLHttpRequest - Methods
- getAllReponseHeaders()
- Returns a delimited string of all the HTTP
headers (names and values) from the response - Examples Content-Type text/html, Referer lturlgt
- 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
32XMLHttpRequest - 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
33Creating 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.XMLHTT
P")
34Creating 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
35Creating 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
36Creating a Request
- Retrieve the contents of the servers 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
37Call the function
- Send the request to the server
http_request.open(GET,page.htm,
true) http_request.send(null)
38Data 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
39Data 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
40Data 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
41Security 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
42Frameworks 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
43Frameworks 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
44Frameworks Backend (.NET)
- Microsoft Ajax Scripting Library (Atlas)
- Microsofts AJAX framework for ASP.NET
- Makes client/server calls
- Generates all invocation code automatically
- Part of Visual Studio 2005, Web Developer Express
- Well cover more of this on Day 2
- Ajax.NET Professional
- Third-party Ajax library for ASP.NET
- Minimal setup
45Frameworks 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
46Frameworks 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
47Drawbacks 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
48Drawbacks 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
49Drawbacks 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)
50Drawbacks 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
51Demo 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)
52Flickr
- 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 couldnt come up with
53Section Complete
54Debugging Ajax
- Various tools that can help you develop with AJAX
productively
55Course Schedule Day 1
56DOM 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
57History of Tools
- Old Javascript Debugging Tools
- Regular JavaScript Editors
- Notepad!
- Visual InterDev had some debugging
- TCP/IP proxy
- Our best friend, alert()
58JS 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
59DOM Inspectors
- Mozilla/Firefox
- Can be optionally installed as part of the
Firefox developer tools - Very similar to IEs DOM inspector (many
identical features)
60Traffic 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
61IDEs
- 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
62Demo 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
63Section Complete
64Web 2.0 Solutions
- Build a web 2.0 style solution for a client
65Course Schedule Day 1
66Instructions
- 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
67Your 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
68Microsoft .NET and Web 2.0
- Microsofts initiatives in Web 2.0 and
Rich-Client development
69Course Schedule Day 1
70Microsofts 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
71Windows Live
- Microsofts 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
72.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
73Ajax.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 ltsystem.webgt
lthttpHandlersgt ltadd verbPOST, GET
pathAjaxPro/.ashx typeAjaxPro.AjaxHan
dlerFactory,AjaxPro /gt lt/httpHandlersgt
74Ajax.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
75Microsoft Atlas
- Microsofts 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
76Atlas 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)
77Atlas 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)
78Atlas Layers
- Browser Compatibility Layer
- Abstracts support for browsers
- Eliminates (if browser firefox) type code
- Supports various versions of IE, Firefox, Safari
79Atlas 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
80Atlas 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
81Client-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 dont
82Client-Side Framework Sarissa
var xmlhttp new XMLHttpRequest() xmlhttp.open(
GET, http//www.YourServer.com/DataDocumen
t.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
83Client-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
84Just one more thing Demo
85Microsoft 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
86Section Complete
87Infrastructure 2.0 andOpen Source
- How many Web 2.0 sites are hosted
88Course Schedule Day 2
89Goals 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
90Rapid 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!
91Big 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 RD budgets required to
develop a line of Mainframes
92Little 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
93Little 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
94Little 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
95Commercial 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)
96Commercial Platforms
- Disadvantages
- Dependence on a single vendor
- Patches, Updates, Official Support
- Constrained market can not propose solutions
where the customer requires a different platform
97Open 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
98Open 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
99Free/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
100Free/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
101Demo - 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
102FiveRuns
103Section Complete
104Web 2.0 Rich Client - Banking
- Build web 2.0 style Improvements into online
banking
105Course Schedule Day 2
106Develop 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
107Ruby
108Course Schedule Day 2
109What 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.
110Standard language design goals
- Running Efficiency
- Simpler Parsing
- Maintainability
- Make managers happy
- Make compilers happy
111- The author of Ruby, Yukihiro Matsumoto set out
to create a language that would "make programmers
happy." - The benevolent dictator of Ruby
112Objects
- Everything in Ruby is an object
'hello'.upcase -42.abs 3.times puts 'Ni!' x
'vubee', 'java', 'python', 'monty' x.length
113Some Ruby-isms
puts 'hello'.length Unless you have multiple
statements on same lineputs -42.abs puts 'hello'
- No curly brackets for control structures
if (condition) ...
if (condition) ...end
- Braces are optional for expressions and methods
calls
puts 'hello' if x gt 0 Is same as puts('hello')
if (x gt 0)
114Naming Conventions
- 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 _at_ sign.
GeeForce 9.80665 Constant account_va
lue 3141592654 Local variable Book my_book
Class name (Book) MathPI
Module name (Math)
115Arrays and Hashes
reptiles 'lizard', 'crocodile',
'turtle' reptiles wlizard crocodile
turtle amphibians Array.new amphibians.push
'frog' amphibians.push 'salamander' ectotherms
reptiles amphibians puts ectotherms.sort h
'name' gt 'yoda', 'age' gt 1000, 'hobby' gt
'yoga' puts h'name' h name gt 'yoda',
age gt 1000, hobby gt 'yoga' puts hname
116Regular Expressions
- Supports Perl-like regular expressions and most
methods.
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/).uni
q.sort.to_s
117Control Structures
if (condition) ...elsif (condition)
...else ...end
unless (condition) ...else ...end
interest_category (interest_rate gt 9) ? 'high'
'low'
case (interest_rate) when 0..9 puts
'low' when 10..99 puts 'high'
else puts 'invalid' end
118Loops
- Standard while loops
- Or the opposite
while (condition) ...end
until (condition) ...end
119Iterators
- Iterators make your life simple!
books 'ruby', 'java', 'python'for b in
books puts bendfor n in 0..3 puts
nend4.upto(8) do i puts iend3.times do
print 'Ja! 'end
120Iterators in Java?
- Using an iterator in Java looks like
List bookList Iterator iter
bookList.iterator() while (iter.hasNext()) bo
ok (Book)bookList.next() // yada yada
121Blocks
- 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 ().
blockvariable
blockmethod
books 'ruby', 'java', 'python'books.each
x puts x
block
122Methods
def just_do_it(n) n.times do puts 'just do
it!' endend puts just_do_it 2
def square(n) nnendputs square(3)
def convert(args) if (argskg)
argskg2.2 else argslb/2.2
endendputs convert(lb gt 110)
123Classes and Accessors
class Aircraft attr_reader model
attr_accessor manufacturer def
initialize(model) _at_model model
endendfighter_jet Aircraft.new('F-16')fight
er_jet.model 'MiG-29' This will throw an
errorfighter_jet.manufacturer 'out-sourced to
Romania'puts fighter_jet.modelputs
fighter_jet.manufacturer
124Class Inheritance
class PassengerJet lt Aircraft attr_accessor
seats def initialize(model, seats)
super(model) _at_seats seats
endendairbus PassengerJet.new('A380',
800)airbus.manufacturer 'Airbus
Industries'airbus.seats 600puts
airbus.modelputs airbus.manufacturerputs
airbus.seats
125Modules
- Modules are classes that cannot be instantiated.
- Consider it like a library class.
module Geometry def Geometry.degrees2radians(d
egrees) degrees/180.0 MathPI
end end puts Geometry.degrees2radians(90)
126Logging
- Built-in logging functions with trace levels.
- Trace levels can be changed at run-time.
log Logger.new(STDOUT) log.level
LoggerDEBUG log.datetime_format
'HMS' log.info 'starting logging' log.debug
'testing logging' log.warn 'possible system
failure!'
127Exception Handling
file File.open('tmp.txt') begin do
stuff raise 'Error bad file!' rescue handle
error ensure file.close unless file.nil? end
128File Handling
animals wcow elephant parrot monkey
Writingfile File.open('tmp.txt',
'w') animals.each do a file.puts
a end file.close Reading File.open('tmp.txt').e
ach line puts line
129Database Access
- Perl-like database abstraction library
require 'dbi'db DBI.connect('DBImysqldatabas
etest')stmt db.execute('select from
products')stmt.fetch_hash do row puts
row'description'endstmt.finishdb.disconnect
130And much more...
- Reflection
- Threads
- Dynamic Loading
- Tons of built-in library modules
- NetFTP, NetHTTP, NetWebServices
- Encryption
- Process, Kernel
- Mixins
- Garbage collection
- Marshelling
131Demo
132Google Maps
- First high-profile mapping sites that utilized
AJAX - Enabled Rich-Client mapping
- More attractive maps using their implementation
133Google 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 Googles own
- (Green environmentally friendly sites mashup
for Earth Day, etc)
134Section Complete
135Ruby on Rails
The Agile New Framework
136Course Schedule Day 2
137Model-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?)
138Why 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.
139What 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.
140RoR Model
Presentation Layer
Application Logic
Business Model
View
Controller
Model
DB
- Controllers
- Actions
- Sessions
- Flash
- Filters
- RHTML
- Helpers
- Layouts
- Partials
RoR Model
141Model
Books to Reviews is a one-to-many relation.
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))
RoR Model
142Active Record
- 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.
class Product lt ActiveRecordBase has_many
reviews end class Review lt ActiveRecordBase
belongs_to product end
RoR Model
143Active Record
product Product.new(title gt 'RubyBook',
price gt '15.00')product.save!review
Review.new(reviewer gt 'Rama', product gt
product)review.comments 'Very good
book.'review.save!review Review.new(reviewer
gt 'Krishna', product gt product)review.comment
s 'Great book.'review.save!product.reviews.ea
ch review pp review
RoR Model
144Validation
- Several built-in validation methods
class Product lt ActiveRecordBase has_many
reviews validates_presence_of title,
price validates_numericality_of
price end class Review lt ActiveRecordBase be
longs_to product validates_presence_of
reviewer, product end
RoR Model
145Active Record
- Ruby uses finder methods with SQL-like conditions
syntax.
products Product.find(all, conditions gt
"title 'RubyBook' and price lt 20", limit gt
10, order gt 'title DESC') products
Product.find(all, conditions gt "title ?
and price lt ?", 'RubyBook', 20) params
title gt 'RubyBook', price gt 20 products
Product.find(all, conditions gt "title
title and price lt price", params) products.eac
h product pp product
RoR Model
146RoR View
Presentation Layer
Application Logic
Business Model
View
Controller
Model
DB
- Controllers
- Actions
- Sessions
- Flash
- Filters
- RHTML
- Helpers
- Layouts
- Partials
RoR View
147RHTML
- Embed Ruby in HTML
- Similar to JSP/PHP tags
- lt ruby code gt
- lt ruby expression gt
- ERb - Lightweight Templating System
RoR View
148RHTML
lthtmlgt Embedded Ruby expression inside
HTMLltbr/gt The time is lt Time.now gt
ltbr/gt Embedded Ruby code inside HTML
ltpgt lt books 'ruby', 'java',
'python' books.each x puts x
gt lt/pgt lt/htmlgt
RoR View
149Helpers
- Share reusable code.
- Helper modules.
module ShoppingCartHelper def items_in_cart nit
ems get_number_of_items_in_cart if nitems
0 return Your shopping cart is
empty else return You have ntems in
your cart end endend
lthtmlgt lth3gt Status lt items_in_cart gt
lt/h3gt lt/htmlgt
RoR View
150Built-in Helpers
lthtmlgt lt human_size(1024) gt ltbr/gt lt
number_to_currency(161.80) gt ltbr/gt lt
number_to_phone(1112223333, area_codegttrue,
delimitergt'-') gt lt number_with_delimiter(1112
22333) gt lt/htmlgt
1 KB 161.80 (111)222-3333 111,222,333
RoR View
151Built-in Helpers
- lt form_tag(action, class) gt
- lt end_form_tag gt
- lt text_field(variable, attribute, options
gt - lt hidden_field(variable, attribute, options
gt - lt password_field(variable, attribute,
options gt - lt radio_button(variable, attribute,
tag_value, option gt - lt check_box(variable, attribute, options,
on_value, off_value gt - lt select(variable, attribute, choices,
options, html_options gt - lt date_select(variable, attribute, options)
gt
RoR View
152Layouts
- 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
153Layouts
lthtmlgt ltheadgt lttitlegtBook Storelt/titlegt lt
stylesheet_link_tag 'bookstore'
gt lt/headgt ltbodygt lt!-- Header HTML code here
--gt lt _at_content_for_layout gt lt!-- Footer
HTML code here --gt lt/bodygt lt/htmlgt
RoR View
154Partials
- 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
155Controllers
- Following the MVC paradigm, RoR applications are
invoked through the controllers.
http//localhost/bookstore/admin/add_product
Identifies the application (bookstore)
Identifies the controller (AdminController)
Identifies the action/method to invoke
(add_product)
RoR Controller
156RoR Controller
Presentation Layer
Application Logic
Business Model
View
Controller
Model
DB
- Controllers
- Actions
- Sessions
- Flash
- Filters
- RHTML
- Helpers
- Layouts
- Partials
RoR Controller
157Controllers
class AdminController lt 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.
RoR Controller
158Sessions
- Session information is stored in hash called
session. - It is available across all the controllers.
Helper method, available to all controllers to
retrieve the current shopping cart from the
session. def get_shopping_cart sessioncart
Cart.new end
RoR Controller
159The Flash
- The flash is a convenient hash you can store
stuff in, and is visible to the view. - Useful for displaying error messages.
class AdminController lt ApplicationController def
add_product ... product.save redirect_to(
action gt 'list_products') rescue flashnotic
e Failed to add product redirect_to(action
gt 'show_error') end end
RoR Controller
160Filters
- Filters are a powerful feature. It is a method
that is invoked before any action is invoked.
class AdminController lt ApplicationController bef
ore_filter authorize ...end
This should go in app/controllers/application.rb
def authorize unless sessionuser_id flash
notice Please login in redirect_to(contro
ller gt login, action gt login) endend
RoR Controller
161And much more...
- Emphasis on test driven development
- Interactive console for fast debugging
- Emphasis on Elegance of APIs
RoR Controller
162Demo
163Del.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
164Section Complete
165Ajax on Rails
- Redefining Web Development.
166Let's code...
- Assume a form has this ltdivgt tag
ltdiv idmydivgtWe're going to change this text
using Ajax!lt/divgt
- Let's change the text using Ajax (that is,
without submitting the form). - We can do that by adding the Ajax'ed link
lt link_to_remote(Ajax demo!, update gt
'mydiv', url gt action gt test_ajax) gt
167Straight to the code...
- Define the action.
- Tell it not to use layouts wrapper.
def test_ajax render(layout gt false) end
- Define the view (test_ajax.rhtml).
ltemgtText has changed! Time on the server is lt
Time.now gtlt/emgt
168Let's try it!
169Behind 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 ltheadgt should include
lt javascript_include_tag prototype gt
170Ajax any Form
- You can ajax any form by using the
form_remote_tag() instead of the form_tag()
lt form_remote_tag(update gt mydiv,
url gt action gt guess) gt
171Observers
- Monitors the specified field in a form
- Calls an Ajax action when user changes the data
in that field.
ltlabel forsearchgtSearchlt/labelgtlt
text_field_tag search gtlt observe_field(sear
ch, frequency gt 0.5,
update gt results,
url gt action gt search) gtltdiv
idresults/gt
172Periodic Updates
- Periodically call an Ajax action.
lt periodically_call_remote(
frequency gt 2 update gt
results, url gt action gt
server_time) gtltdiv idresultsgtlt/divgt
def server_time render(text gt Time.now) end
173Special 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.
lt form_remote_tag(url gt action gt
add_item, update gt items, position gt
bottom, complete gt item_added(request),)
gt lt end_form_tag gt
174Special Effects
- Note that the Ajax action add_item returns the id
of the item via the header.
def add_item item Item.new(name gt
paramsname) item.save! headers.'x-item-id'
item.id render(partial gt item, object gt
item)end
- The _item.rhtml should have the id field
ltli iditem_lt item.idgtgt lt/ligt
175Special 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.
ltscriptgt function item_added(request) var id
request.getResponseHeader('x-item-id') new
Effect.Highlight('item_' id) ('new_item').va
lue ''lt/scriptgt
176And 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.
177Wikipedia
- 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
178Section Complete
179Web 2.0 Solutions
- Build a web 2.0 style solution for a client
180Course Schedule Day 2
181More web 2.0 brainstorming!
- Within each group, pick a project that one member
implemented in their organization - Knowing what youve 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!!!
182Ajax on Rails
- Redefining Web Development.
183Course Schedule Day 2
184Let's code...
- Assume a form has this ltdivgt tag
ltdiv idmydivgtWe're going to change this text
using Ajax!lt/divgt
- Let's change the text using Ajax (that is,
without submitting the form). - We can do that by adding the Ajax'ed link
lt link_to_remote(Ajax demo!, update gt
'mydiv', url gt action gt test_ajax) gt
185Straight to the code...
- Define the action.
- Tell it not to use layouts wrapper.
def test_ajax render(layout gt false) end
- Define the view (test_ajax.rhtml).
ltemgtText has changed! Time on the server is lt
Time.now gtlt/emgt
186Let's try it!
187Behind 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 ltheadgt should include
lt javascript_include_tag prototype gt
188Ajax any Form
- You can ajax any form by using the
form_remote_tag() instead of the form_tag()
lt form_remote_tag(update gt mydiv,
url gt action gt guess) gt
189Observers
- Monitors the specified field in a form
- Calls an Ajax action when user changes the data
in that field.
ltlabel forsearchgtSearchlt/labelgtlt
text_field_tag search gtlt observe_field(sear
ch, frequency gt 0.5,
update gt results,
url gt action gt search) gtltdiv
idresults/gt
190Periodic Updates
- Periodically call an Ajax action.
lt periodically_call_remote(
frequency gt 2 update gt
results, url gt action gt
server_time) gtltdiv idresultsgtlt/divgt
def server_time render(text gt Time.now) end
191Special 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.
lt form_remote_tag(url gt action gt
add_item, update gt items, position gt
bottom, complete gt item_added(request),)
gt lt end_form_tag gt
192Special Effects
- Note that the Ajax action add_item returns the id
of the item via the header.
def add_item item Item.new(name gt
paramsname) item.save! headers.'x-item-id'
item.id render(partial gt item, object gt
item)end
- The _item.rhtml should have the id field
ltli iditem_lt item.idgtgt lt/ligt
193Special Effects
- The following JavaScript (added to the forms
layout), determines the effect. - It uses built-in special effects