Seventh Octave

We're Starters. We write about culture, design and the business of software.

We believe software should be beautiful and inspired. Follow us as we build TechOctave.

NHibernate: The Good Parts Tian Feb 08

Post a comment

NHibernate is an Object Relational Mapper (ORM) for the .NET Runtime. XML Mappings are still the most popular method of mapping persistent classes to their relational tables.

Inspired by the success of Fluent NHibernate and what Martin Fowler calls the Fluent Interface, NHibernate 3.2 will feature its own NHibernate Mapping by Code API.

With such change abound, I thought it a great opportunity to layout the fundamentals of XML Mappings. In the process, we'll also delve into a few core development laws I use regardless of platform.

spacer

Elements of Object Oriented Software

Particularly with static languages, I adhere to two core object oriented design principles. These principles were first applied in Design Patterns: Elements of Reusable Object-Oriented Software by The Gang of Four - Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides:

  1. Program to an interface, not an implementation.
  2. Favor object composition over class inheritance.

These design principles form the basis for maintainable NTier'd applications both on the J2EE and .NET Runtimes.

Let's take a look at a domain model that implements these core object oriented design principles. Let's model a blog Post:

The Post Interface (IPost.cs)

The interface exposes the public properties and methods of a persistent class in your domain:

public interface IPost
{
    int Id { get; set; }
    string Title { get; set; }
    string Content { get; set; }
    IAuthor Author { get; set; }
    IList<Comment> Comments { get; set; }
}

The Post Implementation (Post.cs)

The Post class implements the IPost interface. Here, we assume the Author class and the Comment class are defined elsewhere:

public class Post : IPost
{
    private int id;
    private string title;
    private string content;
    private IAuthor author;
    private IList<Comment> comments;

    public Post()
    {
       author = new Author();
       comments = new List<Comment>();
    }

    public virtual int Id 
    { 
       get { return id; } 
       set { id = value; } 
    }

    public virtual string Title
    { 
       get { return title; } 
       set { title = value; } 
    }

    public virtual string Content
    { 
       get { return content; } 
       set { content = value; } 
    }

    public virtual IAuthor Author
    { 
       get { return author; } 
       set { author = value; } 
    }

    public virtual IList<Comment> Comments
    { 
       get { return comments; } 
       set { comments = value; } 
    }
}

Each Post has an Author and a list of Comments. In the Post constructor, I create instances of each domain object.

Rarely does a problem domain ever break down to neat hierarchical entities. The majority of domain models are usually composed of another model or a collection of other models that it does work on or relies on.

That's why understanding object composition is so important. Object composition gives you the freedom to model the world as you see it without the self-imposed restrictions that come with being inheritance focused.

The real problem is inheritance breaks encapsulation because it exposes a subclass to details of it's parents implementation.

These implementation dependencies can cause problems when trying to reuse a subclass. Should any aspect of the inherited implementation not be appropriate for new problem domains, the parent class must be rewritten or replaced by something more appropriate. This dependency limits flexibility and ultimately reusability.

On the other hand, Object Composition requires objects to respect each others interfaces, which in turn requires us to carefully design interfaces that don't stop you from using one object with many others. Because objects are accessed solely through their interfaces, we don't break encapsulation.

Favoring object composition over class inheritance helps you keep each class focused on one task - The Single Responsibility Rule. You classes and class hierarchies will remain small and will be less likely to grow into unmanageable monsters.

NHibernate XML Mappings

NHibernate XML Mappings are a way to map our domain objects to their corresponding database tables.

Using NHibernate, the database becomes an implementation detail and you can spend more time understanding your problem domain and less time fiddling with database tables.

Here's how we would map our Post class:

The NHibernate Mapping (Post.hbm.xml)

Here, we'll assume the Author class is mapped in Author.hbm.xml and the Comment class is mapped in Comment.hbm.xml:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="Blogcast.Domain"
                   namespace="Blogcast.Domain"
                   default-lazy="true">

  <class name="Post" table="Posts">
    <id name="Id" unsaved-value="0">
      <generator/>
    </id>

    <property name="Title"/>

    <property name="Content"/>

    <many-to-one name="Author" cascade="all-delete-orphan"/>

    <bag name="Comments" cascade="all-delete-orphan">
      <key column="PostId"/>
      <one-to-many/>
    </bag>
  </class>
</hibernate-mapping>

Top to bottom, here are some major key points to take away from this NHibernate class map:

Lazy Loading

There are time when you don't need to fetch the entire object graph. Setting default-lazy="true" ensures NHibernate will only request the entity data you requested at a given time.

Also, if you use lazy loading (which I highly recommend you do), you need to add the virtual keyword to each of your classes' public properties and methods.

Orphaned Data

We can all agree orphaned data isn't a good thing. Set the cascade property to "all-delete-orphan" to delete data that would otherwise have been orphaned forever. This issue generally comes to light when handling custom types or lists of custom types.

Class Properties

System Types - (int, string, bool) are defined using the property tag.

Custom Types - (Author) are defined using the many-to-one tag.

Lists of Custom Types - (List of Comments) are defined using the bag tag with a one-to-many relationship to the Custom Type (Comment). Here, each instance of a Comment has an associated unique Post instance. Therefore, PostId needs to be a public property on the Comment class. Then NHibernate an properly associate each Comment to the correct Post.

Take away

Today we covered a modern approach to object oriented programming. We also covered how to flush out a domain model and how to map its custom types in NHibernate.

NHibernate is a fine piece of software. Sometimes the hardest part is understanding how to map your custom classes. I hope this article helps in understanding the mapping between your domain's custom types and lists of custom types.

Don't worry, you'll be an ORM Boss in no time. Godspeed and Happy Coding. Go get 'em!

The Future is JavaScript Tian Jan 15

2 comments Latest by TVD

JavaScript has come a long way as a language. With faster browsers and a growing community of dedicated developers, it's poised to take the web places we can hardly imagine today. The future is JavaScript and the future is now.

From JavaScript Charts, to presentation platforms, to games - JavaScript is enabling productivity and entertaining us to boot. I believe single page apps and client-side heavy apps are the future. A lot of big players seem to agree.

Big Players For A Big Time

Mozilla + Firefox - XUL = JetPack

The Mozilla Corporation - the fine folks behind the Firefox Web Browser - recently invested heavily in modernizing Firefox's add-on development infrastructure and now we have Firefox JetPack:

spacer

With JetPack, you can create add-ons for Firefox using modern web standards like HTML5, CSS3 and JavaScript. Prior to this advancement, our only option was to use Mozilla's proprietary XML User-Interface Language or XUL.

XUL was cross-platform - yes. But, it was a pain to work with and not exactly beautiful. With JetPack, all that is going to change. Expect a Firefox add-on renaissance. But, Mozilla isn't the only company innovating in the client-side space.

Google + NaCl = Tasty

Google is also betting that heavy client-side JavaScript is the future. From day one, the promise of the Chrome Web Store has always been apps built on open standards (HTML5, CSS3 and JavaScript). In fact, one of our products - Tweetlr - A Powerful Twitter CRM - is built on the foundations of that promise. Open standards and a monetization platform could have been enough - should have been enough. But for a company where innovation is everything, enough is never enough. Enter Native Client:

Recently, Google released functionality in Google Chrome that gives Chrome developers the ability to run native C or C++ code in their Chrome web applications. Google calls this Native Client and promises you can run your native code on the web. Combine the back-end power of C/C++ with the responsiveness of HTML5, CSS3 and JavaScript and I believe you get a powerful architecture that doesn't even need a server.

A few folks have wondered whether Chrome's Native Client (NaCl) is simply the next ActiveX and rightfully so. The answer is no and the key to that answer lies in NaCl's distribution model.

