Web 2.0
Upcoming SlideShare
Loading in...5
×
 

Web 2.0

on

  • 2,436 views

 

Statistics

Views

Total Views
2,436
Views on SlideShare
2,434
Embed Views
2

Actions

Likes
0
Downloads
13
Comments
0

1 Embed 2

http://www.slideshare.net 2

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Web 2.0 It is a concept, not a technology. (The concept of more collaboration, etc) We really want to emphasize how little the technology comes into play anymore. Open Source and Agile Development Talk about how open source software being free and of very high quality nowadays, is part of what is helping many web 2.0 websites launch for much lesser prices. Also that since they are delivering and maintaining websites. AJAX Again, you want to mention that AJAX is just one piece of what makes Web 2.0 what it is. You also want to accent throughout the course that AJAX is not at all a new technology (It is actually 8 years old), but a unique way of implementing an old technology, much like DHTML = Javascript/CSS/HTML Ruby on Rails Emphasize the fact that Rails allows for extremely fast and agile development, one of the hallmarks of Web 2.0.
  • Course Format, Each Hour (You are free to change this) 45 minutes of Lecture Website Demonstration (You can decide whether to do this at the beginning or at the end) 15 minutes of break Each lecture is not necessarily one hour long. Some are longer (AJAX, Web 2.0 Intro), some are shorter (Debugging AJAX) There is enough content in the .NET chapter to take more than an hour.
  • Talk about how the first WWW was all about “interactivity” Compared to TVs, a completely passive activity, the web was slightly more interactive (it allowed you to choose your content), but this wasn’t very different from changing your channel on TV. Talk about how 1.5 was sort of halfway there because it allowed users to actually submit comments to stories, etc (on database driven sites) Web 2.0 actually runs off the users, and the users are the primary suppliers and organizers of content, instead of only being people who review, respond, and comment on content.
  • Again, Web 2.0, Ajax, neither of which are any particular technologies Ajax – Combination of technologies Web 2.0 – increased “collaborative” web Talk about how web 2.0 is, to an extent, a marketing term. But it is important to give things a name (examples include DHTML, “Pentium” increasing Intel’s sales, and “Centrino” really launching wifi)
  • Free = Freedom (as in, freedom to use it any way you wish to), and also Free as in zero cost. Social Networks - Basically, traditional networks of users, etc but you now know who knows who (for example, you sign up and are associated with a friend on the network so the site knows how everybody knows everybody else)
  • PHP, Python, Perl, Ruby, etc Rich Client is a piece of software that allows you to interact in more than the normal ways a website allows you to. These clients usually have animations, and support features that have been around for traditional desktop software based solutions, like drag-n-drop, and other
  • Hackability You can talk about the origins of HousingMaps.com
  • Make sure you register two accounts on Writely before the course , so you can demonstrate collaboration. It will take too long to do this in front of the students
  • Course Format, Each Hour (You are free to change this) 45 minutes of Lecture Website Demonstration (You can decide whether to do this at the beginning or at the end) 15 minutes of break Each lecture is not necessarily one hour long. Some are longer (AJAX, Web 2.0 Intro), some are shorter (Debugging AJAX) There is enough content in the .NET chapter to take more than an hour.
  • Ideally you want this to take about 30-45 mins at most. Never longer. If some students talk too much about technology, consider changing the slide to “One technology and platform you have used”
  • Course Format, Each Hour (You are free to change this) 45 minutes of Lecture Website Demonstration (You can decide whether to do this at the beginning or at the end) 15 minutes of break Each lecture is not necessarily one hour long. Some are longer (AJAX, Web 2.0 Intro), some are shorter (Debugging AJAX) There is enough content in the .NET chapter to take more than an hour.
  • Prototype - More of a convenience library used by OTHER AJAX frameworks, rather than something you would really use.
  • Talk about how a lot of these frameworks basically created JS-equivalent objects to the actual Java/.NET objects. They are basically serializers.
  • It will be effective to do a demo of the Moo.fx Accordion control in the main page at moofx.mad4milk.net
  • Consider doing a demo of Zimbra later in the course if time permits. It is a great example of a rich client.
  • Talk about some programming patterns that are emerging to address the “Broken back button” problem.
  • Course Format, Each Hour (You are free to change this) 45 minutes of Lecture Website Demonstration (You can decide whether to do this at the beginning or at the end) 15 minutes of break Each lecture is not necessarily one hour long. Some are longer (AJAX, Web 2.0 Intro), some are shorter (Debugging AJAX) There is enough content in the .NET chapter to take more than an hour.
  • Course Format, Each Hour (You are free to change this) 45 minutes of Lecture Website Demonstration (You can decide whether to do this at the beginning or at the end) 15 minutes of break Each lecture is not necessarily one hour long. Some are longer (AJAX, Web 2.0 Intro), some are shorter (Debugging AJAX) There is enough content in the .NET chapter to take more than an hour.
  • Course Format, Each Hour (You are free to change this) 45 minutes of Lecture Website Demonstration (You can decide whether to do this at the beginning or at the end) 15 minutes of break Each lecture is not necessarily one hour long. Some are longer (AJAX, Web 2.0 Intro), some are shorter (Debugging AJAX) There is enough content in the .NET chapter to take more than an hour.
  • Big Iron traditionally allows for a lot of hot swappable components Hardware is not cheap Cluster is inherently “hot swappable” with regular hardware because you only take down individual nodes
  • Strings are objects. Even numbers are objects. There are no “primitive types”. Every type is an object.Arrays of anything are Array objects (there is no primitive array “Integer x[]” versus Array x).
  • %w is a short cut for quote+comma More than one way to put stuff in an array Try adding two arrays in java! - you'll need to iterate through each. Hash maps are key-value pairs. You can use symbols instead of strings for the key (Ruby makes extensive use of symbols whenever possible).
  • Ruby supports the full extent of Perl regular expressions. 1. Substitutes all occurrences of any vowel character with "*". Result: f*c*t***s 2. Substitutes the first 3 occurrences of "o" followed by any character with "*". Result: anthr*phic 3. This prints 'abcdefghijk...' gsub(/s/, '') removes all spaces. 'thequickbrown....' split(/s*/) creates an array of characters. ['t', 'h', 'e', 'q', 'u', 'i',...] uniq() - removes duplicates from the array sort - sort it. to_s - converts the array into a string End result: 'abcdefghijk....'
  • Note that the case statement can use Ranges.
  • Ruby has limited loop constructs. Because preferred way of doing it is using iterators.......
  • There is more than one way of doing it. Try doing this in Java: you'll have to declare an Iterator or Enumerator class, get elements using getNextElement,, check using hasMoreElements,, and not to mention type cast the Element.
  • There is more than one way of doing it. Try doing this in Java: you'll have to declare an Iterator or Enumerator class, get elements using getNextElement,, check using hasMoreElements,, and not to mention type cast the Element.
  • Methods are defined using def The last statement is the return value (using “return” statement is optional) There is no return value nor parameter type declaration Methods can take optional parameters. For example if :lb is specified then convert() returns the weight in kg, if :kg is specified then convert() returns the weight in lb.
  • Constructor is called “initialize” No need to write setter and getter methods. attr_reader is allows the variable to be read. attr_accessor allows the variable to be read and set. Note the instance variable “@model” In the example, trying to set "model" of an Aircraft will throw an exception.
  • Inheritance is using "<" The superclass's constructor is called using "super()"
  • Print out each element of array animals[] to a file. Read each line from the file and print it to console.
  • Uses Perl-like DBI database abstraction layer. Useful for quick database access. A better alternative is to use ActiveRecords.
  • In the rest of the slides will look Rails, by Model, View, and Controller respectively. We'll start with what Rails has to offer in terms of the Model. Note the bottom right hand corner - to indicate which layer of the MVC the slide pertains to.
  • We'll use a sample application of products and product reviews. A product contains many reviews. A review pertains to only a particular product.
  • Only thing left for us to do is define the relation between products and reviews. Why can't ActiveRecords do this also automatically, based on the FK constraints? Because not all database support FK (and those that do not cannot be probed in the same way). has_many says Product has many reviews belongs_to says that a Review belongs to product
  • Fields are specified using symbol parameter maps. Not-Null fields must be specified when constructing a new object Other fields are optional. Note how by assigning product to review, the automatically foreign key references are automatically taken care of.
  • Where do you put the validation? In the model, protecting the database from bad data. Ruby has several methods, some of which you see here. If the validation fails it throws an exception which can be caught and handled at the controller level.
  • Parameters to finder methods use familiar SQL syntax. Arguments to the :conditions can be parametersize (with ?) It can also be passed as hashmap (with symbol references in the :conditions) The first parameter specified whether to return first record found or all records.
  • Similar to JSP / PHP.
  • Views can share code via helpers. Declared in helper modules. Similar to JSP bean tags.
  • Form tags tightly integrate form elements with Ruby variables.

Web 2.0 Web 2.0 Presentation Transcript

  • Web 2.0 Overview An 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
    View slide
  • Course Schedule – Day 1 Microsoft .NET and Web 2.0 Lecture Build a Web 2.0 Solution Exercise Debugging AJAX Lecture Lunch Break AJAX Introduction Lecture In-Room Experiences Exercise Introduction to Web 2.0 Lecture 1 Hour for Lunch 10-15 minute breaks each hour Breaks View slide
  • Course Schedule – Day 2 Wrap-Up, Web “3.0”, Humor Lecture “ Ajaxifying” our Rails Application Lecture Redesign your solution for Web 2.0 Exercise Building an Application using Rails Lecture Lunch Break Ruby on rails Lecture Ruby Lecture Rich Client User Interface - Banking Exercise Infrastructure “2.0” and Open Source Lecture
  • 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 Experiences Describe yourself and your Projects
  • Course Schedule – Day 1 Microsoft .NET and Web 2.0 Lecture Build a Web 2.0 Solution Exercise Debugging AJAX Lecture Lunch Break AJAX Introduction Lecture In-Room Experiences Exercise Introduction to Web 2.0 Lecture
  • 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 Finally, we see some code!
  • Course Schedule – Day 1 Microsoft .NET and Web 2.0 Lecture Build a Web 2.0 Solution Exercise Debugging AJAX Lecture Lunch Break AJAX Introduction Lecture In-Room Experiences Exercise Introduction to Web 2.0 Lecture
  • What is AJAX?
    • A synchronous J avaScript A nd X ML
    • 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(&quot;Microsoft.XMLHTTP&quot;); }
  • 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 Complete 4 Interactive 3 Loaded 2 Loading 1 Uninitialized 0
  • 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 } } Request Status Codes Internal Server Error 500 Not Found 404 OK 200
  • 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
    • Send the request to the server
    http_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 Ajax Various tools that can help you develop with AJAX productively
  • Course Schedule – Day 1 Microsoft .NET and Web 2.0 Lecture Build a Web 2.0 Solution Exercise Debugging AJAX Lecture Lunch Break AJAX Introduction Lecture In-Room Experiences Exercise Introduction to Web 2.0 Lecture
  • 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 Solutions Build a web 2.0 style solution for a client
  • Course Schedule – Day 1 Microsoft .NET and Web 2.0 Lecture Build a Web 2.0 Solution Exercise Debugging AJAX Lecture Lunch Break AJAX Introduction Lecture In-Room Experiences Exercise Introduction to Web 2.0 Lecture
  • 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.0 Microsoft’s initiatives in Web 2.0 and Rich-Client development
  • Course Schedule – Day 1 Microsoft .NET and Web 2.0 Lecture Build a Web 2.0 Solution Exercise Debugging AJAX Lecture Lunch Break AJAX Introduction Lecture In-Room Experiences Exercise Introduction to Web 2.0 Lecture
  • 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
    • XMLHttpRequest() is actually a sarissa class
      • Abstracts creation between Firefox/IE/Safari
    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);
  • 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” and Open Source How many Web 2.0 sites are hosted
  • Course Schedule – Day 2 Wrap-Up, Web “3.0”, Humor Lecture “ Ajaxifying” our Rails Application Lecture Redesign your solution for Web 2.0 Exercise Building an Application using Rails Lecture Lunch Break Ruby on rails Lecture Ruby Lecture Web 2.0 Rich Client - Banking Exercise Infrastructure “2.0” and Open Source Lecture
  • 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 - Banking Build web 2.0 style Improvements into online banking
  • Course Schedule – Day 2 Wrap-Up, Web “3.0”, Humor Lecture “ Ajaxifying” our Rails Application Lecture Redesign your solution for Web 2.0 Exercise Building an Application using Rails Lecture Lunch Break Ruby on rails Lecture Ruby Lecture Web 2.0 Rich Client - Banking Exercise Infrastructure “2.0” and Open Source Lecture
  • 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
      • The Agile New Language.
  • Course Schedule – Day 2 Wrap-Up, Web “3.0”, Humor Lecture “ Ajaxifying” our Rails Application Lecture Redesign your solution for Web 2.0 Exercise Building an Application using Rails Lecture Lunch Break Ruby on rails Lecture Ruby Lecture Web 2.0 Rich Client - Banking Exercise Infrastructure “2.0” and Open Source Lecture
  • 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 &quot; make programmers happy .&quot;
    • The “benevolent dictator” of Ruby
  • Objects
    • Everything in Ruby is an object
    'hello'.upcase -42.abs 3.times {puts 'Ni!'} x = ['vubee', 'java', 'python', 'monty'] x.length
  • Some Ruby-isms
    • No need for semi-colons:
    puts 'hello'.length # Unless you have multiple statements on same line puts -42.abs; puts 'hello'
    • 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
    • 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.
    GeeForce = 9.80665 # Constant account_value = 3141592654 # Local variable Book my_book # Class name (Book) Math::PI # Module name (Math)
  • 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 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 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
    • Standard while loops
    • Or the opposite…
    while ( condition ) ... end until ( condition ) ... end
  • Iterators
    • Iterators make your life simple!
    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 in Java?
    • Using an iterator in Java looks like:
    List bookList; Iterator iter = bookList.iterator(); while (iter.hasNext()) { book = (Book)bookList.next(); // yada yada }
  • 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 } block method block variable block
  • 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 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 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 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 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
    • 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 Rails The Agile New Framework
  • Course Schedule – Day 2 Wrap-Up, Web “3.0”, Humor Lecture “ Ajaxifying” our Rails Application Lecture Redesign your solution for Web 2.0 Exercise Building an Application using Rails Lecture Lunch Break Ruby on rails Lecture Ruby Lecture Web 2.0 Rich Client - Banking Exercise Infrastructure “2.0” and Open Source Lecture
  • 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
    • 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.
    RoR Model class Product < ActiveRecord::Base has_many :reviews end class Review < ActiveRecord::Base belongs_to :product end
  • Active Record
    • Creating and saving.
    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 }
  • Validation
    • Several built-in validation methods
    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
  • Active Record
    • Ruby uses finder methods with SQL-like conditions syntax.
    RoR Model products = Product.find(:all, :conditions => &quot;title = 'RubyBook' and price < 20&quot;, :limit => 10, :order => 'title DESC') products = Product.find(:all, :conditions => [&quot;title = ? and price < ?&quot;, 'RubyBook', 20]) params = {:title => 'RubyBook', :price => 20} products = Product.find(:all, :conditions => [&quot;title = :title and price < :price&quot;, 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 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
    • 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 < ApplicationController before_filter :authorize # ... end # This should go in app/controllers/application.rb def authorize unless session[:user_id] flash[:notice] = “Please login in” redirect_to(:controller => “login”, :action => “login”) end end
  • 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 Rails
      • Redefining 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_item item = Item.new(:name => params[:name]) item.save! headers.['x-item-id'] = item.id render(: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 Solutions Build a web 2.0 style solution for a client
  • Course Schedule – Day 2 Wrap-Up, Web “3.0”, Humor Lecture “ Ajaxifying” our Rails Application Lecture Redesign your solution for Web 2.0 Exercise Building an Application using Rails Lecture Lunch Break Ruby on rails Lecture Ruby Lecture Web 2.0 Rich Client - Banking Exercise Infrastructure “2.0” and Open Source Lecture
  • 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
      • Redefining Web Development.
  • Course Schedule – Day 2 Wrap-Up, Web “3.0”, Humor Lecture “ Ajaxifying” our Rails Application Lecture Redesign your solution for Web 2.0 Exercise Building an Application using Rails Lecture Lunch Break Ruby on rails Lecture Ruby Lecture Web 2.0 Rich Client - Banking Exercise Infrastructure “2.0” and Open Source Lecture
  • 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_item item = Item.new(:name => params[:name]) item.save! headers.['x-item-id'] = item.id render(: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?