Hello Meteor


Javascript/AJAX

(modified from http://asynchrotron.com/blog/2012/05/22/hello-meteor/)

This post is for the benefit of all those who are feeling like they might be missing a step with frameworks like Backbone, Ember, (and now Meteor), et. al. Read on for recommendations on what to read up on to understand more about the problems they’re solving.

First a brief note about MVC

The Model-View-Controller application architecture (MVC) is used in most modern applications to separate an application’s data from its business rules and user interface. Briefly, Models represent an application’s data and functions to access it. Views represent information presented to the user. Controllers represent intermediary resources required to generate Views. The MVC pattern isn’t new (it can be traced back to Smalltalk), but it was popularized, along with the REST style of client-server API design by server-side web frameworks such as Rails and Django.

So what’s all the fuss about JavaScript MVC frameworks (Backbone, Ember, et. al.)?

If you think of the screens – or pages – in your application as different “states” in your application, server-side frameworks require a round trip back to the server when the user goes from one application state to another. This is fine for content-heavy apps or websites. Or if you’re accessing the pages via an ethernet cable or 802.11. But when you move to high latency connections and along the continuum — and I believe it really is a continuum — from a web site to a web app, you can deliver a much better user experience if you avoid the server round trip for each state change, and instead switch from state to state on the client, within a single browser page load cycle.

This saves you all of the overhead of destroying and recreating the DOM tree, flushing browser context (JavaScript, CSS, etc.) on each new page load. You also are transmitting less data on the wire (or ether) since HTML is generated on the client, and only JSON passed over the network. Both of these factors (page refresh time and network traffic optimization) are significant when you consider the fact that more and more internet usage is taking place via mobiles and tablets.

You would still need a server to authenticate users and perform other privileged operations, and to store the “official” version of the data that different clients synchronize with, but instead of sending dynamically created HTML to the client (a la aforementioned server-side frameworks) the server would send as much data as needed (typically as JSON) to the client, and the client would create all of the different application states dynamically. The problem with this approach — and I’ve been writing apps this way since 2008, without the benefit of any client side frameworks — is that they quickly turn into a mass of spaghetti code.

This is where the likes of Backbone, Ember, etc. come in. They are a re-imagination of the MVC application architecture for JavaScript application development in the client, where all (or nearly all) application states are handled in the client, in JavaScript. They provide a way to structure your JavaScript applications in a more organized MVC style.

Addy Osmani’s articles, and especially his Backbone Fundamentals book are a great place to start reading more about this. Although it’s focused on one specific framework (Backbone), it has a good overview of MVC and how the pattern has moved from server side frameworks (like Rails, Django) to the client side (Backbone, et. al.).

I also wholeheartedly recommend his recent talks on providing structure to JavaScript apps.

And this is a useful comparison of various front-end frameworks, although the conclusions should be taken with a grain of salt (it’s one persons’s perspective, and things are not quite as quantifiable as the article suggests):
So, all of these are client side frameworks, which solve the problems of a) separating client side code into MVC, and b) optionally, allowing views to “observe” client side models, so that views get updated automatically as the data in the models is updated or as new data arrives from the server.

This gets you pretty far, but all of these applications have something else in common which the previously mentioned MVC frameworks don’t address: They need to send data back to the server and check in if data has changed on the server. In other words, they need to synchronize client side models with the server side models.

Enter Meteor.

Meteor is a full stack framework for end-to-end JavaScript applications. The beauty of coding it all in JavaScript is that you can easily implement the observer pattern (views watching for changes to the models) all the way to the server side. Meteor
apps can subscribe to models (or subsets of models) on the server, and meteor takes care of all of the plumbing. This really is the bleeding edge of JS today.

For more on the problems Meteor solves, read the Meteor docs from the intro section through to as many of the detailed concepts you’re interested in. Or come to my talk at JS.Chi() and we will work through it together. Here are the slides from the talk.

Have fun!

Pallavi

ASP.NET Membership.GetUserNameByEmail Error: “The E-mail supplied is invalid.”


.NETASP.NETC#LanguagesTips and Tricks

What the heck does this error message mean?? I had cause to find out when I was getting this error in a method that was simply updating the email address for an existing user. Mind you, I wasn’t creating a new user – I was just updating an existing user.  Since the error message is less than helpful, I thought I’d post this so anyone else getting this error won’t have to search as much as I did to find the solution.

Here’s how it came into play: I had created a secure web page to allow my client to manage some of their user accounts. They often had requests to change the email address for the account, so I created a simple form with a couple of text boxes (tbChangeEmail_Old and tbChangeEmail_New), a label to display the status of the attempt (lblChangeEmail_Status) and a Submit button.

Here’s the code I was using, when the user clicked the Submit button:

try
{
   string username = Membership.GetUserNameByEmail(tbChangeEmail_Old.Text);
   if (!string.IsNullOrEmpty(username))
   {
      MembershipUser user = Membership.GetUser(username, false);
      user.Email = tbChangeEmail_New.Text;
      Membership.UpdateUser(user);
      lblChangeEmail_Status.Text = "Email address successfully changed.";
   }
   else
   {
      lblChangeEmail_Status.Text = "Unable to find user with that email.";
   }
}
catch (Exception ex)
{
   lblChangeEmail_Status.Text = "Error: " + ex.Message;
}

It’s pretty straightforward – attempt to get the username using the ‘old’ email, and if the account isn’t found, display a message to the user. If we do find the username, then use it to get a MembershipUser object, set the Email property to the ‘new’ value, and update the user. Wrap that up in a try/catch block, and we’re good to go.

Everything worked fine, until today, when my client reported she was getting an error message for one user: “The E-Mail is invalid.” Huh. Did that mean the new email address wasn’t a valid email format? No, the new email was fine. Did it mean the old email didn’t work and the user wasn’t found? No, the test for !string.IsNullOrEmpty(username) catches that, and I verified that the account with the old email address was present. So what’s going on?

I did the usual trick of Googling for a solution, and found a lot of forum questions related to creating a new user, but then I finally found something about DUPLICATE emails, which, of course, are not allowed in the Membership database, based on our configuration. Aha! I did a quick SQL query of the DB, and sure enough, there was already an account with the ‘new’ email address, so it was not possible to update the ‘old’ account with the ‘new’ address!

So, since the existing error message is less than helpful in this case, I changed the logic in the catch block, so I could display a more helpful error on the web page:

catch (Exception ex)
{
   if (ex.Message.ToLower() == "the e-mail supplied is invalid.")
      lblChangeEmail_Status.Text = "There is another account with the 'new' email address, so the 'old' email account cannot be updated.";
   else
      lblChangeEmail_Status.Text = "Error: " + ex.Message;
}

Now, if we run across another case like this, my client will know exactly what’s going on. No more ambiguous error messages! J

So, not earth-shattering .NET stuff, but I figure what I learned might help someone else in the same situation. Happy coding!

Displaying another app’s data using HTTParty and Kaminari


RailsRuby

I needed to access some data from another app and display it to users. The api side was a Rails 2.3.11 app and used will_paginate. It returned the json of a model collection and an association along with paginator information. The client side was a Rails 3.1 app using HTTParty and Kaminari.

API Controller

Rails 2.3.11 doesn’t include associations in the json, which is a known bug. So I returned a collection with the two models’ information. I used an API key to authenticate, which I won’t describe in detail since it’s outside the scope of this post.

class Api::FoosController < ApplicationController
  before_filter :authenticate_api_key!

  def foos_index
    @foos = Foo.paginate(:order => "created_at desc", :per_page => 40, :page => params[:page], 
        :include => :bar)
    @records = @foos.collect { |foo| {:foo => foo, :bar => bar} }
    render :json =>  {:records => @records, :total_entries => @foos.total_entries, 
        :per_page => @foo.per_page }
  end
end

API Route

The route requires the page number.

  map.connect '/api/foos/foos_index/:page', :controller =&gt; "api/foos", :action =&gt; :foos_index

Client Model

FooIndex.foos_index returns itself, along with accessors for the response, records, total_count, current_page, and limit_value. The last three are important for Kaminari. When I parsed the JSON, I symbolized the keys. Much prettier than strings.

class FooIndex
  include HTTParty
  base_uri ENV['FOO_APP_URL']
  default_params :api_key =&gt; ENV['FOO_API_KEY']
  format :json
  attr_accessor :response, :records, :total_count, :current_page, :limit_value

  def initialize(response, records, total_count, current_page, limit_value)
    self.response = response
    self.records = records
    self.total_count = total_count
    self.current_page = current_page
    self.limit_value = limit_value
  end

  def self.foos_index(page)
    @current_page = page || 1
    response = get("/api/foos/foos_index/#{@current_page}")
    if response.success?
      json = JSON.parse(response.body, symbolize_names: true) 
      self.new(response, json[:records], json[:total_entries], page, json[:per_page])
    else
      raise response.response
    end
  end