The Chrome browser only runs Native Client applications published through the Chrome Web Store (CWS). This has some very important implications.

Whereas an ActiveX object is dependent on an entire Operating System (Microsoft Windows), a Native Client module is only dependent on the Chrome browser. The Chrome browser is cross platform - which means it runs on Windows, Mac and Linux. By extension, an application written with Native Client would have reach that far exceeds any ActiveX app. So pick your OS of choice and keep your apps because Chrome runs on every platform.

Google + NaCl + Product = Profit

Native Client apps are cross platform, but they aren't currently meant to be cross browser and we shouldn't expect them to be either. NaCl is about apps and the app market is part of JavaScript's future too.

With Native Client, there will never be the "Best viewed in Internet Explorer" atrocities. When customers purchase from the Chrome Web Store they know and understand their app only runs in Google Chrome. Is this any different than when we purchase an app from Apple's App Store?

Developers shouldn't have to choose between native speed and open standards. NaCl is meant to level the proverbial "playing field" and give open web app developers access to speeds and resources once only available in Objective-C and iOS or Java and Android.

Financial Times + HTML5 = Happy Customers

Even the Financial Times gets it. spacer

Betting big on the future of HTML5, the Financial Times stepped out of the shadow of Apple's App Store and into the light of HTML5, CSS3 and JavaScript.

This puts them in a better position to compete in the iPhone and iPad space - arguably the future of the Newspaper & Magazine industry itself.

Google Chrome Experiments

To showcase JavaScript and the open web, Google created Chrome Experiments. A showcase of creative talent in HTML5, Canvas, SVG, and WebGL.

They believe JavaScript is awesome and browsers are awesome and that together, they can do some beautiful, magical, crazy things. I couldn't agree more. Here are a few of my favorite experiments:

WebGL Globe by Google Data Arts Team:

I absolutely love data visualization, so this experiment was a top pick for me. Yes, those are JavaScript Charts on those continents.

WebGL Bookcase by Google Data Arts Team:

WebGL Bookcase is an experimental interface for the Google Books API.

Baroque.me by Alexander Chen:

Baroque.me visualizes the first Prelude from Bach's Cello Suites. Using HTML5 and JavaScript to highlight the music's underlying structure and subtle shifts.

spacer

3 Dreams of Black by Google Data Arts Team:

3 Dreams of Black is truly an experience you don't want to miss. I recommend grabbing some Kombucha for this one.

Impress.js by Bartek Szopka:

Impress.js struck me as a truly remarkable presentation platform. I'm pretty sure I'm using it for my next talk.

spacer

X-Wing by OutsideOfSociety:

It's a combination of JavaScript, code and Star Wars. This is the pinnacle of Geekdom.

spacer

The Smart Money's on JavaScript

JavaScript is a beautiful language. It's the future. Sometimes it feels like the weight of history itself beckons its success. I'm not a betting man by any standards. But I guarantee, the smart money's on JavaScript. And you can take that to the bank.

Beautiful cross browser JavaScript dashboard charts Tian Jan 01

Post a comment

Recently, we released our JavaScript Charts Suite. They're perfect for creating a business intelligence dashboard that gives Senior Management an intuitive pulse on the enterprise.

Our JavaScript Charts Suite includes a highly configurable API. Choose from over 30+ customizable properties to design the exact chart you need. Build your own executive level dashboard. Beautifully illustrate your data.

We believe software should be beautiful and inspired. Data is no different. Beautiful data is easier to understand and faster to comprehend. Your users will thank you:

spacer

Six Core Principles

We built our JavaScript Charts Suite on Six Core Principles:

  1. Beautifully Illustrated
  2. Cross Browser Compatible
  3. Lightweight Footprint
  4. Vector Based for Crisp Zoom and Print
  5. Highly Configurable
  6. Framework Agnostic

We know you have tight deadlines and constraints. We know you value quality and craftsmanship. We know you'd rather not sacrifice one for the other. That's why we built our JavaScript Charts Suite to deliver just what you need and nothing more.

Show. Me. The. Codes. Please!?!

We believe in developing with intelligent defaults. For you, this means you can get each of our JavaScript Charts running quickly and easily:

var sales = new PieChart("sales");
. . .
<div id="sales"></div>

That's it! This is the minimum requirement to render one of our JavaScript Charts. Time to up the ante.

You'll want to populate each JavaScript Chart with your own data and maybe add legend titles and legend labels:

var purchases = [55, 20, 13];

var sales = new PieChart("sales", {
    data: purchases,
    legendTitle: "Sales",
    legendLabels: ["United State", "Canada", "Brazil"]
});

. . .

<div id="sales"></div>

There are a ton more properties you could configure. In fact, each JavaScript Chart comes with over 30+ configurable properties.

Our JavaScript Charts are elegantly responsive and update dynamically with ease. So use your JavaScript Polling method of choice and update your chart instance like so:

(function poll(){
    $.ajax({ url: "server", success: function(data){
        sales.setData(data); //Update pie chart

    }, dataType: "json", complete: poll, timeout: 30000 });
})();

To poll the server, this example used jQuery. But, we believe in framework agnosticism and believe you should have the freedom to choose whichever JavaScript framework you please. So go ahead!

Our JavaScript Charts are framework agnostic. jQuery, Prototype, Mootools, ExtJS...Forget about it...We've got you covered. We believe data is most free when it's beautiful and dynamic - that's it! The rest of the decisions are in your hands - where they should be!

There are just too many goodies to mention in a single post. So seriously, pick your team up a copy of our JavaScript Charts. You're next project deserves our JavaScript Charts. You know what? You deserve our JavaScript Charts!

We're Developer Too

We're developers too. We've been there. We know requirements shift and enhancements are right around the corner. We want you to be positioned for success.

Our JavaScript Charts work in every browser that supports Standard Vector Graphics (SVG) - it just works! We're pixel perfect.

Using jQuery Mobile, we're your best fit. Working on an iPad app, your customers will be impressed with the quality of each chart. With crisp zoom and a crisp, clean print, your customers will be impressed.

Best part is we're framework agnostic. That means you can use your favorite JavaScript framework: jQuery, Prototype, MooTools, ExtJS, Dojo - we're compatible with them all.

With over 30+ configurable properties, each JavaScript Chart is highly configurable. Create the perfect chart you were thinking about. Tweak and adjust all your heart desires.

Each purchase comes with a year of support. Have a quick question. Talk to the Lead Developer directly. No middle men. No outsourced customer service. We're here for you!

Looking for a JavaScript Charts Suite that Rocks? Checkout our JavaScript Charts Suite today.

Prototypes and The Law of Conservation of Quality Tian Dec 29

Post a comment

Prototyping is hard, but good for business. It's a necessary phase between idea and product. It's the double rainbow between you and your customer. No Unicorns.

We apply prototyping to all of our products. Here are some lessons learned from our latest product - JavaScript Charts Suite. We hope you enjoy!

Great products evolve from great prototypes...

Good prototyping isn't easy either. It takes sacrifice and diligence to introspect and seek the right questions before coming to a "solution". Think about it...What could you have been doing instead of prototyping? Working on client work? Jumping straight into production code?

My point is prototyping takes time away from other activities. But, I posit this, "Great products evolve from great prototypes." Without dedication to the prototyping process, a continuous loop of feedback, what are we left with? Luck? I prefer iterations over luck.

Don't get me wrong, I respect Lady Luck. I just believe she favors those who Tango with purposeful intent. With our Dashboard Chart Suite, prototyping is both meaningful and purposeful.

Prototypes are Functional Concepts

The scope of a prototype is really up to you. Each can vary based on what you're trying to accomplish. Prototypes are functional concepts.

Prototypes should help you: 1) Get a feel for the problem domain; 2) Get something solid enough where you can begin soliciting feedback.

Our Dashboard Chart Suite has several prototypes we feel represent core functionality. For example, here are two:

spacer spacer

Left: Scatter Chart, Right: Column Chart

A good prototype allows you to have a conversation about complexity. Hypotheticals are removed and you can quickly get down to brass tacks. I follow a series of methodical questions when I prototype:

  1. What environment will this product be used?
  2. Who is going to use this product?
  3. What is the motivation to use this product?

What environment will this product be used?

Here, I'm trying to figure out the operating constraints of the product: Will it be used in a web application? Or will it be used in a Desktop application? Or is it a server utility?

These are the basis for my digital product questions. But, I'm an Engineer by training so hardware products aren't out of scope. For hardware products, you might ask: How will the user interact with the device? What communication protocol(s) need to be available? Is the context a laboratory? Is the context someone's home? Or, is the context someone's business?

Some questions are useful for both software and hardware: Is this a stand alone component? Is this product a single piece to a much larger puzzle? Is this piece mission critical? What will this product mean to the success of the larger initiative?

It's important to know which environment your product will be used. Knowing this will help you value your product. It will also help your customers value their time.

Who is going to use this product?

Here, it's important to reflect on who the end user is. Call it, "Getting inside their head". Call it "User Profiles". Call it, "End User Analysis". Whatever you call it, make sure you spend time empathizing with the end user. Make sure you spend time thinking about (their) level of experience - not yours.

Most of my customers are developers. I'm a developer too. So I can make a pretty good call as to what makes sense and what doesn't. But, your situation may be different.

Maybe your customers are designers. What if you're not a designer? All that means is you'll have to spend a little more time upfront understanding how they work and why.

Fundamentally, the answer to this question helps you understand how much complexity you have liberty to expose and how much you simply need to keep hidden.

What is the motivation to use this product?

This is where you get down to brass tacks and truly evaluate the value of what your prototype can become. Why is the customer here? Why don't they just build the product themselves? Are they trying to save time? Are they trying to save money? Are they trying to save both?

Maybe your customers value beauty. I believe in beauty. I believe software should be beautiful and inspired. This is a core value. People value functional things, but they love beautiful things. As you evaluate motivation try to remember that.

Intelligent Defaults

I not only value beauty, I also value aforethought and conviction. That's why I believe in Intelligent Defaults.

I believe each product should be able to run with as minimum configuration as possible. This concept is a hallmark of our Dashboard Gauge Suite and our customers love it. Intelligent defaults increase confidence and decrease learning curve.

I say learn to love intelligent defaults. Apply them without haste. It's good for the end user and it's good for you too. Intelligent Defaults are good for you because they communicate clean interfaces from which to work from.

For example, which do you believe is cleaner code?

Interface One (Uses Intelligent Defaults):

var data = [["2010", 150, 99, 350, 1200],
            ["2011", 25, 120, 2400, 540]];

var sales = new BarChart("sales", {"data": data});

An instance of the BarChart object sales is instantiated and beautifully drawn on your screen.

Interface Two:

var data = [["2010", 150, 99, 350, 1200],
            ["2011", 25, 120, 2400, 540]];

var sales = new BarChart();

sales.SetProperty("id", "sales");
sales.SetProperty("data", data);

sales.SetProperty("colors", ["#FF2400", "#E25822", "#F2F2F2", "#B22222"]);

sales.SetProperty("fill", true);
sales.SetProperty("width", 200);
sales.SetProperty("height", 200);
sales.SetProperty("scaling", 0.5);

...

sales.drawGraph();

There were a few more properties to set before a "valid" BarChart could be rendered. But, let's cut to the chase. Your project is behind schedule and the boss is getting antsy for results. Which philosophy do you wish guided the development of your components?

Intelligent Defaults are core to your DNA

Intelligent Defaults can and should go further than user experience. Indeed, I believe Intelligent Defaults should be at the DNA of our products.

In the example above, why use the new keyword at all?

