Archive

Archive for the ‘AJAX’ Category

The Same Origin Policy: JSONP vs The document.domain Property

March 18th, 2010

The Same Origin Policy ensures that the client-side code (JavaScript) running on a website originated from that website. This prevents website http://kahtava.com from accessing resources (via client-side code) on website http://malicious-password-sniffers.com or website http://adam.kahtava.com from executing resources from http://kahtava.com - note that the sub-domains differ, one being kahtava.com, the other being adam.kahtava.com

In most cases The Same Origin Policy is desirable. It helps to prevent malicious code that could potentially reveal sensitive information from being run on arbitrary website. However, the same origin policy also makes it difficult to share resources within a common root domain, or run external widgets on your site (like displaying The Project Badge within your site). There are a couple ways to circumvent The Same Origin Policy, but I focus on JSONP and the document.domain property in this post.

Ways to circumvent the Same Origin Policy

  1. JSONP
  2. Modifying the document.domain property
  3. Creating a server side web proxy

JSONP (JSON with padding)

How it works: JSONP dynamically creates a script element in the head of your HTML document which then requests data from outside your domain. JSONP exploits a loophole in the Same Origin Policy that allows JavaScript from an external sites to be run within your site (much like how web analytic tracking works). The JSON response, when returned, is executed within your browser at which time the JavaScript can manipulate your HTML page / DOM.

An Example Using JSONP with jQuery:

JAVASCRIPT:
  1. (function(){
  2.   $.getJSON('http://adam.kahtava.com/services/open-source/projects.json?project-host:username=github:adamdotcom&callback=?', function(data) {
  3.     alert(data);
  4.   });
  5. })();

Note the callback=? at the end of the URI, in jQuery this indicates a JSONP call.

Pros

  • Lets us make external calls to any endpoint that supports JSONP
  • Lets us make external calls from HTTP to HTTPS
  • Supported by all major browsers

Cons

  • A bit more complex upfront, but most server side technologies support JSONP, browsers are natively supporting JSON, and JavaScript libraries like jQuery continue to abstract away most of the complexity.

The document.domain property

How it works: the document.domain property contains the domain of the server from which the page was loaded. For example, the domain for http://adam.kahtava.com/ would be adam.kahtava.com whereas the domain for http://kahtava.com would be kahtava.com. The Same Origin Policy restricts resource access from kahtava.com to adam.kahtava.com unless we set the document.domain property to the root domain (in this case I'd want it set to kahtava.com to share resources with http://adam.kahtava.com).

An Example using the document.domain property:

JAVASCRIPT:
  1. (function(){
  2.   document.domain = 'kahtava.com';
  3.   $.get('http://adam.kahtava.com/contact-me/', function(data) {
  4.     alert(data);
  5.   });
  6. })();

Pros

  • An easy way to access resources within our root domains
  • Supported by all major browsers

Cons

  • Prevents us from making external calls outside a root domain
  • Prevents us from switching between HTTP and HTTPS
  • Kind of a hack - technically, the document.domain property is supposed to be a read only property, but most browsers also provide set access

JSONP vs document.domain isn't a cut and dry comparison. JSONP lets anyone consume and share data, whereas overriding the document.domain lets you share resources within a common root domain. In simple cases where your only concern is sharing data within a single domain (exclusively on HTTP or exclusively on HTTPS), then overriding the domain works well, but in cases where you want to share or consume external data that may be passed over HTTP or HTTPS you'd probably want to stick with JSONP.

The Project Badge makes use of JSONP so it can work on your website. Most of my publicly available web services also make use of JSONP through a WCF JSONPBehavior.

The Project Badge: Show The World Your GitHub and Google Code Projects On Your Blog

February 24th, 2010

The Project Badge displays your GitHub and Google Code projects in a badge that can be displayed on your site. This widget was built on the data being returned from my Open Source Service.

View this post outside your RSS reader to see it in action or view it here.

The source for the Project Badge can be found here and the source for the accompanying service can be found here. A list of all my publicly available web services can be found here.