end

Client Controller

I had to be creative with Kaminari using the paginate_array method. The options total_count and limit are used because the api doesn’t return the whole set of data, just the data for one page.

class FoosController &lt; ApplicationController
  def index
    params[:page] ||= 1
    @foos_index = FooIndex.foos_index(params[:page])
    @paginated_array = Kaminari.paginate_array(@foos_index.records, 
        total_count: @foos_index.total_count, 
        limit: @foos_index.limit_value).page(@foos_index.current_page)
  end
end

Client Route

Page number is optional in the route. The controller defaults it to page 1.

  match '/foos(/:page)', :controller =&gt; :foos, :action =&gt; :index

Client View in HAML

The json returned by the api doubles up the first part of the hash. I’m not sure of an elegant way to handle that.

= paginate @paginated_array

%table
  %thead
    %th Foo Name
    %th Bar Name
    - @foos_index.records.each do |record|
      %tr
        %td= record[:foo][:foo][:name]
        %td= record[:bar][:bar][:name]

= paginate @paginated_array

And that’s all it takes. Please comment with any comments or questions.

About Angel N. Sciortino

Ruby programmer. Sysadmin. Queer and polyamorous. Welder. Crocheter and darner. Chaotic good.

More Posts by Angel N. Sciortino - Author Website

DevChix Speaking at Conferences 2012


Events

We’ve collected a list of the DevChix speaking at conferences (so far) this year. If you are at one of these conferences, be sure to say hi!

January

February

March

April

May

June

July

Meet devChix member Susan Potter


IntroductionsPeople

Susan Potter is a wearer of many hats, but mostly software engineer and practicing applications architect (based in Chicago, IL).

Employer: Finsignia

Extras: Last month, Susan presented at WindyCityDB conference in Chicago, IL on Link-walking with Riak. She was a speaker at Code PaLOUsa 2011 in June. Talk: Deploying distributed software services to the cloud without breaking a sweat. She is very active in the open source community with GitHub personal repositoriesTwitter4R and collection of Gists.


Our short Q&A with Susan Potter:

What is your technical background?

At university I studied Mathematics, but audited Computer Science courses while writing an experimental parallel and distributed PDE solver first in C, then in C++ and finally in Java, which didn’t have much utility other than to teach me how not to write multi-threaded or distributed software.After graduating I worked for investment banks in London before skipping off to a San Francisco startup building a B2B trading platform and have since been working as a senior software consultant for hedge funds, investment banks and technology startups all over the US.

What industry sites or blogs do you read regularly?

To be honest, I use my Twitter timeline and some private lists as a fairly reliable source of interesting, relevant and/or thought-provoking technical resources from all over the internet. However, the following links have been fonts of recent software engineering wisdom or great resources in the areas I currently practice within:

What are a few of your favorite development tools and why?

I recently wrote a blog post on the (types of) tools that have made me a better software engineer. In short these are: emacs, vi(m), make, gdb, UNIX commands / utilities, UNIX shells, LaTeX, Git. The blog post explains why.

What tip or advice would you like to impart to women interested in programming?

If you enjoy software development, always learning new things and are excited about the possibilities in this field, then do not let anyone discourage you from persuing it further. There will always be a job market for self-starters that can teach themselves even if they don’t have the right educational background. Make sure to back up what you have learned on your own. Open source projects, blog posts or screencasts that demonstrate your skills in the areas you are looking to get into help much more nowadays than simply having a CS degree with no public portfolio IMHO.

If you were a computer part, what would you be?

A CPU socket comes close. It provides multiple connections (mechanical and electrical) between the microprocessor and circuit board. In the technology community it seems I am always connecting people based on their interests and needs such as connecting business founders with technical founders or hiring managers with skilled developers (mechanical connections). Other times I am suggesting new architectures, software stacks, tools, etc. to solve the problems people I talk to are currently encountering (electrical connections).

About Carmelyne Thompson

With 14 years experience in web development consistently learning new technologies; Loves: user interface design, programming & being an entrepreneur

More Posts by Carmelyne Thompson - Author Website