The first example could go from:

var sales = new BarChart("sales", {"data": data});

To:

var sales = BarChart("sales", {"data": data});

With well executed constructor code:

function BarChart(id, options) {
   if(window === this) {
      return new BarChart(id, options);
   }
   ...
}

What this means is the end user gets the benefits of a fully instantiated object without ever having to worry about forgetting the new keyword.

With this attention to detail, the new keyword would never slip through the cracks. That means the end user doesn't have to worry about potentially overriding data. That means less logic errors will occur. Less testing time will be needed. Indeed, less development time will be needed. That's why I always say, "Quality has a price and it's not a question of if you'll pay, but when."

The Law of Conservation of Quality

The Law of Conservation of Energy is a fundamental law of physics. It states, "The total amount of energy in an isolated system remains constant over time. Therefore, the total energy is said to be conserved over time."

For an isolated system, this law means that energy can change its location within the system, and that it can change form within the system, but that energy can be neither created nor destroyed.

I believe there is a corollary in software development. I call it The Law of Conservation of Quality. It states, "The total amount of quality in an isolated software project remains constant over time."

From a pragmatic standpoint, this means to increase quality, we need to add quality. This could come in the form of quality components, quality processes and most importantly, quality people.

Quality doesn't come out of thin air, it's either bought upfront or bought later. Eventually, someone pays the price and the many benefit.

Those people go by many names. Some call them Pioneers. Some call them Leaders. I call them Customers.

Looking for an easy to use JavaScript Charts library with a powerful API? Checkout our JavaScript Charts Suite. We believe in quality because we're developers too.

Blogcast 1.1.0 is Here! Tian Dec 25

Post a comment

A year ago, we set out to change the way creatives built community. That day, a better way to blog was born - Blogcast was born!

spacer Merry Christmas and Happy New Year!

In that time I've met so many wonderful designers, developers and UX professionals. Thousands of downloads later, we're happy to say Blogcast provided the exact value we so hoped it would.

We believe in giving back. Blogcast has always been our way of saying, "Thank you!" Thank you to the community for all you do collectively. The world, indeed our very professions, wouldn't be possible without the many and thankless contributions of countless designers and developers worldwide.

As always, there will be bugs to fix and features to add. But, what's great is we'll do it together. On my shortlist is User Authorization Roles. Ryan Bate's excellent CanCan library comes to mind. Any takers?

Well, without further ado, please do enjoy Blogast 1.1.0. You can download from the Official Blogcast website or from the Official Blogcast Github Repo:

git clone git://github.com/tiandavis/blogcast.git
cd blogcast
bundle install

Then jump right in:

rails server
localhost:3000/admin
login with l/p: admin

Blogcast Revamped and Reworked

  1. Restructured JavaScript assets. Main => blogcast.js. All 3rd party librarie in /librarie folder.
  2. Fixed default Comment text not highlighting bug. Using HTML5 Placeholders now.
  3. Added AutoSave functionality to New Post and Draft. Shoutout to the Backbone.js Team.
  4. Added Shortcut Key Save. Mac OS X => Command + s. Windows => Ctrl + s.
  5. Added ability for admins to Edit Comments. Simply click the edit icon.
  6. Upgraded to Rails 3.1.0
  7. Updated jQuery 1.4.3 to 1.6.4
  8. Updated Entourage 1.0.0 to 1.1.0
  9. Updates Rails.js 1.0.0 to 1.0.12
  10. Added Backbone.js support
  11. Added Underscore.js support
  12. CSS3 Cleanups

Take care folks! Have a Merry Christmas and a Happy New Year! Be excellent to each other.

Libertango Tian Dec 17

Post a comment

Astor Piazzolla was an Argentine composer who revolutionized the traditional tango. Incorporating elements from both jazz and classical music, Piazzolla's Nuevo Tango reshaped it's traditional cousin.

Luis Bacalov - Libertango (Astor Piazzolla):

It's funny how one art makes you appreciate another. Starters can learn a lot from Piazzolla. Whatever you're doing and wherever you're at, give a piece of your soul to your quest. I don't care if you're in development, design or business development - give of yourself!

At approximately time 3:30 the performer begins one of Piazzolla's most intense bandoneon discourses I've yet to hear. His music is enthralling and almost hypnotizing. At the end, you feel like you left with a piece of Piazzolla. You feel because he gave of himself.

Piazzolla took what could've been a mundane instrument and turned it into fire! Smoldering, piercing heat with a dash of grandiosity and I loved it!

Here, the instrument didn't make the man or the performance. The man was the performance. My point is this...Your technology stack, your infrastructure, your access to capital or whatever else simply doesn't matter!

What matters most is you! It isn't Ruby, it's Matz. It isn't Rails, it's David. It isn't Virgin, it's Sir Richard Branson. Fill in your own blanks...

Whether you maintain legacy applications or run with bleeding edge application stacks, my challenge to you is to fill in your own blanks.

And always remember it's never the technology that makes the project, it's the people who give it life.

When the Gods demand a sacrifice, don't be afraid to give of yourself. There is true strength in sacrifice. Done with earnest, a man can turn a framework into a way of life and a bandoneon into a Libertango.

Silicon Valley is the Ellis Island of Entreporn Tian Dec 10

Post a comment

The problem with the Silicon Valley fantasy is the inherent escapism. You have to run away from your life’s challenges and opportunities to pursue “The Dream” in some unfamiliar place. Silicon Valley is the Ellis Island of Entreporn.

spacer

If you insist, go to California. By all means stake your claim. It's always been the place to be if you're in a rush. But please don't pretend to be there for the customer. The truth is you don't plan or want to be there any longer than you have to.

Business is about execution and sticking around and that’s the kind of business owner I feel comfortable giving my money to. If you’re not even planning to be around for long, then what’s the point of me forming a relationship with you?

What’s the point of me relying on your tools or building my business on top of your platform if you’re only here until the next best offer arrives?

The myth of the price conscious customer Tian Dec 03

Post a comment

Andy Budd had a great article today called "Why designers are holding themselves back". But that article could have easily been titled, "Why developers are holding themselves back?"

spacer

How would you like your application development?

We've been taught our entire lives to believe in the notion of limited resources. So when we start our own companies, it is easy to make believe that clients are limited and that the value of our services are limited too.

It's easy to believe you are a commodity, but I can tell you from experience that you are not! You are not a commodity and neither are your customers.

There are more customers whose primary concern is value and reliability than there are those who can only ever see price. Take for example our Dashboard Gauge Suite.

Customers pay good money for our dashboard gauges. This is a fact. I know this and I can appreciate this. What they get in return is not only a product that far exceeds anything on the market, but they also get access to the source and the lead developers of the software.

What this means is if they have suggestions, get stuck or need help, there is a real person behind the product to help them get to where they need to be.

Try getting that type of hands-on attention from closed source companies and companies that fancy themselves the next Microsoft. It's just not happening.

My point is, your best customers expect to pay premium because your best customers expect premium service.

A lot of us go into this industry expecting to be the next big thing. But what does that even mean? It's hard to define. It's intangible. I for one don't even know what that is.

But there are values I do know well. I know loyalty. I know trust. I know dependability.

Now, I also know that our products aren't the best fit for everyone. But for those who our products are the best fit, we can provide superior products, superior service, a company you can trust and a team you can depend on.

Simple Long Polling Example with JavaScript and jQuery Tian Oct 15

9 comments Latest by Lars

There are many reasons you might need to poll a web server. Recently, one of our Dashboard Gauge Suite customers needed to poll sales data from his company's data warehouse and update his executive dashboard with the fresh data.

But you could be doing something different too. Maybe you're pulling your company's QC data so you can give your leadership team a visual of how each group is managing defect counts.

spacer