Using The Project Badge On Your Website or Blog

1. Add The Asset References

Add the following asset references, and a reference to jQuery (if you don't have one already).

HTML:
  1. <link rel="stylesheet" type="text/css" href="http://github.com/AdamDotCom/project-badge/raw/master/project-badge.css" />
  2. <script type="text/javascript" src="http://github.com/AdamDotCom/project-badge/raw/master/projectBadge.js"></script>

2. Configure Your Accounts

Set your project accounts (it's OK if you only use one host) then optionally set the appropriate filters - in my case my Google Code projects were prefixed with adamdotcom and I had duplicate projects on both GitHub and Google Code. By specifying remove:adamdotcom,remove:duplicate-items in my filters I filter out the duplicates and removed adamdotcom from the project name.

JavaScript:
  1. <script type="text/javascript">
  2.   projectBadge.load({
  3.       gitHub: 'AdamDotCom',
  4.       googleCode: 'adam.kahtava.com'
  5.     },{
  6.       filters: 'remove:adamdotcom,duplicate-items,-,empty-items'
  7.     });
  8. </script>

3. Add The Widget Hook
Add an element to your site or blog with the id of project-badge.

HTML:
  1. <div id="project-badge">
  2.   Loading...
  3. </div>

That's it!
If you have any issues, use the the working example as a reference, or send me a message.

The Google Exercise Revisited: Semantic Markup with jQuery

July 9th, 2009

A couple years ago I tried getting a Web Developer position at Google. After a few interviews they had me complete their Web Developer exercise. I did it, and my initial submission would have made any respectable web developer ill - you can read more here: Getting a Job at Google: A Web Developer Fizzbuzz. I redid the exercise over a year ago, but today even that code stink.

I did the exercise yet again (the third time) because my last attempt needed some improvements:

  • it suffered from chronic classitis and divitis (too many classes, ids, and divs were making me itchy)
  • it wasn't really using semantic / structural markup (all the extra divs etc... cluttered my markup, and some of my class names like container-borders are non-semantic altogether)
  • it performed poorly and wasn't accessible (everything was being rendered in the DOM, there was no immediate rendered markup which kind of violated the idea of unobtrusive JavaScript, nor was it screen reader friendly)
  • it wasn't making use of any JavaScript libraries to abstract browser inconsistencies out of the code
  • it suffered from my software ethnocentrism (my variable and object naming like GoogleExercise was mirroring statically typed languages and not the native language they were being written in)

Here's my latest Google Exercise (addressing all the above concerns):
View this post outside your RSS reader to see it in action or view it here.

This attempt makes use of jQuery and uses 57 lines of JavaScript (almost 200 lines less from my last one).

You can view the code for this attempt here: google.contact.widget.js, index.html, google-contact-widget.css.

You can view the old code here: GoogleExercise.js, index.html, GoogleExercise.css.

If you think I can improve on my code then let me know. Oh yeah, and if you're a recruiter from Google then hire me! :)

Don’t Write Frameworks For Dummies

February 5th, 2009

Eric Evans offers this piece of advice:

Don't write frameworks for dummies. [Frameworks designed by organizations] that assume some developers are not smart enough ... are likely to fail because they underestimate the difficulty of ... development. ... This attitude also poisons the relationship between [the developers and framework designer]. - Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software

Evans goes on to make the point that there's a fine line between designing for dummies, and providing useful encapsulation / abstraction. I found this advice interesting because I had been wrestling with whether the ASP.NET AJAX Framework is for Dummies.

Author: Adam Kahtava Categories: .NET, AJAX, ASP.NET, ASP.NET AJAX, Musings Tags:

Some Design Up Front is Good

December 18th, 2008

Like a horse with blinders on, avoiding some degree of Big Design Up Front (BDUF) can force your team and project into tunnel vision, because... If you don't look at what you're building in its entirety, it is harder to see the big picture, to have to that ah-hah moment that leads to a break through, to maintain conceptual integrity, or have a successful project.

I worked on a project where we attempted evolutionary design (avoiding Big Design Up Front) while taking an Agile approach. We used Continuous Integration, and Test Driven Development. Looking back, our attempt at trying to avoid Big Design Up Front was fatal for our project's success and probably our biggest mistake. The funny thing is, the only reason we avoided BDUF was because it seemed non-Agile (note the capital 'A' in 'Agile' read Yegge's post Good Agile, Bad Agile for the reference). As a development team we were inexperienced Agile (eXtreme Programming) teenagers and somewhere along the way we exchanged our brains for dogma.

eXtreme Programming [is at odds with] "Big Design, Up Front" (BDUF) _ Because "Ya Ain't Gonna Need It" (YAGNI) ... [but this is often] taken as permission to not do any planning - Gerard Meszaros' Alberta TechFest slide deck '07

In the past Big Design Up Front (BDUF) was associated with large inflexible architectural solutions that are designed upfront (before development begins) - like the waterfall methodology. However; BDUF (like most techniques / methodologies / tools) are quite useful when used with a sprinkle of common sense and moderation. BDUF can be a productive lightweight tool for fleshing out the high level overview of a system. It is important to note that I'm not advocating Big Architectural Design Up Front which is often composed of reams of documents, UML, ERDs, diagrams, and other unneeded artifacts. Instead I'm advocating for paper based story boards, wire frames, paper prototypes, user stories - anything that is easy to create, destroy, and recreate. These techniques provide the foundation of the final product, they start to verbalize the common product goal and can start to draw out the language, metaphors, and model that will eventually compose the project.

Avoiding some Design Up Front was a mistake for our project. As a team we were trying to cope with the complexities of our domain under very tight deadlines. Our code became increasingly brittle, we had overlooked obvious shared functionality that a high level overview would have fleshed out. At the same time we had segregated our application into sprint sized silos with no clear relationships - each sprint was essentially a two week tunnel, and disconnected.

Without some form of BDUF it was difficult to:

  • maintain conceptual integrity, a common goal, a consistent user interface
  • estimate the whole product cost
  • have a successful project

We should have headed Steve McConnell's words:

people were claiming,  "I don't have to do requirements or design because I'm using object-oriented programming." That was just an excuse. Most of those people weren't really doing object-oriented programming-they were hacking, and the results were predictable, and poor. Right now, people are saying "I don't have to do requirements or design because I'm doing agile development." Again, the results are easy to predict, and poor - Steve McConnell, Code Complete

Or perhaps Martin Fowler's suggestion:

the planned design approach has been around since the 70s, and lots of people have used it. It is better in many ways than code and fix evolutionary design. But it has some faults. - Martin Fowler, Is Design Dead?

Not doing some Design Up Front is probably another excuse for being sloppy, but what do you think?

Author: Adam Kahtava Categories: AJAX, ASP.NET, Musings, Personal Tags:

Microsoft and jQuery Finally: Thank-You!

September 28th, 2008

Microsoft is looking to make jQuery part of their official development platform ... jQuery will be distributed with Visual Studio
- jQuery, Microsoft, and Nokia

Other links of interest:

I was completely blindsided by this decision.

Author: Adam Kahtava Categories: .NET, AJAX, ASP.NET, ASP.NET AJAX, JavaScript Tags:

Transparency: Considerations For Choosing a JavaScript / AJAX Framework

September 20th, 2008

A growing number of development teams are given the opportunity to choose their JavaScript / AJAX Frameworks. This choice is often thrown to the development team because the Architects are more concerned with the bigger picture, and the technical details are over the manager's head. Letting the development team decide on the JavaScript / AJAX framework produces some great benefits: it gels the team, fosters project buy-in, and creates project excitement.

Now, developers can be pretty skeptical, and getting them to agree has been likened to herding cats, but a couple core considerations / values seem to surface when the decision is being made.

Considerations for choosing a JavaScript / AJAX Framework:

  • Transparency - Who are the framework's development team and why should we trust them? Do these developers blog? Attend conferences? Are they featured on podcasts / videos? Is there a high or low turnover within the team? What are their passions? Is this just a job, do they like what they're doing, are they a cog on a wheel? Are they experts in their field?
  • Competency - Based on the information gathered in the consideration above (transparency), how competent do we feel the development team is?
  • Community Support - How well is the framework supported on forums and blogs? If something were to go wrong can we gain access to the framework's development team? Are there widespread experts using this framework readily available?
  • Reputation - How popular is the framework in the industry? Who uses it? Are there any white papers, success stories, case studies available?

One of the easiest ways for a developer to choose a framework is by looking at the developers that built it (and talking with those that are using it). As developers our day job will be stepping into someone else's code for the duration of the project, working with a framework created by competent developers makes our jobs easy. Frameworks without transparency don't allow us to gauge the competency of the developers or the framework.

Transparency is essential for JavaScript / AJAX Framework teams, JavaScript itself is open and transparent (not compiled yet), it follows that JavaScript / AJAX Framework along with their teams should also be transparent. When the decision for choosing a JavaScript / AJAX Framework is placed in the hands of developers the frameworks that don't meet the above criteria sink to the bottom of the list.

The only way to succeed now is to be completely transparent, everything is exposed, everything you do - Gary Vaynerchuk 

Author: Adam Kahtava Categories: AJAX, ASP.NET AJAX, JavaScript, Software Tags:

Book Reviewed: JavaScript: The Good Parts by Douglas Crockford

June 7th, 2008

Weighing in at 140+ pages of content, JavaScript: The Good Parts [Douglas Crockford] cuts through the obscurities, pleasantries, and filler found in most technical books. Instead, this book dives straight into the heart of the JavaScript language. It presents the clearest comprehensive explanation of what makes JavaScript a great programming language that I've encountered to date. It nails the important concepts, like JavaScript's: object oriented nature, its classless (pseudoclassical) nature, and functional nature. While covering the fundamentals like JavaScript's: functions, lexical scoping, lambdas, prototypal inheritance, and functional inheritance.

This book's size makes it approachable for all audiences, its style is terse and concise. This book has the potential to do for JavaScript, what Richie's inspirational classic the C Programming Language did for the C language.

JavaScript is the programming language of the web (AJAX), and this book will guide you through the good parts of this often misunderstood language - while this book is an excellent reference, it is not intended to replace JavaScript: The Definitive Guide, you'll do best to have both these books on hand.

If you enjoyed (or are considering) this book then you may want to learn more of what Douglas Crockford has to say, check out his great JavaScript video series on the YUI Theater.

I highly recommend this book. View my review on Amazon.

Writing a Control for the AJAX Control Toolkit: How ASP.NET AJAX Failed

June 7th, 2008

One of my resolutions this year was to contribute to the AJAX Control Toolkit for the ASP.NET AJAX Framework. I began my AJAX Control Toolkit development quest by digging into the online resources, reading ASP.NET AJAX in Action, and decomposing the AJAX Control Toolkit. I noted the huge learning curve required to developing a control, and continued to dig deeper. Once mired in ASP.NET AJAX a bad smell kept wafting by. Since then I've been trying to distinguish this smell.

What's really wrong with ASP.NET AJAX?

  • It doesn't plan for performance from day one
  • It treats AJAX as a classic computer science problem
  • It tries to turn JavaScript into a classical language which works against JavaScript's dynamic, prototypical nature
  • It feels like a framework that was written for dummies (Don't Write Frameworks For Dummies)

A Case Study: Why Plaxo.com Almost Failed

In the video: High-performance JavaScript: Why Everything You've Been Taught is Wrong (YUI Theater) Joseph Smarr discusses the challenges and lessons learned while developing Plaxo.com. While developing this AJAX centric application, the Plaxo team decided to include everything they could think of into their application. They created a framework to treat JavaScript as a classical language, they gave priority to features over performance, and... the project ALMOST FAILED. They were able to salvage their application by diverting their development efforts, making performance one of their top priorities, by unlearning everything they'd been taught about classical applications (instead embracing JavaScript), jettisoning unneeded framework bloat, and more.

Some of the points made in this video were:

  • Plan for performance from day one
  • AJAX is not a classic problem
  • JavaScript is not a classical programming language
  • User experience and a responsive application can make or break an application
  • Unneeded bloat in a framework, and an obtuse approach to using AJAX (treating AJAX and JavaScript as a classical language or classic computer science problem) has the potential to cripple your application

This Channel 9 video also mirrors these sentiments: Douglas Crockford, Alex Russell and Joseph Smarr: On the Past, Present and Future of JavaScript

How ASP.NET AJAX Failed: What can we learn from Plaxo?

The way the Plaxo team approached their application development is similar to how the ASP.NET AJAX Framework has been designed. Like Plaxo's initial attempt ASP.NET AJAX attempts to mold JavaScript into a classical language, and attempts to treat JavaScript and AJAX as a classic computer science problem by heaping on more abstractions. Like Plaxo's initial attempt ASP.NET AJAX also gives a low priority to performance. Plaxo was able to change their direction and salvaged their application, but the ASP.NET AJAX Framework is not in a position to make any sweeping changes - ASP.NET AJAX is going down the wrong path and it's too late.

The ASP.NET AJAX Framework is probably another exercise in Framework Architecture (demoware) and a failure in practice. Its lack of use in the wild attests to these shortcomings - contrast the sites using ASP.NET AJAX with the sites using jQuery (Actions Speak Louder Than Words). Furthermore the places that ASP.NET AJAX does thrive (the small internal ASP.NET business apps that need some bling-bling) will also be the areas that Silverlight shines - Silverlight offers a better Microsoft centric programming model (less leaky Win Form / Web Form abstractions) that most Microsoft developers will embrace. Silverlight will probably divert the developers that currently embrace ASP.NET AJAX.

I don't recommend the ASP.NET AJAX Framework and won't be contributing to the AJAX Control Toolkit. My time is better spent elsewhere.

Author: Adam Kahtava Categories: .NET, AJAX, ASP.NET, ASP.NET AJAX, JavaScript Tags:

More on the perils of The ASP.NET AJAX Framework

June 3rd, 2008

There's no need to whip a dead horse (I've probably been griping about the ASP.NET AJAX Framework for too long), but... Jon Galloway and a group of other notable gurus (K. Scott Allen, Scott Koon, and Kevin Dente) have started a podcast, their latest segment sparked my interest since it covered ASP.NET AJAX and AJAX Libraries / Frameworks in general.

I share their sentiments so I thought I'd post a brief but choppy transcript:

[ASP.NET AJAX] ... does offer some some nice features, they did try to take some of the common pieces of the CLR that [.NET Developers are] used to working with and move that down into a JavaScript library. So you get classes like a WebRequest class that wraps the XMLHttpRequest ... and they have a StringBuilder, and they added methods that we're more accustom with ...

that's wonderful, but I don't find myself needing those extensions all that often. If you want to do strictly client-side programming then something like jQuery offers you a lot more capabilities to do things that you really want to do client-side like sorting and CSS selectors. ... That stuff is easy to do with an Update Panel and ASP.NET, but Update Panels aren't always the best solution to use. ...

the goals with ASP.NET AJAX was to integrate into the ASP.NET server-side model ... that's great for ASP.NET, but it needs more client-side features. ... It works if your thinking from the ASP.NET control perspective, but if you look at it outside the ASP.NET model there are a lot easier ways to do it. ...

ASP.NET AJAX [development] seems to have come to a standstill I'm not seeing a lot of development in that area and the rest of these [AJAX] Frameworks are doing monthly releases. Every month that goes by [the ASP.NET AJAX Framework] falls further and further behind ... it needs to evolve.

Listen to this podcast here: Technology Round Table Podcast #2 - AJAX Frameworks

Author: Adam Kahtava Categories: .NET, AJAX, ASP.NET, ASP.NET AJAX, CSS, DOM, JavaScript Tags: