Background image

Rodrigo Carmona Donoso

Profile

Rodrigo Carmona Donoso

Ingeniero Desarrollador en Imagemaker
Information Technology and Services | Chile, CL

Summary

He trabajado en proyectos diversos, tanto en tecnologia como en negocio. Poseo facilidad para aprender lo que se necesite para desarrollar el trabajo de la mejor manera. Me gustan mucho los nuevos desafios, mientras mas aprenda y mas pueda entregar, mejor. I have worked on various projects both in technology and in business. I own ability to learn what it takes to develop the work in the best way. I really like the new challenges, the more learning and more to deliver better
Specialties: Por ahora solo desarrollo. Java, C# y PHP son mis copilotos. By now, i like very much to develop apps. Java, C# and PHP are my best friends at work

Experience

  • Nov 2009 - Present

    Desarrollador / Imagemaker IT

    Analisis y desarrollo de Aplicacion web para el banco de chile, usando el producto Excelsys Engine, propiedad de Excelsys (www.excelsys.net) - Servidor de Aplicaciones: Oracle Weblogic 11gR1 - Lenguajes: Java, xsl, xpath, xml, html, javascript (jquery), css - Base de datos: OracleXE (solo para desarrollo) Analasys and development of web applications for the Bank of Chile, using the product Excelsys Engine, owned by Excelsys (www.excelsys.net) - Application Server: Oracle WebLogic 11gR1 - Languages: Java, xsl, xpath, xml, html, javascript (jquery), css - Database: OracleXE (only for development)
  • Apr 2009 - Nov 2009

    Analista Programador / Bluesoft Ingenieros Asociados

    Proyecto “Sistema Administración Comercial Para Canales de TV” Lenguajes: Flex 3(Action Script 3), Java (J2EE) Persistencia de datos: Eclipse-Link Servidor de Aplicaciones: GlassFish Enterprise Server 2.1 Motor BD: Oracle IDE: Flex Builder 3, Eclipse Ganymede Software Base de datos: DbVisualizer Otros: Maven 2, Granite amf
  • May 2008 - Mar 2009

    Analista Programador / Genbiz S.A.

    * Sistema de Agendamientos para Call Center Cargo: Analista y Desarrollador Lenguajes: PHP 5, CSS, HTML 4.0 Strict Base de Datos: MS SQL Server 2000 Servidor de Aplicaciones: Apache sobre CentOS 5 IDE: Eclipse con plugin PHP Software de Base de datos: SQL Managment Studio 2005 * Soporte PHP4/5 para otros sistemas en producción * Soporte T-SQL para revisión de performance en procedimientos almacenados
  • Sept 2005 - Apr 2008

    Programador / Bluesoft Ingenieros Asociados

    * Proyecto “Fonasa Digital” Lenguajes: Java, XML. Bases de Datos: Oracle, Derby. Servidores de Aplicaciones: Weblogic 8.1. Persistencia de Datos: Hibernate (HQL). IDE: Eclipse 3.2. Software de Base de Datos: SQuirreL SQL Client * Proyectos internos con uso de Java, Awk, Visual Basic 6

Education

  • 2002 - 2007

    Instituto Profesional de Chile

    Ingeniero in En Informatica

Posts

  • March 08, 04:03 PM

    Steam llegará oficialmente a Mac en abril

    valve-half-lifeValve confirmó oficialmente que el portal de descarga de videojuegos Steam tendrá su versión para Mac, trayendo consigo juegos como Left 4 Dead 2, Counter-Strike, Half-Life, Portal y Team Fortress 2 a las máquinas de Apple.

    Steam estará disponible a partir de abril, con versiones adaptadas de los juegos. El Source Engine además incorporará OpenGL para permitir soporte para Mac a los desarrolladores.

    Una de las cosas más interesantes es que los clientes que compraron una versión para Windows, por ejemplo, podrán jugar el juego en Mac sin tener que pagar otra vez gracias a la opción Steam Play. Por ejemplo, un flojo individuo podría jugar en el PC de la oficina y luego ir a la casa y continuar el juego en su Mac. O bien, si decides cambiar tu Mac por un PC… o al revés… no tienes que comprar el juego de nuevo.

    Con esto, los juegos de Valve podrían ser lanzados en el futuro en PC, Mac y Xbox360 simultáneamente.

    Link: Valve confirma oficialmente que Steam y sus juegos llegarán a Mac (Niubie)

  • March 04, 08:45 AM
  • March 07, 05:39 PM
  • March 08, 09:00 AM

    Restore a Scratched-Up iPhone with Sandpaper [IPhone]

    iPhones are scratch-resistant, but life throws some tough stuff at our phones. One MacRumors user, owning a phone that looks pretty beat, demonstrates the full process of restoring his phone with sandpaper and a new LCD kit.

    The poster makes a point of noting that on most phones, you'll only want to use a rougher sandpaper to try and remove 90 percent of the scratches, not get to a completely clean and polished look—with the scratch-resistant coating completely removed—as shown at the full post. For those looking to completely refinish their phone, there's a very informative post on the technique of wet sanding, along with tips on taping up your controls and glass and polishing off the finished result. For those with cracked or deeply scratched glass, there's a replacement guide included, too.

    It's a cheap process and doesn't take much time, especially if you don't plan on upgrading to a new model any time soon (ha!). While you're at it, you can also try giving your bezel a brushed look. If you've discovered a similarly complete and thorough iPhone transformation guide, tell us about it in the comments. Thanks for the tip, NomadDNA!



  • March 05, 01:48 AM

    Canon 'captura' tu café en una lente de 70-200mm

    Filed under:

    Es el sueño de todo fotógrafo amante del café. ¿Lo mejor de los dos mundos? ¿Qué tal un termo con tu café bien calentito y que tenga forma de lente EF70-200mm f/4L USM? Este particular Edén lo logró el directivo de Microsoft Josh Weisberg en una rueda prensa en plenos Juegos Olímpicos de Invierno. Tenemos envidia, y mucha.

    [Vía Akihabara News]
    Read | Permalink | Email this | Comments

  • March 03, 03:03 PM

    Terremoto Chile: Un resumen con todos lo ocurrido en el sector móvil

    (cc) Luis Iturra

    (cc) Luis Iturra

    Debido al terremoto ocurrido en Chile, las diferentes operadoras  de telefonía han aportado con su granito de arena, después de que las comunicaciones se interrumpieran en gran parte del país, haciendo muy difícil para las familias poder conocer cómo estaban sus seres queridos.

    Por ahora, todavía sigue siendo necesario este tipo de acciones, ya que en algunos lugares, es casi imposible establecer comunicación. Además, luego de tantas noticias respecto al tema, uno se entra a confundir, y es por esa razón que hemos realizado este resumen para que puedas leerlas en orden y sepas qué beneficios están disponibles.

    Operadoras

    • Movistar está entregando servicios de gran importancia totalmente gratis. Ha permitido llamar sin cobros desde sus cabinas de teléfonos públicos, ha sumado CLP$1.500 en crédito a los móviles de prepago de la región del Maule y Bío-Bío, y su filial en Argentina ha decidido dejar los primeros 5 minutos de cada llamada a Chile, totalmente gratis, al igual que los SMS.
    • Entel también ha querido aportar a la causa, y ha entregado 20 minutos libres para llamar a teléfonos móviles -o de casa- de cualquier compañía, y 80 SMS. Obviamente, esto es para los damnificados de la región del Maule y Bío-Bío. Al parecer, esta promoción tendría una vigencia de unos 20 días.
    • La compañía también instalará junto a Carabineros puntos de comunicación en las áreas más afectadas del país, donde los teléfonos están cortados.
    • Telmex Internacional también ofrece llamadas gratuitas, que se realicen desde Argentina, Brasil, Colombia, Ecuador, Perú, México y Uruguay hacia Chile. El servicio será muy parecido al ofrecido por Verizon, ya que solo podrá ser a través de teléfonos fijos y tendrá duración hasta el próximo 7 de marzo.
    • ¿Y Telmex Chile? Ha ofrecido liberar por 30 días los cobros a todas las llamadas de larga distancia nacional que se realicen en la región del Maule y Bío-Bío (a partir del 1 de marzo). Para usar este servicio, se deberá usar el carrier de la compañía, 171.
    • Claro fue una de las últimas operadoras en pronunciarse con algún servicio gratuito. Ofrecieron entregar 100 SMS gratis a cerca de 600.000 clientes prepago afectados de la región del Libertador General Bernardo O’Higgins, Maule, y Bío-Bío. Además, anunciaron esto en conjunto con América Móvil, quienes están presentes en Argentina, Brasil, Perú, México, Honduras, Nicaragua y Guatemala. Eso significa que de esos países podrán enviar SMS sin costo alguno hacia Chile hasta el próximo 7 de marzo.
    • En el exterior, Verizon Wireless de Estados Unidos da llamadas gratis hacia Chile, aunque solo para sus clientes de líneas fijas. Este granito de arena tendrá vigencia por toda una semana. El gerente de Verizon dijo que “en tiempos de crisis, salimos a actuar. Al actuar rápidamente, ayudamos a familias a conectarse sin preocuparse de los costos”.
    • La operadora AT&T también ha querido ayudar, y permite donar dinero a Chile a través de mensajes de texto en Estados Unidos. Por lo que se puede ver, AT&T será el intermediario de algunas organizaciones, tales como Convoy of Hope, World Program, Habit for Humanity, Operation USA, Salvation Army y World Vision. Un ejemplo, envía un mensaje con la palabra CHILE al 50555, y estarás donando USD$10.

    Otras informaciones

    • Por un tiempo, las redes móviles soportaron bastante bien el colapso debido al terremoto. Aunque se les hubiera pedido más estabilidad en el servicio, pero se hacia lo que se podía, ya que a esa hora, de madrugada, el terremoto nos pilló de sorpresa a todos. Pero como nos contaba ZooTV, él no tuvo problemas con la redes de datos, aunque la de voz, funcionaba a veces (y todavía anda con problemas).
    • A sólo horas del terremoto, publicamos 2 aplicaciones totalmente gratuitas para el iPhone para monitorear sismos, que se pueden encontrar en la App Store. La primera y más eficiente, se llama iSeismometer, y nos permite mantenernos informados en “tiempo real” sobre movimientos telúricos, y la otra, Terremoto, que nos reporta nuevos movimientos sísmicos, y la posibilidad de confirmarlos en U.S. Geological Survey (USGS).
    • Lamentablemente, Entel tuvo varios problemas con sus servicios debido al terremoto, ya que luego de 72 horas del gran movimiento sismico, se quedaron sin energía eléctrica de respaldo. Pero ya comunicaron que su red troncal esta 100% operativa, y que todo ya debería estar funcionando sin problemas.
    • La Subtel entregó ayer un informe con el estado de las telecomunicaciones, que aún tienen muchos problemas, sobre todo en las regiones del Maule y Biobío, donde menos del 40% de las líneas móviles están operativas.
    • Para terminar, les queremos comentar que en Betazeta además de estar informando acerca de nuevos servicios y sitios de utilidad publica sobre el terremoto, hemos querido poner “a disposición de las organizaciones y agencias que quieran ocupar nuestros espacios publicitarios sin costo alguno para informar a la ciudadanía de los centros de concentración de ayuda”. – Betazeta. También puedes seguir leyendo Wayerless para conocer más informaciones.
    • http://www.betazeta.com/2010/03/terremoto-chile-todos-podemos-ayudar/
  • March 04, 04:47 PM

    Dónde llamar gratis desde BioBío y Maule tras el terremoto en Chile (Actualizado)

    Ruta I-50, San Fernando – Pichilemu, vía @mi_ruz

    Ruta I-50, San Fernando – Pichilemu, vía @mi_ruz

    Entel y Carabineros habilitaron una serie de puntos de comunicación de emergencia en las regiones de BioBío y Maule, que pueden ser utilizados de forma gratuita por quienes se encuentren allá.

    Los teléfonos están ubicados en los siguientes lugares:

    Región del Maule:

    • 1ª Comisaría de Linares: Valentín Letelier Nº 380
    • VII Zona carabineros del Maule: 4 norte Nº 687 Talca
    • Prefectura de Linares: Valentín Letelier Nº 376
    • 4ª Comisaría de Cauquenes: Membrillar Nº 420.
    • Retén San José de Duao T.Maule: Duao s/n, Duao.
    • Retén Paso Nevado; 1ª San Clemente: Ruta Ch 115 Km 46, El Colorado.
    • Tenencia del Maule; 4ª Talca: Balmaceda 410, Maule.
    • Retén La Mina F; 1ª San Clemente: Ruta K-115 Km 104, San Clemente.
    • Retén Villa Santa Olga; 2ª Constitución: Los Lirios s/n. Villa Santa Olga, Km 24 Ruta M-30L,Constitución.
    • Tenencia de Pencahue 4ª Talca: Ruta K-60, Km 14 s/n, comuna de Pencahue, San José Duao.
    • 1ª Comisaría de San Clemente: Avda. Cruz 349.
    • 2° Comisaría de Licantén: Mataquito s/n.
    • 2° Comisaría de Chanco: Teniente Merino s/n.

    Región del Bío Bío:

    • Prefectura de Bío-Bío: Avda. Ricardo Vicuña Nº 405.
    • Prefectura de Concepción: San Martín Nº 171.
    • 6ª Comisaría de Chillán Viejo: Avda. O’Higgins Nº 2804.
    • Tenencia de la Carretera Bío Bío: Ruta 5 sur, Km. 518, Los Angeles.
    • Retén El Alamo; 1ª Los Angeles: Ruta Q-45, Km 15.
    • 1ª Comisaría de San Carlos: Avda. Vicuña Mackenna Nº 137.
    • OS-7 Chillán: Independencia 545, Chillán.
    • Prefectura de Talcahuano.
    • Retén Rucapequén 6ª Chillán: Principal s/n.
    • Retén Quinchamalí 2ª Chillán: Camino Principal s/n.
    • 3ª Comisaría de Nacimiento: Bulnes Nº 39, Nacimiento.
    • Subcomisaría Huambali 2ª Chillán: Barros Arana 602.
    • Tenencia San Gregorio 1ª San Carlos: Estado s/n.
    • Policlínico Los Angeles: Ercilla 520.
    • Retén Cachapoal 1ª San Carlos: Ruta 31 km 16 s/n.

    Actualización: reporte por región del estado de la red de telefonía móvil de Entel al día de hoy:

    • Región de Valparaíso: la disponibilidad de la red aumentó a 87,8%.
    • Región Metropolitana: la disponibilidad de la red aumentó a 85,2%.
    • Región del Libertador General Bernardo O’Higgins: la disponibilidad de la red aumentó a 66,1%.
    • Región del Maule: la disponibilidad de la red aumentó a 73%.
    • Región del Bío Bío: la disponibilidad de la red aumentó a 54,6%.
    • Región de la Araucanía: la disponibilidad de la red aumentó a 95,2%.

    Entel informó que hay cinco carros móviles con antenas que se irán movilizando por la zona, entregando cobertura. Uno de los camiones está en Chanco, otro en Curanipe y otro en Cañete. Los dos restantes van caminoa Bucalemu y Arauco.

    Link: Entel

  • February 25, 06:00 PM

    Justicia geek

    Juzgo a la gente dependiendo del explorador de Internet que usa.

    – Mau Galindocohen
    (Vía arroba)

    # Enlace Permanente

  • February 08, 07:29 AM

    iPad gratis

    Lo hemos vuelto a lograr. Tras regalar iPods, iPod Nano, iPhones, iPhones 3G, PDAs e incluso un tablet pc con linux, ahora le toca el turno al último gadget de la codiciada manzana, el iPad (o Aipat).

    paper_ipad

    Nuestros contactos en Cupertino nos han dado luz verde para regalar todos los iPads que queramos, así que si quieres el tuyo, solo tienes que descargarte las plantillas (delante y parte de atrás), imprimir y disfrutar de tu nuevo iPad.

    Para que luego digan que no somos generosos.

    ¿Algo que comentar? [63] Tags: , , ,
  • February 09, 10:56 AM

    SIMfi, un punto de acceso Wi-Fi dentro de una tarjeta SIM

    simfi

    Será una de las novedades que presentará Telefónica durante el Mobile World Congress que tendrá lugar en Barcelona del 15 al 18 de este mes.

    SIMfi, es una tarjeta SIM, pero con una particularidad muy interesante, ya que incorpora un diminuto punto de acceso Wi-Fi integrado, una antena y un módulo de radio compatible con IEEE 802.11, con el que podremos compartir la conexión HSPA de nuestro móvil para poder utilizarla desde otros dispositivos, como el portátil.

    simfi

    La tarjeta, que será comercializada por telefónica, la fabrica Sagem Orga bajo el nombre de ConnectSIM, y funcionará en cualquier móvil siempre que soporte HSDPA o EDGE.

    Muy interesante este nuevo tipo de tarjetas, que pueden acabar definitivamente con los modems USB o la necesidad de, en ocasiones, tener una doble SIM para conectarnos a Internet vía conexión móvil, sólo necesitaremos un portátil u ordenador con Wi-Fi para hacerlo.

    Vía | BandaAncha

  • February 09, 02:09 PM

    How to Build an Unobtrusive Login System in Rails

    An unobtrusive login system is one that gets out of the user’s way. It will make your application nicer and more polished. This article will guide you through the process of setting up user logins, then ajaxifying the process by moving the form into a modal box that communicates with the server. Additionally, this article will show you how to create the setup using jQuery and Prototype so you can choose your favorite library. This article assumes that you have experience with Rails and jQuery or Prototype.


    You can use Adman65/nettuts for a successful login. Be sure to use bad credentials so you can see how everything works.

    What We’re Making

    Getting Started

    We’re going to start by creating a dummy application that has a public and private page. The root url is the public page. There’s a login link on the public page. If the user logs in successfully, they’re redirected to the private page. If not, they’re redirected back to the login form. The private page shows the user name. We’ll use this as the starting point for ajaxifying the site.

    The first step is using the rails command to generate a new application, then install and setup up authlogic.

    $ cd into-a-directory
    $ rails unobtrusive-login
    

    Add authlogic.

    # /config/environment.rb
    config.gem 'authlogic'
    

    Now install the gems.

    $ sudo gem install gemcutter
    $ sudo gem tumble
    $ sudo rake gems:install
    

    Next create a user model and add the required authlogic columns to the migration.

    $ ./script/generate model User
    exists  app/models/
    exists  test/unit/
    exists  test/fixtures/
    create  app/models/user.rb
    create  test/unit/user_test.rb
    create  test/fixtures/users.yml
    create  db/migrate
    create  db/migrate/20100102082657_create_users.rb
    

    Now, add the columns to the new migration.

    class CreateUsers < ActiveRecord::Migration
      def self.up
        create_table :users do |t|
          t.string    :login,               :null => false
          t.string    :crypted_password,    :null => false
          t.string    :password_salt,       :null => false
          t.string    :persistence_token,   :null => false
          t.timestamps
        end
      end
    
      def self.down
        drop_table :users
      end
    end
    

    Migrate the database.

    $ rake db:migrate
    

    Include authlogic in the user model.

    # /app/models/user.rb
    class User < ActiveRecord::Base
      acts_as_authentic
    end
    

    Now we can create a user. Since this is a demo app, web based functionality for signing up isn’t required. So open up the console and create a user:

    $ ./script/console
    >> me = User.create(:login => 'Adman65', :password => 'nettuts', :password_confirmation => 'nettuts')
    

    Now we have a user in the system, but we have no way to login or logout. We need to create the models, controllers, and views for this. Authlogic has its own class for tracking logins. We can use the generator for that:

    # create the user session
    $ ./script/generate UserSession
    

    Next we need to generate the controller that will login/logout users. You can create sessions just like any other resource in Rails.

    # create the session controller
    $ ./script/generate controller UserSessions
    

    Now set its contents to:

    # /app/controllers/user_sessions_controller.rb
    class UserSessionsController < ApplicationController
      def new
        @user_session = UserSession.new
      end
    
      def create
        @user_session = UserSession.new(params[:user_session])
        if @user_session.save
          flash[:notice] = "Login successful!"
          redirect_back_or_default user_path
        else
          render :action => :new
        end
      end
    end
    

    It looks exactly the same as a controller that was generated via scaffolding. Now create the users controller which has public and private content. Generate a users controller. Inside the controller we’ll use a before filter to limit access to the private areas. The index action is public and show is private.

    # create the users controller
    $ ./script/generate controller users
    

    Update its contents:

    # /app/controllers/users_controller.rb
    class UsersController < ApplicationController
      before_filter :login_required, :o nly => :show
    
      def index
      end
    
      def show
        @user = current_user
      end
    
      private
      def login_required
        unless current_user
          flash[:error] = 'You must be logged in to view this page.'
          redirect_to new_user_session_path
        end
      end
    end
    

    You should notice that current_user is an undefined method at this point. Define these methods in ApplicationController. Open up application_controller.rb and update its contents:

    # application controller
    class ApplicationController < ActionController::Base
      helper :all # include all helpers, all the time
      protect_from_forgery # See ActionController::RequestForgeryProtection for details
    
      # From authlogic
      filter_parameter_logging :password, :password_confirmation
      helper_method :current_user_session, :current_user
    
      private
      def current_user_session
        @current_user_session ||= UserSession.find
      end
    
      def current_user
        @current_user ||= current_user_session && current_user_session.user
      end
    end
    

    At this point the models and controllers are complete, but views aren’t. We need to create views for a login form and the public and private content. We’ll use the nifty-generators gem to create a basic layout.

    $ sudo gem install nifty-generators
    $ ./script/generate nifty_layout
    

    Time to create the login form. We’re going to use a partial for this because in the future we’ll use the partial to render just the login form in the modal box. Here’s the code to create the login form. It’s exactly the same as if you were creating a blog post or any other model.

    # create the login views
    # /app/views/user_sessions/_form.html.erb
    <% form_for(@user_session, :url => user_session_path) do |form| %>
      <%= form.error_messages %>
    
      <p>
        <%= form.label :login %>
        <%= form.text_field :login %>
      </p>
    
      <p>
        <%= form.label :password %>
        <%= form.password_field :password %>
      </p>
    
      <%= form.submit 'Login' %>
    <% end %>
    

    Render the partial in the new view:

    # /app/views/user_sessions/new.html.erb
    <% title 'Login Please' %>
    <%= render :partial => 'form' %>
    

    Create some basic pages for the public and private content. The index action shows public content and show displays private content.

    # create the dummy public page
    # /app/views/users/index.html.erb
    <% title 'Unobtrusive Login' %>
    
    <p>Public Facing Content</p>
    
    <%= link_to 'Login', new_user_session_path %>
    

    And for the private page:

    # create the dummy private page
    # /app/views/users/show.html.erb
    <% title 'Welcome' %>
    <h2>Hello <%=h @user.login %></h2>
    
    <%= link_to 'Logout', user_session_path, :method => :delete %>
    

    Delete the file /public/index.html and start the server. You can now log in and logout of the application.

    $ ./script/server
    

    Here are some screenshots of the demo application. The first one is the public page.

    Public Page

    Now the login form

    Login Page

    And the private page

    Private Page

    And finally, access denied when you try to visit http://localhost:3000/user

    Access Denied

    The AJAX Login Process

    Before continuing, we need to understand how the server and browser are going to work together to complete this process. We know that we’ll need to use some JavaScript for the modal box and the server to validate logins. Let’s be clear on how this is going to work. The user clicks the login link, then a modal box appears with the login form. The user fills in the form and is either redirected to the private page, or the modal box is refreshed with a new login form. The next question is how do you refresh the modal box or tell the browser what to do after the user submits the form? Rails has respond_to blocks. With respond_to, you can tell the controller to render different content if the user requested XML, HTML, JavaScript, YAML etc. So when the user submits the form, the server can return some JavaScript to execute in the browser. We’ll use this render a new form or a redirect. Before diving any deeper, let’s go over the process in order.

    1. User goes to the public page
    2. User clicks the login link
    3. Modal box appears
    4. User fills in the form
    5. Form is submitted to the server
    6. Server returns JavaScript for execution
    7. Browser executes the JavaScript which either redirects or updates the modal box.

    That’s the high level. Here’s the low level implementation.

    1. User visits the public page
    2. The public page has some JavaScript that runs when the DOM is ready that attaches JavaScript to the login link. That javscript does an XMLHTTPRequest (XHR from now on) to the server for some JavaScript. The JavaScript sets the modal box’s content to the form HTML. The JavaScript also does something very important. It binds the form’s submit action to an XHR with POST data to the form’s action. This allows the user to keep filling the login form in inside the modal box.
    3. Modal box now has the form and required JavaScript
    4. User clicks ‘Login’
    5. The submit() function is called which does a POST XHR to the form’s action with its data.
    6. Server either generates the JavaScript for the form or the redirect
    7. Browser receives the JavaScript and executes it. The browser will either update the modal box, or redirect the user through window.location.

    Taking a Peak at the AJAX Ready Controller

    Let’s take a look at the new structure for the UserSessions controller.

    class UserSessionsController < ApplicationController
      layout :choose_layout
    
      def new
        @user_session = UserSession.new
      end
    
      def create
        @user_session = UserSession.new(params[:user_session])
    
        if @user_session.save
          respond_to do |wants|
            wants.html { redirect_to user_path(@user_session.user) }
            wants.js { render :action => :redirect } # JavaScript to do the redirect
          end
        else
          respond_to do |wants|
            wants.html { render :new }
            wants.js # defaults to create.js.erb
          end
        end
      end
    
      private
      def choose_layout
        (request.xhr?) ? nil : 'application'
      end
    end
    

    As you can see the structure is different. Inside the if save, else conditional, respond_to is used to render the correct content. want.xx where xx is a content type. By default Prototype and jQuery request text/JavaScript. This corresponds to wants.js. We’re about ready to get started on the AJAX part. We won’t use any plugins except ones for modal boxes. We’ll use Facebox for jQuery and ModalBox for Prototype.

    Prototype

    Rails has built in support for Prototype. The Rail’s JavaScript helpers are Ruby functions that generate JavaScript that use Prototype. This technique is known as RJS (Ruby JavaScript). One example is remote_form_for which works like the standard for_for adds some JS bound to onsubmit that submits to the form to its action using its method with its data. I won’t use RJS in this article since I want to demonstrate vanilla JS. I think by using pure JS and eliminating the JS helpers the article will be more approachable by less experienced developers. That being said, you could easily accomplish these steps using RJS/Prototype helpers if you choose.

    Adding Prototype to the application is very easy. When you use the rails command, it creates the Prototype and scriptaculous files in /public/JavaScripts. Including them is easy. Open up /app/views/layouts/application.erb and add this line inside the head tag:

    <%= JavaScript_include_tag :defaults %>
    

    JavaScript_include_tag creates script tags for default files in /public/JavaScripts, most importantly prototype.js, effects.js, and application.js. effects.js is scriptaculous. application.js is a file you can use to keep application specific JS. Now we need a modal box plugin. We’re going to use this. Its a very nice modal box plugin inspired by OSX. The source is hosted on GitHub, so you’ll have to clone and move the files in your project directory. For example:

    $ cd code
    $ git clone git://github.com/okonet/modalbox.git
    $ cd modalbox
    # move the files in the correct directories.
    # move modalbox.css into /public/stylesheets
    # move modalbox.js into /public/JavaScripts
    # move spinner.gif into /public/images
    

    Now include the stylesheets and JavaScript in your application.

      <%= stylesheet_link_tag ‘application’ %>
      <%= stylesheet_link_tag ‘modalbox’ %>
      <%= JavaScript_include_tag :defaults %>
      <%= JavaScript_include_tag ‘modalbox’%>

    Now let’s get our login link to open a modalbox. In order to do this we need to add some JavaScript that runs when the DOM is ready that attaches the modalbox to our link. When the user clicks the login link, the browser will do a GET to /user_sessions/new which contains the login form. The login link uses the #login-link selector. Update the login link to use the new id in /app/views/users/index.html.erb. Modify the link_to function like this:

    <%= link_to 'Login', new_user_session_path, :id => 'login-link' %>
    

    That gives us a#login-link. Now for the JavaScript to attach a modalbox. Add this JS in /public/JavaScripts/application.js

    document.observe('dom:loaded', function() {
        $('login-link').observe('click', function(event) {
            event.stop();
            Modalbox.show(this.href,
                {title: 'Login',
                width: 500}
            );
        });
    })
    

    There’s some simple JS for when the user clicks the link a modal box opens up with the link’s href. Refer to the modalbox documentation if you’d like more customization. Here’s a screenshot:

    Initial Modalbox

    Notice that inside the modal box looks very similar to our standard page. Rails is using our application layout for all HTML responses. Since our XHR’s want HTML fragments, it make sense to render without layouts. Refer back to the example controller. I introduced a method for determining the layout. Add that to UserSessionsController to disable layout for XHR’s.

    class UserSessionsController < ApplicationController
      layout :choose_layout
    
      def new
        @user_session = UserSession.new
      end
    
      def create
        @user_session = UserSession.new(params[:user_session])
        if @user_session.save
          flash[:notice] = "Login successful!"
          redirect_to user_path
        else
          render :action => :new
        end
      end
    
      def destroy
        current_user_session.destroy
        flash[:notice] = "Logout successful!"
        redirect_to root_path
      end
    
      private
      def choose_layout
        (request.xhr?) ? nil : 'application'
      end
    end
    

    Refresh the page and click the link you should get something like this:

    Without Layout

    Fill in the form and see what happens. If you fill in the from with bad info, you’re redirected outside the modal box. If you login correctly you’re redirected normally. According the requirements the user should be able to fill out the form over and over again inside the modal box until they login correctly. How can we accomplish this? As described before we need to use AJAX to submit data to the server, then use JavaScript to update the modal box with the form or do a redirection. We know that the modalbox does a GET for HTML. After displaying the initial modalbox, we need to write JS that makes the form submits itself AJAX style. This allows the form to submit itself inside the modal box. Simply adding this code after the modal box is called won’t work because the XHR might not have finished. We need to use Modalbox’s afterLoad callback. Here’s the new code:

    document.observe('dom:loaded', function() {
        $('login-link').observe('click', function(event) {
            event.stop();
            Modalbox.show(this.href,
                {title: 'Login',
                width: 500,
                afterLoad: function() {
                    $('new_user_session').observe('submit', function(event) {
                        event.stop();
                        this.request();
                    })
                }}
            );
        });
    })
    

    Form#request is a convenience method for serializing and submitting the form via an Ajax.Request to the URL of the form’s action attribute—which is exactly what we want. Now you can fill in the form inside the modal without it closing. The client side is now complete. What about the server side? The client is submitting a POST wanting JS back. The server needs to decide to either return JavaScript to update the form or render a redirect. In the UserSessionsController we’ll use respond_to to handle the JS request and a conditional to return the correct JS. Let’s begin by handling the failed login case. The server needs to return JS that updates the form, and tells the new form to submit over ajax. We’ll place this template in /app/views/users_sessions/create.js.erb. Here’s the structure for the new create action:

    def create
      @user_session = UserSession.new(params[:user_session])
      if @user_session.save
        flash[:notice] = "Login successful!"
        redirect_to user_path
      else
        respond_to do |wants|
          wants.html { render :new }
          wants.js # create.js.erb
        end
      end
    end
    

    Now let’s fill in create.js.erb:

    $('MB_content').update("<%= escape_JavaScript(render :partial => 'form') %>");
    Modalbox.resizeToContent();
    $('new_user_session').observe('submit', function(event) {
        event.stop();
        this.request();
    });
    

    First we update the content to include the new form. Then we resize the modal box. Next we ajaxify the form just as before. Voilla, you can fill in the form as many times as you want.

    Bad Info
    Updated Form

    Next we need to handle the redirection case. Create a new file in /app/views/users_sessions/redirect.js.erb:

      window.location=”<%= user_path %>”;
    

    Now, update the create action to handle the redirection process:

    def create
      @user_session = UserSession.new(params[:user_session])
      if @user_session.save
        respond_to do |wants|
          wants.html do
            flash[:notice] = "Login successful!"
            redirect_to user_path
          end
    
          wants.js { render :redirect }
        end
      else
        respond_to do |wants|
          wants.html { render :new }
          wants.js # create.js.erb
        end
      end
    end
    

    And that’s it! Now try login with correct credentials and you’re redirected to the private page. For further learning, try to add a spinner and notification telling the user the form is submitting or they’re being redirect. The application still works if the user has JavaScript disabled too.

    jQuery

    Since I’ve already covered the Prototype process, so I won’t go into the same detail as before. Instead, I will move quickly describing the alternate JavaScript to add to the application. The jQuery vesion will have the exact same structure as the Prototype version. All we need to change is what’s in application.js, create.js.erb, and the JavaScript/css includes.

    First thing we need to do is download jQuery and Facebox. Move jQuery into /public/JavaScripts as jquery.js. For facebox move the images into /public/images/, stylesheets into /public/stylesheets, and finally the JS into /public/JavaScripts. Now update /app/views/layouts/application.html.erb to reflect the changes:

    <head>
      <title><%= h(yield(:title) || "Untitled") %></title>
      <%= stylesheet_link_tag 'facebox' %>
      <%= stylesheet_link_tag 'application' %>
      <%= JavaScript_include_tag 'jquery' %>
      <%= JavaScript_include_tag 'facebox' %>
      <%= JavaScript_include_tag 'application' %>
    </head>
    

    Facebox comes with a default stylesheet which assumes you have your images in /facebox. You’ll need to update these selectors in facebox.css like so:

    #facebox .b {
      background:url(/images/b.png);
    }
    
    #facebox .tl {
      background:url(/images/tl.png);
    }
    
    #facebox .tr {
      background:url(/images/tr.png);
    }
    
    #facebox .bl {
      background:url(/images/bl.png);
    }
    
    #facebox .br {
      background:url(/images/br.png);
    }
    

    Now we attach facebox to the login link. Open up /public/JavaScripts/application.js and use this:

    $(document).ready(function() {
        $('#login-link').facebox({
            loadingImage : '/images/loading.gif',
        closeImage   : '/images/closelabel.gif',
        });
    });
    

    I override the default settings for the images to reflect the new image path. Start the sever and head over to the index page. You should see a nice facebox with the login form:

    Facebox

    Next thing we have to do is set the form to submit itself via AJAX. Just like before, we’ll have to use callbacks to execute code after the modal box is ready. We’ll use jQuery’s post method for the XHR request. Facebox has an after reveal hook we can use. application.js:

    $(document).ready(function() {
        $('#login-link').facebox({
            loadingImage : '/images/loading.gif',
            closeImage   : '/images/closelabel.gif',
        });
    
        $(document).bind('reveal.facebox', function() {
            $('#new_user_session').submit(function() {
                $.post(this.action, $(this).serialize(), null, "script");
                return false;
            });
        });
    });
    

    Updating create.js.erb should be easy enough. We have to update the facebox’s contents and re-ajaxify the form. Here’s the code:

    $('#facebox .content').html("<%= escape_JavaScript(render :partial => 'form') %>");
    $('#new_user_session').submit(function() {
        $.post(this.action, $(this).serialize(), null, "script");
        return false;
    });
    

    And that’s it! Here’s the final product:

    Logging In
    Bad Login
    Redirected

    Downloading the Code

    You can get the code here. There are branches for each library so you can check out the Prototype or jQuery versions. Any questions, comments, concerns? Thanks again for reading!

  • February 09, 10:00 AM

    Learn Basic Color Theory for Better Designs [Design]

    Whether you're putting together a portfolio web site or just slapping together some slides, knowing how colors affect the minds of your audience makes your message more appealing. Smashing magazine offers a post that serves as Color Psychology 101 for would-be designers.

    Beyond explaining which colors work as "warm" and "cool," how primaries play off secondary colors, and offering lots of keen examples of every kind of color design, Smashing's post offers some clues on how colors are perceived when images are translated to mental impressions. Here's a little primer on orange that caught me unawares:

    Orange is a very vibrant and energetic color. In its muted forms, it can be associated with the earth and with autumn. Because of its association with the changing seasons, orange can represent change and movement in general.

    Because orange is associated with the fruit of the same name, it can be associated with health and vitality. In designs, orange commands attention without being as overpowering as red. It's often considered more friendly and inviting, and less in-your-face.

    Hit the link for a deeper read. While you've got your monocle and draft paper out, tell us what color schemes you like, and which have never appealed to you, in the comments.



  • February 06, 03:14 PM

    Being Happy

    Author: chris
    Posted on: 2010-02-07 01:39:34

  • February 05, 12:00 AM
  • February 04, 08:47 AM

    Working with RESTful Services in CodeIgniter

    CodeIgniter is becoming well known for its power as a PHP based web application framework, but it’s not often that we see examples of it being used for anything else. Today we’ll learn how we can use CodeIgniter to create a RESTful API for your existing web applications, and demonstrate how to interact with your own API or other RESTful web-services, such as Facebook and Twitter.

    Tutorial Details

    Introduction

    If you have been following the CodeIgniter From Scratch series you will know by now that it is relatively quick and easy to put together simple web applications, such as blogs, CMS systems, brochure sites, etc. One thing you may not have thought about is using CodeIgniter to create an interactive API. After trying several existing REST implementations, I found they not only lacked simplicity but were missing most of the features you would expect from a RESTful implementation; so I built my own. This tutorial will show you how to use this code to set up your REST API, and gives example of how to interact with it from your web application.

    Assumptions

    1. You have a web server set up, locally or online and known how to manage files on it.
    2. You have read a few of the CodeIgniter from Scratch tutorials.
    3. You know how to set up CodeIgniter.
    4. You know a little about RESTful services.

    This tutorial is broken down into two parts. We will start by learning how to create a RESTful service, then further down, we will learn how to interact with it in a few different ways.

    Part 1 – Creating a RESTful API

    Step 1: Setting up the Demo

    Firstly you need to download the codeigniter-restserver code from GitHub and extract it and move the code to your server.

    When you open the folder, you will see an entire CodeIgniter install, which is there to power the demo. This allows people to have a play with the REST demo before integrating with your existing application.

    Open up “application/config/config.php” and set the base_url to get links working. This base_url will be different for everyone and depends entirely on where you uploaded your files.

    Step 2: The URLs

    With the files extracted and the base_url set, we are ready to load up our RESTful CodeIgniter installation, and have a look at the demo supplied with it. Browse the base URL, which by default is:

    http://localhost/restserver

    Here you will find a few example links to the example_api controller, which can be found at “application/controllers/example_api.php”. Let’s dissect the URL’s of these examples to see what is going on. The first URL is a very simple one.

    This URL looks very much like any other CodeIgniter URL with a controller and a method, but you will notice in this diagram that the method is named a “Resource”. REST is all about Resources and they are essentially a noun within your application, which are interacted with (i.e added, deleted, edited, queried) based on HTTP headers and URL query strings or HTTP arguments.

    The default format for output is XML which is what we see in this basic example. The other links are slightly larger and demonstrate how to pass parameters and show how the output format can be modified in the URL:

    Normally in CodeIgniter, you just pass in parameter values, but a REST controller accepts any number of parameters in any order. For this to work, we need to pass in the name of the parameter followed by the value in pairs.

    At the end of the URL is the “format” parameter. This is a reserved parameter that will modify the output format of the requested data like so:

    By giving both the API developer and the client application the choice of data formats to use, the API is opened up to a much wider audience and can be used with more programming languages and systems. These three are not the only formats supported, out of the box your REST API can use:

    • xml – almost any programming language can read XML
    • json – useful for JavaScript and increasingly PHP apps.
    • csv – open with spreadsheet programs
    • html – a simple HTML table
    • php – Representation of PHP code that can be eval()’ed
    • serialize – Serialized data that can be unserialized in PHP

    While adding the format to the URL is not technically the most RESTful way to change formats, it allows for easy browser testing and lets developers without cURL perform simple GET requests on the API. The more RESTful way is to send a Content-type HTTP header to the REST controller using cURL, but that will be explained later.

    Step 3: The Code

    Now if you open up application/controllers/example_api.php you will immediatley spot a few differences from normal CodeIgniter controllers.

    REST_Controller

    In the MVC pattern, a controller is the central point of the logic. It is called when a user makes a request and then based on the logic in the controller it fetches data and outputs views. CodeIgniter contains its own logic for how a Controller should work, but as we are doing something different we need our own REST_Controller library to contain its own REST related logic. So instead of simply using:

    <?php
    class Example_api extends Controller {
    
    }
    

    …you will need to use:

    <?php
    require(APPPATH'.libraries/REST_Controller.php');
    
    class Example_api extends REST_Controller {
    
    }
    

    Working with Resources

    Now your empty controller is set up, next are the methods or “resources”. This is prossibly the most confusing part of the tutorial if you are used to how CodeIgniter works. Basically, you take the Resource and the HTTP verb and combine them to make a method name. So the two examples we looked at before had a Resource of user and users. Because both of these were loaded in the browser, we know it was using a GET request and so the two methods below are used:

    <?php
    require(APPPATH'.libraries/REST_Controller.php');
    
    class Example_api extends REST_Controller {
    
        function user_get()
        {
    		// respond with information about a user
        }
    
        function users_get()
        {
    		// respond with information about several users
        }
    }
    

    This may seem a little strange, but it gives you the ability to use the same URL and respond to the request depending on the HTTP verb that has been used. If somebody tries to access your API in a way that is not allowed (in this example PUT or DELETE) it will simply respond with a 404. If you aren’t sure about HTTP verbs, let me explain.

    GET

    Used to fetch information about an existing resource. This is used by browsers when you enter a URL and hit go, or when you click on a link, so it perfect for fetching information on one of your REST resources (like user).

    POST

    Used to update an existing resource with information. Browsers use this to submit most types of forms on the internet, although some use GET as well by submitting the form action with a query string containing the field data.

    PUT

    Less commonly used and not supported by most browsers, PUT is used to create a new resource.

    DELETE

    Also not used by many browsers, this HTTP verb rather obviously is used to delete a resource.

    If we put that into code and allow each verb on the resource user it would look like this:

    <?php
    require(APPPATH'.libraries/REST_Controller.php');
    
    class Example_api extends REST_Controller {
    
        function user_get()
        {
    		// respond with information about a user
        }
    
        function user_put()
        {
    		// create a new user and respond with a status/errors
        }
    
        function user_post()
        {
    		// update an existing user and respond with a status/errors
        }
    
        function user_delete()
        {
    		// delete a user and respond with a status/errors
        }
    }
    

    Accessing parameters and returning data

    So now the API has been given its structure by setting up the resources and defining a method for each HTTP verb we wish to support; we need parameters so we can use our CodeIgniter models and libraries. This is one of the major benefits of using CodeIgniter for our API, as we can use our existing models and libraries and not have to re-code them.

    <?php
    require(APPPATH'.libraries/REST_Controller.php');
    
    class Example_api extends REST_Controller {
    
        function user_get()
        {
    		$data = array('returned: '. $this->get('id'));
    		$this->response($data);
        }
    
        function user_post()
        {
    		$data = array('returned: '. $this->post('id'));
    		$this->response($data);
        }
    
        function user_put()
        {
    		$data = array('returned: '. $this->put('id'));
    		$this->response($data;
        }
    
        function user_delete()
        {
    		$data = array('returned: '. $this->delete('id'));
    		$this->response($data);
        }
    }
    

    This example contains five new pieces of code:

    $this->get()

    Is used to return GET variables from either a query string like this index.php/example_api/user?id=1 or can be set in the more CodeIgniter’esque way with index.php/example_api/user/id/1.

    $this->post()

    Is an alias for $this->input->post() which is CodeIgniter’s method to access $_POST variables with XSS protection.

    $this->put()

    Reads in PUT arguments set in the HTTP headers or via cURL.

    $this->delete()

    You guessed it, this reads in DELETE arguments, also set in HTTP headers or via cURL.

    $this->response()

    Sends data to the browser in whichever data format has been requested, or defaults to XML. You can optionally pass a HTTP status code to show it has worked or failed. E.g if the ID provided was not in the database, you could use $this->response(array(‘error’ => ‘User not found.’), 404);

    Step 4: Working with your Models

    Until now, we have been working with an example API in a clean install. So the next step is to get a REST API running from your existing codebase.

    Although the download comes with a full CodeIgniter installation for the demo and to allow API’s to be built from scratch, the only two files of importance are:

    1. application/config/rest.php
    2. application/libraries/REST_Controller.php

    Drop those two files into your CodeIgniter application and create a new API controller.

    <?php
    require(APPPATH.'/libraries/REST_Controller.php');
    
    class Api extends REST_Controller
    {
    	function user_get()
        {
            if(!$this->get('id'))
            {
            	$this->response(NULL, 400);
            }
    
            $user = $this->user_model->get( $this->get('id') );
    
            if($user)
            {
                $this->response($user, 200); // 200 being the HTTP response code
            }
    
            else
            {
                $this->response(NULL, 404);
            }
        }
    
        function user_post()
        {
            $result = $this->user_model->update( $this->post('id'), array(
            	'name' => $this->post('name'),
            	'email' => $this->post('email')
            ));
    
            if($result === FALSE)
            {
            	$this->response(array('status' => 'failed'));
            }
    
            else
            {
            	$this->response(array('status' => 'success'));
            }
    
        }
    
        function users_get()
        {
            $users = $this->user_model->get_all();
    
            if($users)
            {
                $this->response($users, 200);
            }
    
            else
            {
                $this->response(NULL, 404);
            }
        }
    }
    ?>
    

    This shows an example API with some generic model names. In the first method, we are picking up a ?id=XX and passing it to the model. If data is found we send it to the $this->response() function with a status 200. If nothing is found, return no body and a 404 to say nothing was found. You can imagine how this could be expanded to run all sorts of API activities for your web application.

    Step 5: Securing the API

    Now your API is built it needs securing so only users given access can interact with the API. To set the login type, usernames and passwords open up “application/config/rest.php” inside your codebase.

    /*
    |--------------------------------------------------------------------------
    | REST Login
    |--------------------------------------------------------------------------
    |
    | Is login required and if so, which type of login?
    |
    |	'' = no login required, 'basic' = relatively secure login, 'digest' = secure login
    |
    */
    $config['rest_auth'] = 'basic';
    

    None

    Anyone can interact with any one of of your API controllers.

    Basic

    A relatively insecure login method which should only be used on internal/secure networks.

    Digest

    A much more secure login method which encrypts usernames and password. If you wish to have a protected API which anyone could get at, use digest.

    /*
    |--------------------------------------------------------------------------
    | REST Login usernames
    |--------------------------------------------------------------------------
    |
    | Array of usernames and passwords for login
    |
    |	array('admin' => '1234')
    |
    */
    $config['rest_valid_logins'] = array('admin' => '1234');
    

    Setting up the users is simple. Each login is an array item, with a key and a value. The key is the username and the value is the password. Add as many as you like to this array and dish them out to anyone who will be using the API.

    Part 2 – Interacting with RESTful Services

    Whether it is the API you have just built or a public service such as Twitter, you will want to be able to interact with it somehow. Seeing as RESTful services work with basic HTTP requests it is very easy to do this in a number of different ways.

    Different Methods to Interact with REST

    Each of these different interaction methods will be shown with the code placed directly in the Controller methods. This is purely so the demos are easier to read and would normally would be placed inside a model or a library for correct MVC separation.

    file_get_contents()

    Using the very simple PHP function file_get_contents(), you can perform a basic GET request. This is the most basic of all the methods but is worth mentioning for those “quick and dirty” moments.

    $user = json_decode(
    	file_get_contents('http://example.com/index.php/api/user/id/1/format/json')
    );
    
    echo $user->name;
    

    It’s worth noting that, while this method will not work using HTTP Digest authentication, if you are using HTTP Basic authentication you can use the following syntax to get data from your password protected RESTful API:

    $user = json_decode(
    	file_get_contents('http://admin:1234@example.com/index.php/api/user/id/1/format/json')
    );
    
    echo $user->name;
    

    There are a few problems with using this method: the only way to set extra HTTP headers is to set them manually using the PHP function stream_context_create(), which can be very complicated for developers who are new to the internal workings of HTTP requests. Another disadvantage is that you only receive the body of the HTTP response in its raw format, which means you need to handle conversion from very single request.

    cURL

    cURL is the most flexible way to interact with a REST API as it was designed for exactly this sort of thing. You can set HTTP headers, HTTP parameters and plenty more. Here is an example of how to update a user with our example_api and cURL to make a POST request:

    
        function native_curl($new_name, $new_email)
        {
    	    $username = 'admin';
    		$password = '1234';
    
    		// Alternative JSON version
    		// $url = 'http://twitter.com/statuses/update.json';
    		// Set up and execute the curl process
    		$curl_handle = curl_init();
    		curl_setopt($curl_handle, CURLOPT_URL, 'http://localhost/restserver/index.php/example_api/user/id/1/format/json');
    		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    		curl_setopt($curl_handle, CURLOPT_POST, 1);
    		curl_setopt($curl_handle, CURLOPT_POSTFIELDS, array(
    			'name' => $new_name,
    			'email' => $new_email
    		));
    
    		// Optional, delete this line if your API is open
    		curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ':' . $password);
    
    		$buffer = curl_exec($curl_handle);
    		curl_close($curl_handle);
    
    		$result = json_decode($buffer);
    
    		if(isset($result->status) && $result->status == 'success')
    		{
    			echo 'User has been updated.';
    		}
    
    		else
    		{
    			echo 'Something has gone wrong';
    		}
        }
    

    Interacting with your API this way works fine, but there are two problems with this method:

    1. It uses an ugly confusing syntax – imagine creating several an application based on that.
    2. cURL is not installed on all servers by default.

    To solve this ugly syntax, a cURL library has been developed for CodeIgniter which simplifies things immensely.

    The exact same request made with the cURL library would look like this:

        function ci_curl($new_name, $new_email)
        {
    	    $username = 'admin';
    		$password = '1234';
    
    		$this->load->library('curl');
    
    		$this->curl->create('http://localhost/restserver/index.php/example_api/user/id/1/format/json');
    
    		// Optional, delete this line if your API is open
    		$this->curl->http_login($username, $password);
    
    		$this->curl->post(array(
    			'name' => $new_name,
    			'email' => $new_email
    		));
    
    		$result = json_decode($this->curl->execute());
    
    		if(isset($result->status) && $result->status == 'success')
    		{
    			echo 'User has been updated.';
    		}
    
    		else
    		{
    			echo 'Something has gone wrong';
    		}
        }
    

    Much nicer to look at right? Well there is an even easier method to work with REST in your CodeIgniter applications that this.

    REST client library

    A REST client library has been developed that sits on top of this cURL library which handles format conversion, HTTP logins and several other aspects of your REST API.

        function rest_client_example($id)
        {
    		$this->load->library('rest', array(
    			'server' => 'http://localhost/restserver/index.php/example_api/',
    			'http_user' => 'admin',
    			'http_pass' => '1234',
    			'http_auth' => 'basic' // or 'digest'
    		));
    
            $user = $this->rest->get('user', array('id' => $id), 'json');
    
            echo $user->name;
        }
    

    Here you can see we are making a GET request, sending id as a parameter and telling the library we want ‘json’ as the content format. This handles the setting of Content-type for you, and converts the data into a PHP object for you. You can change this value to ‘xml’, ‘json’, ’serialize’, ‘php’, ‘csv’ or any custom MIME-type you like, for example:

    	$user = $this->rest->get('user', array('id' => $id), 'application/json');
    

    As you have probably guessed as well as $this->rest->get(), the library also supports $this->rest->post(), $this->rest->put(), $this->rest->delete() to match all of your REST_Controller methods.

    You will need to var_dump() results coming from the REST client library to make sure you are getting the right data format back. The conversion will somtimes be array and sometimes be an object, depending on how it is converted by PHP. If the returned MIME-type is not supported then it will simply return the format as plain-text.

    Talking to Twitter

    Using this REST library you can talk other RESTful services such as Twitter and Facebook. Here is a simple example of how you can get details for a specfic user based on their ID, using Twitter’s default format XML.

            $this->load->library('rest', array('server' => 'http://twitter.com/'));
    
            $user = $this->rest->get('users/show', array('screen_name' => 'philsturgeon'));
    
            $this->load->library('rest', array(
            	'server' => 'http://twitter.com/',
    			'http_user' => 'username',
    			'http_pass' => 'password',
    			'http_auth' => 'basic'
            ));
    
            $user = $this->rest->post('statuses/update.json', array('status' => 'Using the REST client to do stuff'));
    

    Looking at this, you will notice that interacting with the Twitter API is a bit different in a few ways.

    1. They support URL based format switching in the form of .json instead of /format/json. Some require an extension, some do not; so it’s best to always add them.
    2. They mostly only support GET/POST, but are starting to add more DELETE methods
    3. They don’t always have just a resource in their URL, for example: users/search is one REST method, but lists is another.

    Keep an eye out for these differences as they can catch you out. If you get stuck, simply echo $this->rest->debug() for a whole range of information on your REST request.

    Summary

    Combining what you now know about RESTful services, the CodeIgniter REST client library and the Twitter API documentation – or any other RESTful API documentation for that matter – you can create some very powerful applications that integrate with any custom or public web service using REST. You can extend your API by creating more REST_Controller’s and even make a modular API by using Matchbox or Modular Separation to create an api.php controller for each module to help keep your API as neatly organized as your application.

    Write a Plus Tutorial

    Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We’re looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you’re of the ability, please contact Jeffrey at nettuts@tutsplus.com.

    Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

    Write a PLUS tutorial

  • February 03, 11:10 AM

    How to Test your JavaScript Code with QUnit

    QUnit, developed by the jQuery team, is a great framework for unit testing your JavaScript. In this tutorial, I’ll introduce what QUnit specifically is, and why you should care about rigorously testing your code.

    Tutorial Details

    • Language: JavaScript
    • Difficulty: Intermediate
    • Estimated Completion Time: 30 minutes
    • Required File: QUnit JS

    What is QUnit

    QUnit is a powerful JavaScript unit testing framework that helps you to debug code. It’s written by members of the jQuery team, and is the official test suite for jQuery. But QUnit is general enough to test any regular JavaScript code, and it’s even able to test server-side JavaScript via some JavaScript engine like Rhino or V8.

    If you’re unfamiliar with the idea of “unit testing”, don’t worry. It’s not too difficult to understand:

    In computer programming, unit testing is a software verification and validation method in which a programmer tests if individual units of source code are fit for use. A unit is the smallest testable part of an application. In procedural programming a unit may be an individual function or procedure.

    This is quoted from Wikipedia. Simply put, you write tests for each functionality of your code, and if all of these tests are passed, you can be sure that the code will be bug-free (mostly, depends on how thorough your tests are).

    Why You Should Test Your Code

    If you haven’t written any unit tests before, you probably just apply your code to a website directly, click for a while to see if any problem occurs, and try to fix it as you spot one. There are many problems with this method.

    First, it’s very tedious. Clicking actually is not an easy job, because you have to make sure everything is clicked and it’s very likely you’ll miss one thing or two. Second, everything you did for testing is not reusable, which means it’s not easy to find regressions. What is a regression? Imagine that you wrote some code and tested it, fixed all the bugs you found, and published it. Then, a user sends some feedback about new bugs, and requests some new features. You go back to the code, fix these new bugs and add these new features. What might happen next is that some of the old bugs come up again, which are called “regressions.” See, now you have to do the clicking again, and chances are you won’t find these old bugs again; even if you do, it’ll take a while before you figure out that the problem is caused by regressions. With unit testing, you write tests to find bugs, and once the code is modified, you filter it through the tests again. If a regression appears, some tests will definitely be failed, and you can easily spot them, knowing which part of the code contains the bug. Since you know what you have just modified, it can easily be fixed.

    Another advantage of unit testing is especially for web development: it eases the testing of cross-browser compatibility. Just run your tests on different browsers, and if a problem occurs on one browser, you fix it and run these tests again, making sure it doesn’t introduce regression on other browsers. You can be sure that all of the target browsers are supported, once they all pass the tests.

    I’d like to mention one of John Resig’s projects: TestSwarm. It takes JavaScript unit testing to a new level, by making it distributed. It’s a website that contains many tests, anyone can go there, run some of the tests, then return the result back to server. In this way, code can be tested on different browsers and even different platforms really quickly.

    How to Write Unit Tests with QUnit

    So how do you write unit tests with QUnit exactly? First, you need to set up a testing environment:

    <!DOCTYPE html>
    <html>
    <head>
    	<title>QUnit Test Suite</title>
    	<link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" media="screen">
    	<script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script>
    	<!-- Your project file goes here -->
    	<script type="text/javascript" src="myProject.js"></script>
    	<!-- Your tests file goes here -->
    	<script type="text/javascript" src="myTests.js"></script>
    </head>
    <body>
    	<h1 id="qunit-header">QUnit Test Suite</h1>
    	<h2 id="qunit-banner"></h2>
    	<div id="qunit-testrunner-toolbar"></div>
    	<h2 id="qunit-userAgent"></h2>
    	<ol id="qunit-tests"></ol>
    </body>
    </html>
    

    As you can see, a hosted version of QUnit framework is used here.

    The code that is going to be tested should be put into myProject.js, and your tests should be inserted into myTests.js. To run these tests, simply open this HTML file in a browser. Now it’s time to write some tests.

    The building blocks of unit tests are assertions.

    An assertion is a statement that predicts the returning result of your code. If the prediction is false, the assertion has failed, and you know that something has gone wrong.

    To run assertions, you should put them into a test case:

    // Let's test this function
    function isEven(val) {
    	return val % 2 === 0;
    }
    
    test('isEven()', function() {
    	ok(isEven(0), 'Zero is an even number');
    	ok(isEven(2), 'So is two');
    	ok(isEven(-4), 'So is negative four');
    	ok(!isEven(1), 'One is not an even number');
    	ok(!isEven(-7), 'Neither is negative seven');
    })
    

    Here we defined a function, isEven, which detects whether a number is even, and we want to test this function to make sure it doesn’t return wrong answers.

    We first call test(), which constructs a test case; the first parameter is a string that will be displayed in the result, and the second parameter is a callback function that contains our assertions. This callback function will get called once QUnit is run.

    We wrote five assertions, all of which are boolean. A boolean assertion expects its first parameter to be true. The second parameter is also a message that will be displayed in the result.

    Here is what you get, once you run the test:

    a test for isEven()

    Since all these assertions have successfully passed, we can be pretty sure that isEven() will work as expected.

    Let’s see what happens if an assertion has failed.

    // Let's test this function
    function isEven(val) {
    	return val % 2 === 0;
    }
    
    test('isEven()', function() {
    	ok(isEven(0), 'Zero is an even number');
    	ok(isEven(2), 'So is two');
    	ok(isEven(-4), 'So is negative four');
    	ok(!isEven(1), 'One is not an even number');
    	ok(!isEven(-7), 'Neither does negative seven');
    
    	// Fails
    	ok(isEven(3), 'Three is an even number');
    })
    

    Here is the result:

    a test contains failed assertion for isEven()

    The assertion has failed because we deliberately wrote it wrong, but in your own project, if the test doesn’t pass, and all assertion are correct, you know a bug has been found.

    More Assertions

    ok() is not the only assertion that QUnit provides. There are other kinds of assertions that are useful when testing your project:

    Comparison Assertion

    The comparison assertion, equals(), expects its first parameter (which is the actual value) is equal to its second parameter (which is the expected value). It’s similar to ok(), but outputs both actual and expected values, making debugging much easier. Like ok(), it takes an optional third parameter as a message to be displayed.

    So instead of:

    test('assertions', function() {
    	ok( 1 == 1, 'one equals one');
    })
    
    a boolean assertion

    You should write:

    test('assertions', function() {
    	equals( 1, 1, 'one equals one');
    })
    
    a comparison assertion

    Notice the last “1″, which is the comparing value.

    And if the values are not equal:

    test('assertions', function() {
    	equals( 2, 1, 'one equals one');
    })
    
    a failed comparison assertion

    It gives a lot more information, making life a lot easier.

    The comparison assertion uses “==” to compare its parameters, so it doesn’t handle array or object comparison:

    test('test', function() {
    	equals( {}, {}, 'fails, these are different objects');
    	equals( {a: 1}, {a: 1} , 'fails');
    	equals( [], [], 'fails, there are different arrays');
    	equals( [1], [1], 'fails');
    })
    

    In order to test this kind of equality, QUnit provides another kind assertion: identical assertion.

    Identical Assertion

    Identical assertion, same(), expects the same parameters as equals(), but it’s a deep recursive comparison assertion that works not only on primitive types, but also arrays and objects. Assertions, in the previous example, will all pass if you change them to identical assertions:

    test('test', function() {
    	same( {}, {}, 'passes, objects have the same content');
    	same( {a: 1}, {a: 1} , 'passes');
    	same( [], [], 'passes, arrays have the same content');
    	same( [1], [1], 'passes');
    })
    

    Notice that same() uses ‘===’ to do comparison when possible, so it’ll come in handy when comparing special values:

    test('test', function() {
    	equals( 0, false, 'true');
    	same( 0, false, 'false');
    	equals( null, undefined, 'true');
    	same( null, undefined, 'false');
    })
    

    Structure Your Assertions

    Putting all assertions in a single test case is a really bad idea, because it’s very hard to maintain, and doesn’t return a clean result. What you should do is to structure them, put them into different test cases, each aiming for a single functionality.

    You can even organize test cases into different modules by calling the module function:

    module('Module A');
    test('a test', function() {});
    test('an another test', function() {});
    
    module('Module B');
    test('a test', function() {});
    test('an another test', function() {});
    
    structure assertions

    Asynchronous Test

    In previous examples, all assertions are called synchronously, which means they run one after another. In the real world, there are also many asynchronous functions, such as ajax calls or functions called by setTimeout() and setInterval(). How can we test these kinds of functions? QUnit provides a special kind of test case called “asynchronous test,” which is dedicated to asynchronous testing:

    Let’s first try to write it in a regular way:

    test('asynchronous test', function() {
    	setTimeout(function() {
    		ok(true);
    	}, 100)
    })
    
    an incorrent example of asychronous test

    See? It’s as if we didn’t write any assertion. This is because the assertion ran asynchronously, by the time it got called, the test case had already finished.

    Here is the correct version:

    test('asynchronous test', function() {
    	// Pause the test first
    	stop();
    
    	setTimeout(function() {
    		ok(true);
    
    		// After the assertion has been called,
    		// continue the test
    		start();
    	}, 100)
    })
    
    a correct example of asychronous test

    Here, we use stop() to pause the test case, and after the assertion has been called, we use start() to continue.

    Calling stop() immediately after calling test() is quite common; so QUnit provides a shortcut: asyncTest(). You can rewrite the previous example like this:

    asyncTest('asynchronous test', function() {
    	// The test is automatically paused
    
    	setTimeout(function() {
    		ok(true);
    
    		// After the assertion has been called,
    		// continue the test
    		start();
    	}, 100)
    })
    

    There is one thing to watch out for: setTimeout() will always call its callback function, but what if it’s a custom function (e.g, an ajax call). How can you be sure the callback function will be called? And if the callback is not called, start() won’t be called, and the whole unit testing will hang:

    unit testing hangs

    So here is what you do:

    // A custom function
    function ajax(successCallback) {
    	$.ajax({
    		url: 'server.php',
    		success: successCallback
    	});
    }
    
    test('asynchronous test', function() {
    	// Pause the test, and fail it if start() isn't called after one second
    	stop(1000);
    
    	ajax(function() {
    		// ...asynchronous assertions
    
    		start();
    	})
    })
    

    You pass a timeout to stop(), which tells QUnit, “if start() isn’t called after that timeout, you should fail this test.” You can be sure that the whole testing won’t hang and you’ll be notified if something goes wrong.

    How about multiple asynchronous functions? Where do you put the start()? You put it in setTimeout():

    // A custom function
    function ajax(successCallback) {
    	$.ajax({
    		url: 'server.php',
    		success: successCallback
    	});
    }
    
    test('asynchronous test', function() {
    	// Pause the test
    	stop();
    
    	ajax(function() {
    		// ...asynchronous assertions
    	})
    
    	ajax(function() {
    		// ...asynchronous assertions
    	})
    
    	setTimeout(function() {
    		start();
    	}, 2000);
    })
    

    The timeout should be reasonably long enough to allow both callbacks to be called before the test continues. But what if one of the callback isn’t called? How can you know that? This is where expect() comes in:

    // A custom function
    function ajax(successCallback) {
    	$.ajax({
    		url: 'server.php',
    		success: successCallback
    	});
    }
    
    test('asynchronous test', function() {
    	// Pause the test
    	stop();
    
    	// Tell QUnit that you expect three assertions to run
    	expect(3);
    
    	ajax(function() {
    		ok(true);
    	})
    
    	ajax(function() {
    		ok(true);
    		ok(true);
    	})
    
    	setTimeout(function() {
    		start();
    	}, 2000);
    })
    

    You pass in a number to expect() to tell QUnit that you expect X many assertions to run, if one of the assertion isn’t called, the number won’t match, and you’ll be notified that something went wrong.

    There is also a shortcut for expect(): you just pass the number as the second parameter to test() or asyncTest():

    // A custom function
    function ajax(successCallback) {
    	$.ajax({
    		url: 'server.php',
    		success: successCallback
    	});
    }
    
    // Tell QUnit that you expect three assertion to run
    test('asynchronous test', 3, function() {
    	// Pause the test
    	stop();
    
    	ajax(function() {
    		ok(true);
    	})
    
    	ajax(function() {
    		ok(true);
    		ok(true);
    	})
    
    	setTimeout(function() {
    		start();
    	}, 2000);
    })
    

    Conclusion

    That’s all you need to know to get started witih QUnit. Unit testing is a great method to test your code before publishing it. If you haven’t written any unit tests before, it’s time to get started! Thanks for reading!

  • February 01, 06:57 PM

    Primera imagen de The Smurfs: Es un pitufo, pero en blanco y negro

    cine Primera imagen de The Smurfs: Es un pitufo, pero en blanco y negro
    Aún sin tener su color característico, en UGO.com han publicado una de las primeras imágenes en la que podemos ver como resultará ‘The Smurfs‘ (‘Los Pitufos’) en su adaptación cinematográfica. Como pueden ver (y de paso comenzar a adorar) en la foto tenemos a Smurfy, quien no sabemos si es una especie de sobrenombre para todo lo que serán el electo digital de esta cinta, o bien un nombre especifico de alguno de los personajes. Ya sabemos que todo en el mundo de los Pitufos, contenía la palabra “Pitufo”. Por ahora, es difícil saberlo.

    El director de esta adaptación es Raja Gosnell (‘Scooby Doo’) bajo una producción que ha sido esencialmente toda de Columbia Pictures. Tiene fecha de estreno para el 29 de julio del 2011, así es que aún falta mucho tiempo para ver si realmente así terminarán siendo los pequeños pitufos. ¿Que opinan? La imagen completa, después del salto.

    cine Primera imagen de The Smurfs: Es un pitufo, pero en blanco y negro

  • January 29, 06:00 PM

    Crack a Wi-Fi Network's WEP Password with BackTrack, the Fancy Video Version [Wi-Fi]

    Last summer we detailed how to crack a Wi-Fi network's WEP password using BackTrack. Now video blog Tinkernut revisits the subject with a great video step-by-step of the process.

    Before you go calling the cops or putting on your bank robber mask, a helpful reminder from our original post:

    Knowledge is power, but power doesn't mean you should be a jerk, or do anything illegal. Knowing how to pick a lock doesn't make you a thief. Consider this post educational, or a proof-of-concept intellectual exercise.

    BackTrack has also updated to version 4 since we last featured it, but the process appears to have remained basically the same. The interesting thing about BackTrack is how easy it is to crack a WEP-encrypted network, which serves as a very good reminder to use WPA encryption to significantly boost your home network security.



  • January 22, 03:24 AM

    "Get a Mac" Complete Campaign

    Author: ccc
    Posted on: 2010-01-22 14:47:30

  • January 20, 05:59 PM

Me gano la vida desarrollando aplicaciones y otros afines a la tecnologia. Hoy por hoy, mis copilotos son Java y PHP, pero aprendo rapidamente y si el desafio es interesante, mejor aun.

rodrigo[at]800mostaza.com

Upgrade Flash to view this site properly