These two scenarios each have three things in common. First, a passion to display data in a beautiful and familiar way. Second, a desire to update each gauge without refreshing the page. Finally, each needs a smart and efficient way to poll their respective servers.

Here, we're going to accomplish each commonality with an emphasis on polling options and techniques:

A History of Polling

Realtime web applications have been with us for quite some time now. To the end user, these applications feel responsive and fluid. Gmail is (arguably) one of the most major applications to popularize this technique. JavaScript is at the heart here.

Have you ever been in the middle of replying to an email, when (suddenly) you're notified the person has sent you another followup? That's the perfect example of polling - sometimes referred to as server-push or comet technology.

A Tale of Two Polling Techniques

Traditional Polling

The setInterval Technique

Now, if you needed to poll your web service, your first instinct might be to do something like this with JavaScript and jQuery:

setInterval(function(){
    $.ajax({ url: "server", success: function(data){
        //Update your dashboard gauge
        salesGauge.setValue(data.value);
    }, dataType: "json"});
}, 30000);

Here, we have the poll ready to execute every thirty (30) seconds. This code is pretty good. It's clean and asynchronous. You're feeling confident. Things will work (and they will), but with a catch. What if it takes longer than thirty (30) seconds for the server to return your call?

That's the gamble with using setInterval. Lag, an unresponsive server or a whole host of network issues could prevent the call from returning in its allotted time. At this point, you could end up with a bunch of queued Ajax requests that won't necessarily return in the same order.

The setTimeout Technique

If you find yourself in a situation where you're going to bust your interval time, then a recursive setTimeout pattern is recommend:

(function poll(){
   setTimeout(function(){
      $.ajax({ url: "server", success: function(data){
        //Update your dashboard gauge
        salesGauge.setValue(data.value);

        //Setup the next poll recursively
        poll();
      }, dataType: "json"});
  }, 30000);
})();

Using the Closure technique, poll becomes a self executing JavaScript function that runs the first time automatically. Sets up the thirty (30) second interval. Makes the asynchronous Ajax call to your server. Then, finally, sets up the next poll recursively.

As you can see, jQuery's Ajax call can take as long as it wants to. So, this pattern doesn't guarantee execution on a fixed interval per se. But, it doesn't guarantee that the previous interval has completed before the next interval is called.

Both techniques suffer from the same flaw - a new connection to the server must be opened each time the $.ajax method is called. To make that connection, your realtime app must gear up and battle through hoards of competing network traffic to make it to your server.

What if you could just keep the connection open?

Long Polling - An Efficient Server-Push Technique

If you could simply keep the connection open, then your application would see faster response times and appear more responsive. That's a good thing and that's where Long Polling comes in:

(function poll(){
    $.ajax({ url: "server", success: function(data){
        //Update your dashboard gauge
        salesGauge.setValue(data.value);

    }, dataType: "json", complete: poll, timeout: 30000 });
})();

Complete: A function to be called when the request finishes (after success and error callbacks are executed). In this case, we call our JavaScript poll function and restart the polling process.

Timeout: Set a timeout (in milliseconds) for the request. The timeout period starts at the point the $.ajax call is made. Here, we set the timeout to 30 seconds. This means our poll function won't get called again until both the ajax call is complete and (at-least) thirty (30) seconds have passed.

As you can see, the Long Polling technique combines the best-case traditional polling with persistent remote server connections. The term Long Polling itself is short for long-held HTTP request.

Applications built with Long Polling in mind attempt to offer realtime interaction, using a persistent or long-lasting HTTP connection between the server and the client.

The self executing JavaScript poll function combined jQuery Ajax's repeating timeout interval means this is a very efficient server-push technique.

What's next? HTML5 WebSockets.

These types of Ajax Push techniques set the foundation for HTML5 WebSockets. With HTML5 WebSockets, we'll be able to see true Server Push styles of application development. This will make for truly responsive web applications.

Lately, I've been recommending Socket.

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.