SocialNetworkInc.com - SEO Tips and Tricks
view blog
Subscribe to socialnetworkinc.com on FriendFeedFollow socialnetworkinc.com on Twitter

Latest Site News

Social Network Inc. - Launching Soon.

Related Links

Encosia
http://encosia.com
ASP.NET and AJAX code, ideas, and examples.
REST vs. RPC in ASP.NET Web API? Who cares; it does both.
source: http://feeds.encosia.com/~r/Encosia/~3/F30kspI4CFo/

It’s probably an understatement to say that ASP.NET Web API has sparked a bit of debate about RESTful design lately.

Web API’s new features like content negotiation, flexible media formatters, and improved JSON formatter are great, but they’ve been presented as features that are tied to the REST paradigm. That may seem troubling if you’re more accustomed to .NET’s RPC endpoints like ASMX, WCF, and even the way ASP.NET MVC controller actions are often used as a makeshift API.

A couple months after the new incarnation of Web API was announced, I’m still seeing a lot of confusion and unhappiness about Web API’s apparent push toward REST. However, what almost everyone has overlooked so far is that Web API supports RPC just as well as REST.

Over-simplifying the difference between REST and RPC

When I say REST, I don’t mean a peaceful afternoon napping in a hammock by the beach, but Representational State Transfer. A RESTful API exposes its data as resources (or nouns) at URIs that clients interact with via HTTP methods like GET and POST (or verbs).

On the other hand, remote procedure call (RPC) refers an API style where endpoints perform arbitrary actions, not necessarily tied to a particular resource. Typically, RPC service methods combine the noun and verb in one method name (e.g. GetPosts or SendInvoice). If you’re using ASMX or WCF today, you’re probably using the RPC approach.

In the context of ASP.NET Web API, the key distinction between REST and RPC is that in a RESTful approach your API consumers interact with public methods corresponding to HTTP verbs (e.g. Get() or Delete(int Id)). If a method doesn’t map to an HTTP verb, it doesn’t fit into a RESTful API.

ASP.NET Web API routing basics

Part of ASP.NET Web API’s magic is that it automatically routes requests to your API methods by convention, matching the request’s HTTP verb to a correspondingly named method in your API class.

For example, this default routing setup in the ASP.NET MVC 4 project template:

routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

Means that you could write a class like this:

public class MyApiController: ApiController {
  public string Get() {
    return "Hello World";
  }
}

And then access that Get() method via HTTP by making a GET request to /api/myapi. Similarly, HTTP requests using the POST, PUT, and DELETE verbs would execute methods with names matching those verbs too.

No coloring outside the lines

That automatic RESTful routing is handy, but what if you wanted to add a method that doesn’t correspond to an HTTP verb, like good ‘ol FooBar:

public class MyApiController: ApiController {
  public string Get() {
    return "Hello World";
  }
 
  public string FooBar() {
    return "FooBar";
  }
}

Confusingly enough, a GET request to /api/myapi/foobar returns Hello World instead of FooBar. The reason for that is because our default Web API route sends that request to MyApi with an {id} of FooBar and then Web API executes the Get() method since the request was an HTTP GET.

Web API supports RPC too

Easy REST support by convention is nice, but what’s not obvious in any of the samples I’ve seen is that Web API supports RPC-style routing too.

By adding an {action} parameter to the route, you can override Web API’s default HTTP verb-based routing:

routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{action}/{id}",
  defaults: new { id = RouteParameter.Optional }
);

With this routing configuration, the previous GET request to /api/myapi/ returns a 404, but requests to /api/myapi/get via any HTTP verb return Hello World. That’s not incredibly useful by itself, but it means we can extend the API with arbitrary RPC methods now:

public class MyApiController: ApiController {
  public string Get() {
    return "Hello World";
  }
 
  public string FooBar() {
    return "FooBar";
  }
}

Now, requests to /api/myapi/foobar will return FooBar instead of Hello World.

Gradually migrating from RPC to REST

Since “switching” from REST to RPC was just a routing change, it stands to reason that you could combine both approaches easily enough. Indeed, it’s as simple as using a pair of routes like these:

routes.MapHttpRoute(
  name: "RestApi",
  routeTemplate: "api/{controller}/{id}",
  defaults: new { id = RouteParameter.Optional }
);
 
routes.MapHttpRoute(
  name: "RpcApi",
  // I like "services" as the path prefix for this since it's
  //  where I usually stored ASMX services in the past, but 
  //  you can use anything you want. "rpc" would be good too.
  routeTemplate: "services/{controller}/{action}"
);

One important caveat with this approach is that you need to name your controllers carefully. Even if they’re in different namespaces, you’ll get an ambiguity error if both folders contain an API controller with the same class name.

It should be possible to resolve that issue by adding a constraint to the route, but I haven’t been able to get that working with MapHttpRoute. If you know how to make that work with Web API, please let me know.

Combining both REST and RPC

If you want to live dangerously, you can even mix both approaches in the same API controller. If you include an optional {action} parameter in your API route definition, you get Web API’s verb-based routing and the option to augment those basic methods with specified RPC-style methods.

routes.MapHttpRoute(
  name: "RestPCApi",
  routeTemplate: "api/{controller}/{action}",
  defaults: new { action = RouteParameter.Optional }
);

Using the previous Get/FooBar class, making GET requests to /api/myapi/ return Hello World, while making a request via any HTTP verb to /api/myapi/foobar will return FooBar. Nifty.

I will say that I haven’t tried using this same-controller hybrid approach in any real code yet, so tread lightly (and please leave a comment on this post if you do try this with or without success).

Why bother? Isn’t REST better?

The prevailing popular opinion these days is clearly in favor of RESTful APIs. REST does make for a nice, clean API when it fits well. That’s especially true for relatively simple public-facing APIs (e.g. services like Twitter and Flickr), where everyone benefits from following common conventions.

On the other hand, private APIs sometimes don’t need a full CRUD implementation for every resource. When you only need a few combinations of noun and verb, a simple RPC API is a perfectly valid alternative to the cartesian product of nouns and verbs that a truly RESTful API requires you to implement.

More importantly, RPC routing support means you don’t need to be afraid of Web API, even if you’re heavily invested in ASMX or WCF services.

You can upgrade to Web API’s goodness without completely revamping your existing services (I recently updated one of my largest ASMX-based projects to ASP.NET Web API in less than a day using this RPC routing approach). That means you can maintain RPC support for those older services, while implementing new services in a RESTful style going forward, and migrate at your own pace without any of your services being stuck on a legacy technology.

Related posts:

  1. Databinding Class Data


You've been reading REST vs. RPC in ASP.NET Web API? Who cares; it does both., originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Facebook is retaining Instagram’s users, not acquiring them
source: http://feeds.encosia.com/~r/Encosia/~3/XUUJhriWyE0/

There’s been plenty of cynical talk going around about today’s news that Facebook is acquiring Instagram for $1 billion in cash and stock. One of the most salient points is the simple arithmetic on how much Facebook is paying for each of Instagram’s roughly 30 million users. With Facebook paying somewhere in the neighborhood of $33 per Instagram user, that seems fairly pricey compared to Facebook’s own valuation of roughly $120 per user.

What’s missing from that math is that Facebook users spend a huge amount of their time sharing and viewing photos. According to recent Comscore data, Facebook users are spending 17% of their time viewing photos on Facebook. Photos are incredibly important to Facebook.

Time spent on Facebook by type of activity.

Thinking of how I use Facebook and how I’ve seen others use it, I’d even make a case for the photos being a crucial part of drawing users into the remaining 83%.

Almost overnight, Instagram’s social network of photo enthusiasts gave it a solid beachhead into some 17% of Facebook’s social stronghold. Perhaps maybe even more importantly, Instagram is entirely focused on mobile (where Facebook sees its future). Maybe Instagram had no intention of ever competing head-to-head with Facebook, but I believe Instagram actually posed a greater potential threat than Google+ has yet.

Though it’s hard to fathom a $1 billion valuation for such a simple app and service, maybe that’s a reasonable price to quash potential competition to the unimaginable windfall that is Facebook. Facebook isn’t buying new users, but paying a premium to retain the union of Facebook and Instagram’s shared users and redirecting this aspect of their engagement back toward Facebook.

No related posts.


You've been reading Facebook is retaining Instagram’s users, not acquiring them, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Someone should copy these 4 features from the Zenbook
source: http://feeds.encosia.com/~r/Encosia/~3/H_NdmJpPNoA/

It’s been a few months since I began reviewing ASUS’ Zenbook UX31 based on day-to-day use, and it’s time to wrap the process up with a third and final post. The original plan for this series of reviews was that I’d write three posts about the Zenbook, finishing with one that summarized my experience using it regularly for a few months.

Unfortunately, the trouble I had with its keyboard sabotaged that plan. If you haven’t been following along, a month with the Zenbook’s keyboard was all I could endure. However, almost every other aspect of the UX31 put it solidly in the running as a successor to my MacBook Air.

Rather than ending on that sour note about the keyboard, this last post in the series will cover a few things that the Zenbook did well. So well, I’ll be looking for these features in whichever Ultrabook™ ultimately does replace my MacBook Air.

Life’s too short to wait on a computer

I mentioned this in my last post in this series, but the Zenbook’s resume-from-sleep delay is the shortest I’ve ever experienced. I always thought my MacBook Air was pretty quick on that front, but it feels impossibly sluggish after using the Zenbook for a month.

Resume speed sounds like a trivial feature, but I think it’s similar to how a machine’s physical fit and finish affects how you perceive that machine’s innards even though they’re unrelated. When I open the lid on my laptop, I’m doing that because I want to use the thing right away. Repeatedly poking around at the touchpad to determine whether I’m looking at a glorified splash screen façade or working OS makes me feel like this guy sometimes:

I hope that I can ultimately find an Ultrabook™ that satisfies my other requirements (read: a keyboard that works) while still including the Zenbook’s impressively quick resume time.

USB+ charging

When I’m mobile, my phone is my lifeline and its battery is the power source I care most about keeping charged. It’s irritating if my laptop runs out of juice, but I’m dead in the water without my phone.

In fact, if you’ve been to a conference with me in the past few years, you might have seen me sitting in an afternoon session, laptop barely cracked open, screen dimmed, charging my phone. Of course, that’s an inefficient way to transfer power from one battery to the other since most of the power flowing out of the laptop’s battery is wasted running the laptop itself in that scenario.

So, I was pleasantly surprised by the UX31’s USB Charger+ feature.

A screenshot of the USB Charger+ control panelWith USB Charger+ enabled, the Zenbook will charge USB devices even while the laptop is in sleep mode, hibernated, or shut down. You can even set a threshold for exactly how much of the Zenbook’s battery capacity will passively transfer, so you don’t accidentally run the laptop’s battery dead in the process.

While I didn’t use my Zenbook long enough to make heavy use of USB Charger+, I’m sure that I would use it regularly if my next laptop had a similar feature.

Quality construction

zenbook-0103-small

The MacBook’s unibody aluminum case was part of the reason that I originally purchased my Air. Certainly, conventional wisdom dictates that Apple’s laptops set the standard for quality construction, right?

On the contrary, I was surprised to find that the Zenbook felt even more solid than my Air. In particular, the relatively flexible top of the Air’s lid has always bothered me. It feels like you’re pressing the case right into the back of the LCD if you squeeze it there to pick it up.

Handling a laptop with a creaky, flexible case is one of my pet peeves, so the Zenbook’s rock-solid construction was one of my favorite things about it. Even its slightly heavier heft, though a detriment when comparing specs on paper, was just the right amount to make it feel robust without being heavy enough to comfortably hold from a front edge or corner.

Great built-in audio

I mentioned this in my last post too, but the Bang & Olufsen internal sound system in the UX31 is impressive. I can’t remember ever regularly listening to music on any of my previous laptops’ speakers, but found myself doing that often during my month with the Zenbook when I was using it in private.

zenbook-0090-small

A laptop’s speakers definitely aren’t as important as the display, touchpad, or keyboard, but the laptop’s built-in audio system will be something I pay attention to in the future. If I can find a MacBook Air successor that does have internal sound comparable to the Zenbook’s, I’ll be happy about that.

Don’t feed the lawyers

Disclosure of Material Connection: I received one or more of the products or services mentioned above for free in the hope that I would mention it on my blog. Regardless, I only recommend products or services I use personally and believe my readers will enjoy. I am disclosing this in accordance with the Federal Trade Commission’s 16 CFR, Part 255: “Guides Concerning the Use of Endorsements and Testimonials in Advertising.”

Conclusion

Of course, there were other aspects where the Zenbook performed well. The Core i5 processor, high resolution display, and responsive touchpad were all welcome features, for example. However, the preceding four features were where the UX31 truly distinguished itself, and I hope that I can eventually find an Ultrabook™ that incorporates those features and the niceties that the Zenbook lacked.

What do you think?

In closing, I’m curious if you found this experiment helpful. I know I can’t be alone in wanting to find a Windows-friendly laptop that has great design and quality construction, so I do hope that you found my review of the Zenbook interesting and relevant.

If I get the opportunity to do this again with a different laptop, would you be interested in reading another series of posts about that hardware? Are there any new laptops that you’re particularly interested in seeing reviewed?

Related posts:

  1. The ASUS Zenbook UX31: Initial impressions
  2. A month with my Zenbook UX31
  3. Exploring one of MS AJAX’s often overlooked features.


You've been reading Someone should copy these 4 features from the Zenbook, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Cooking the books is hard and doesn’t help anyone
source: http://feeds.encosia.com/~r/Encosia/~3/_xVcPOkSUss/

The IE team published an in-depth post over the weekend, raising a few concerns about StatCounter’s methodology (or lack thereof) for reporting browser market share. Their points were interesting to consider, but one of them stood out to me:

You’ll notice some pretty big differences in the weighting of StatCounter versus Net Applications. First and foremost, the most populous country in the world, China, doesn’t make the top 20 for StatCounter, when in fact it represents the world’s largest internet population.

[...]

To further explore this problem, we re-ran the StatCounter numbers and weighted their publicly reported individual country browser share numbers by the CIA internet population data. This calculation would then represent a true country or geo-weighted view of worldwide browser data based on the actual world’s internet population.

It’s true that we should be wary of methodology issues that can creep into data extracted from analytics services that weren’t designed with aggregate statistics in mind. StatCounter’s data is often accepted at face value, without any detailed scrutiny. However, I believe this geo-weighting approach they’ve explored may be as flawed as the raw, unadjusted data itself.

Why does it matter?

What’s the use in splitting hairs about this? When I finished writing this post, I wondered the same thing. Why did I bother writing 1,000+ words about a random IE marketing post?

Microsoft is an incredibly metrics-driven company. You can be sure that these numbers are intended to make a case for ignoring certain aspects of Chrome and Firefox, prioritizing particular Internet Explorer features, and/or confirming that Internet Explorer is turning the tide against Chrome and Firefox.

As long as Internet Explorer is the baseline browser that ships with every Windows-based PC, massaging the numbers to downplay the popularity of what Chrome and Firefox are doing hurts us all. So, that’s why I’m taking the time to voice my doubts about this recent post.

What’s an “Internet user” anyway?

The motivation behind this geo-weighting approach seems to be that the CIA World Factbook reports China’s “Internet users” at a robust 389 million, compared to the US’ 245 million, whereas StatCounter only reports about one percent of the traffic it tracks as coming from IE-laden China. So, maybe it’s reasonable to argue that StatCounter’s numbers for IE usage should be adjusted proportionally.

Not so fast though. If you’re like me, you might be curious what actually counts as an “Internet user” first. Here’s the CIA World Factbook’s definition:

The number of users within a country that access the Internet. Statistics vary from country to country and may include users who access the Internet at least several times a week to those who access it only once within a period of several months.

Reasonable interpretations of that include counting every person that uses an Internet cafe a few times a year and everyone who checks email from an app on their phone as Internet users. Maybe it’s just me, but that seems like an incredibly vague statistic to warrant such a significant adjustment.

It gets worse though. Keep that definition in mind for a minute and let’s talk about another statistic that varies greatly between China and the US.

You can’t ignore mobile

The most current CIA World Factbook stats on mobile phone usage put China at a whopping 859 million subscribers versus 279 million in the US. While Internet access via mobile phone was insignificant in the pre-iPhone US, it has long been the norm in many Eastern countries (some research points to a full two-thirds of Chinese Internet access being via mobile phone).

Given that reliance on mobile access and the nearly 600 million mobile subscribers China has on the US, it’s reasonable to assume that a non-trivial chunk of the “Internet user” gap between the US and China is comprised of mobile users. In fact, the data suggests to me that China’s higher number of total Internet users may actually represent less access via traditional PC than in the US.

Speaking of those mobile users, while we’re swimming in a sea of iOS, Android, and Windows Phone devices in the US, it’s easy to forget that the venerable Nokia feature phone is still the dominant Internet-enabled mobile device in many countries (China included). Behind Nokia, manufacturers like Samsung, LG, Motorola, and Sony Ericsson also sell a combined tens-of-millions of feature phones with Internet capabilities in markets like China each year.

More importantly, only a tiny fraction of mobile phones run any version of Internet Explorer, and no feature phone that I’m aware of runs Internet Explorer. When you consider this aspect of the CIA’s data, it seems plausible that IE’s market share in Eastern countries may actually need to be adjusted downward if anything.

Why not version-weighting too?

The IE team’s blog post specifically mentioning China reminded me of The Internet Explorer 6 Countdown site that Microsoft itself launched last year. One of the datapoints that really stands out there is that China represents a solid majority of Internet Explorer 6’s remaining user base (largely due to pirated copies of Windows XP that can’t easily be upgraded to IE7+):


So, even if you believe that China’s browser share numbers should be adjusted upward to compensate for the potential discrepancy in StatCounter’s data, nearly a full quarter of those users are still stuck on IE6. That’s hardly something to be proud of in 2012, but even more embarrassing in a discussion about IE’s market share as compared to Chrome and Firefox’s rapidly upgrading user base.

Why so mean?

My aim here isn’t to pointlessly bash the Internet Explorer team.

They really are doing some great work on turning IE around. I think IE9 was an inflection point where the Windows team got serious about the web again, and IE10 is poised to bring Internet Explorer forward to a place where it can focus more on moving the entire web platform forward like it did in its heyday 10+ years ago.

Yet, no one benefits from this sort of accounting trick; not even the IE team itself.

  • If they believe that IE9 has similar or higher market share to Chrome, it’s easier to dismiss features like HTML5 Notifications as fringe APIs that can wait till later, when implementing them in IE9 or IE10 would’ve been a win for both developers and users.
  • If they believe that IE9 is more popular than it is and that IE10 is likely to follow in those footsteps, they might be more inclined to continue ignoring the de facto standard touch events API that iOS and Android both support and create a proprietary API instead.
  • If they believe Chrome (and Firefox, to a lesser extent) has been relatively unsuccessful with a rapid release cycle and forced upgrades, it’s easier to remain confident that Internet Explorer’s slow release and upgrade cycle is still as viable as ever.

Rather, I think if Microsoft wants to truly bring Internet Explorer back to dominance, they need to take stock and reevaluate some of their sacred cows:

  • Multiple versions side-by-side: A modern browser may either auto-update on a regular basis or be able to install every one of its currently active versions side-by-side. For example, it’s trivial to test in many versions of Firefox on the same machine and you’ll never need to test in a year-old version of Chrome.
  • Support for XP and Vista: This is related to the previous item, but punting on support for older operating systems is directly responsible for the awful fragmentation that Internet Explorer continues to suffer. Why have Chrome and Firefox figured out how to implement WebGL 3D acceleration on Windows XP, but the company that actually created Windows XP can’t get IE9′s 2D acceleration to work on it? Come on.
  • Embrace the platform: I actually think some of IE9′s proprietary features are compelling. IE9′s work on 2D acceleration spurred the rest of the browsers to take that feature more seriously and site pinning leapfrogs Chrome’s application shortcuts by a long shot. However, that doesn’t make it okay to ignore de facto standards like the HTML5 Notification API and the touch events API, where other browsers have been playing nice with each other.

What do you think?

If you’re part of the 80% of people who visit my site in Firefox or a WebKit browser, what would it take to make Internet Explorer your default browser? Is it possible?

If you’re part of the 8% of people who visit my site in Internet Explorer, why are you using IE? Corporate policy, or are the rest of us missing out on something?

Related posts:

  1. Targeting WebKit is not like targeting IE6
  2. Why PhoneGap 1.1.0 broke jQuery Mobile’s back button


You've been reading Cooking the books is hard and doesn’t help anyone, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


jQuery, ASP.NET Web API, and Json.NET walk into a bar…
source: http://feeds.encosia.com/~r/Encosia/~3/dOINYqTBwFc/

There’s been some confusing back and forth lately about ASP.NET Web API and JSON. During the time between the last WCF Web API preview and the current ASP.NET Web API beta, it’s clear that effort has gone into smoothing out some of DataContractJsonSerializer’s (DCJS) quirks. However, while things like DateTime and Enum deserialization have been improved, issues have still persisted with Anonymous Types, Dictionaries, and DateTime serialization.

Unfortunately, the underlying cause of those remaining issues was too fundamental to simply spackle over. One of the most frustrating aspects of DCJS is that it’s rooted in WCF’s mindset that all things can be expressed as XML and then translated to other formats. In that world, data like Anonymous Types and simple collections of key/value pairs are uninteresting oddities. So, as long as ASP.NET Web API is saddled with DCJS, it’s at a disadvantage in scenarios requiring more flexible JSON serialization.

DataContractJsonSerializer: No one likes you!

Getting away from DCJS is such an obvious first step when using Web API that Microsoft’s own Henrik Nielsen[0] published a guide to switching from using DCJS to using James Newton-King‘s Json.NET last month. This week, Rick Strahl wrote a similar post on how to use JavaScriptSerializer or Json.NET with Web API.

In the same vein, Scott Hanselman had a good post about the woes of dealing with dates in JSON last week. Dates in JSON are bad enough already[1], but the existing JSON serializers built into .NET make them even worse if you’re not using MicrosoftAjax.js or a compatibility wrapper of some sort. His solution was to use Henrik’s approach for jettisoning DCJS and switching to using Json.NET (which supports the de facto standard ISO date format).

In that post, Scott casually mentioned some relatively huge news: Json.NET will be included as the default JSON serializer in Web API by the time it’s released.

Just so we’re clear

It seems like the message about Json.NET becoming the default JSON serializer in Web API got muddled a bit, hiding in the middle of Scott’s post. So, I wanted to hone in on that specifically and hopefully add some clarity.

In fact, I double-checked with Scott Hunter[2] first to be sure I wasn’t adding to the confusion myself. Here’s what he had to say:

We are making Json.net the default moving forward.

It doesn’t get more definitive than that.

This is a good thing

Many of us have been trending toward using ASP.NET as a JSON-speaking backend to power client-side JavaScript as much as anything else lately. For that purpose, this is fantastic news that resolves the last few serialization issues that Web API had as compared to current approaches using JavaScriptSerializer.

It may seem troubling that the default DateTime serialization is changing, but the short-term inconvenience of dealing with that will be well worthwhile in the long run. Moves like this that make ASP.NET more flexible and interoperable with other platforms are ultimately a boon for us all.

Further, isn’t it great to see Microsoft embracing and leveraging an open source project in the community instead of reinventing that wheel again? In my mind, this is one of the best examples of Microsoft playing nice with an open source project since they adopted jQuery in 2008.

Footnotes

[0]: It must be nice to just use a Wikipedia link as your Twitter bio.

[1]: Dates in JSON are such a disaster that I was even able to ride their coattails to a miniature round of applause during Crockford’s talk at MIX11 (at the end, in the Q&A). You know it’s serious business when I’m the only person other than Crockford to get applause during a Crockford talk!

[2]: Scott is Principal Program Manager Lead on the ASP.NET team. You should follow him if you’re an ASP.NET developer on Twitter.

Related posts:

  1. Using jQuery to Consume ASP.NET JSON Web Services
  2. ASP.NET web services mistake: manual JSON serialization
  3. ASMX and JSON – Common mistakes and misconceptions


You've been reading jQuery, ASP.NET Web API, and Json.NET walk into a bar…, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


A month with my Zenbook UX31
source: http://feeds.encosia.com/~r/Encosia/~3/cSZMknmOOtA/

Note: If you haven’t read my initial impressions of the Zenbook, you might want to head over and read that first: The ASUS Zenbook UX31: Initial impressions

I’ve been using my ASUS Zenbook for just over a month at this point, and it’s time for a second review now that I’ve used it for a while on a day-to-day basis. I’ve heard from many of you about being eager to read the next installment in this process, so I’m glad to know that you’re finding this experiment useful too.

Component controversy

First, I want to address something that came up on Twitter a few weeks ago, when it was brought to light that there’s apparently some variation between the touchpad and SSD hardware components that ASUS used in different builds of the same model Zenbooks. You can read more about that in this Amazon review.

The short of it is that Zenbooks that ship with an ADATA SSD are potentially much faster when it comes to some tasks and models with the ELAN touchpad are usually less quirky when multi-finger gestures come into play. I don’t know if that’s an ongoing inconsistency or if all units have the improved hardware going forward, but it’s something important to keep in mind.

One implication I saw mentioned was that ASUS may have provided us with ADATA/ELAN equipped models in order to elicit the best possible reviews. However, while the model that I received does have the ELAN touchpad, its SSD is the slower Sandisk variant.

More importantly, my Zenbook was shipped directly from Amazon, not ASUS. There was no opportunity for that kind of trickery to occur. If you look closely at the photo above, you can see that we actually happened to capture a photo of the Amazon shipping label during the unboxing.

Further, Intel is sponsoring these reviews, not ASUS. So, any suspicion that ASUS is providing us with the best possible model to review is probably misplaced.

Terrific touchpad

Speaking of the ELAN touchpad, I’ve been pleasantly surprised with how well the touchpad in this UX31 works. I guess I’ve just sort of resigned myself to PC laptops having cheap, plasticy touchpads and clunky support for multitouch gestures, but the Zenbook has definitely changed my perception of that.

Gestures like two-finger scrolling work as you’d expect, but it also supports pinching to zoom in and out, three-fingers to the left or right to navigate back and forward, and three-fingers up to invoke Aero Flip 3D. Overall, I found the gestures reliable and quite useful (though I can’t speak for the zoom and rotate gestures because I don’t use those).

My one gripe with the touchpad relates to scrolling. Its implementation of two-finger scrolling is responsive and fluid in most applications, but the two-finger momentum scroll gesture results in an awkwardly jerky transition from scrolling to stationary. Since the scrolling is fluid with fingers still on the touchpad, it doesn’t make sense that it can’t fluidly come to a halt. However, that ought to be fixable via software tweak, so hopefully a subsequent driver update can cure this problem.

That one quirk aside, even though I was coming from my MacBook Air’s gesture-laden OS X Lion environment, I didn’t feel like I was compromising when it came to the touchpad. As high as that particular bar is set, that’s impressive.

Resume rapidly

One of the selling points of both the MacBook Air and Ultrabook™ lines is how quickly they resume from sleep mode. Years ago, I never really thought that my venerable Dell XPS M1330′s resume time was a serious issue… until I started using the MacBook Air.

As quickly as the Air resumes, I found myself pleasantly surprised yet again with the Zenbook. I can’t remember ever opening the UX31′s lid and not finding it responsive to input almost immediately, whereas the Air is often unresponsive for several seconds after resuming to the desktop.

While he was taking the unboxing photos, Ray also shot this video of how quickly the Zenbook resumes from sleep:

Pretty impressive, huh?

Once the Windows desktop is visible, the machine is 100% usable. No delays and no compromises. That’s a welcome improvement compared to the facade of readiness that my MacBook displays for a few seconds before it’s truly responsive.

Keyboard kerfuffle

Unfortunately, my ongoing effort to acclimate to the UX31′s keyboard has been unsuccessful. If I weren’t mildly obligated to give it a fighting chance, the keyboard would probably have been a deal breaker in the beginning. I’ve typed on enough keyboards that don’t require any adjustment period that I don’t have much patience for one I don’t get along with.

I believe the fundamental problem is a mechanical one. What I’ve found is that I can fully depress the corner of a key, even to the point that it gives positive tactile feedback, without anything happening. Typing heavily on the direct center of a key seems to be 100% reliable, but that’s not how I type; especially when it comes to rectangular keys like shift and enter.

Fighting with a keyboard is difficult enough in any circumstance, but having an unreliable shift key is particularly brutal when you’re writing code (or writing about code). Just think about how many times you type characters like $, ", {, }, _, +, (, and ) during a average day. Now, imagine that about a third of them came out “unshifted”. Then, you’ll be able to picture how infuriating development work has been on this keyboard.

Another variation in the underlying hardware?

While I was in Bellevue for the Microsoft MVP Summit last week, I had the opportunity to try typing on two alternate UX31s, Jon Galloway’s and one in Bellevue’s Microsoft Store.

The one I tried in the Microsoft Store seemed slightly more responsive when I typed some ad-hoc jQuery code into a sticky note. One thing I did notice is that both of its shift keys had begun permanently sagging on their inside corners, presumably from heavy use in the store. Eventually, normal daily use would probably produce the same result.

On the other hand, Jon’s worked significantly better than mine. Even to the point that I wonder if this is another case of variance in the components in different batches of the Zenbook.

But, none of that helps me very much…

Maybe I’m a keyboard snob. I do use a diNovo Edge keyboard, with its “PerfectStroke key system”, on my development machine. Or, maybe the Zenbook’s keyboard just doesn’t like the cut of my jib.

Either way, we’re going our separate ways.

Ultimately, this particular Zenbook’s keyboard is a deal breaker for me. I’m not willing to waste time and money on a trial ‘n error process of searching for the occasional Zenbook that I can type well on (and hope that it doesn’t wear like the one I saw in the Microsoft Store).

What’s next?

The original plan was that I would write a total of three posts detailing my impressions of using the Zenbook on a daily basis. However, I’ve switched back to my MacBook Air as of last week. So, that plan doesn’t make sense anymore.

Instead, I’ll be writing a third post about what my month with the Zenbook has shown me that I’d like to have in my next laptop. Though the keyboard ultimately prevented me from sticking with the Zenbook, it has some great features that I’ve already missed since switching back to my MacBook Air.

Photo credit

As was the case in my previous post, all of the beautiful photos you see above are made possible by my friends at 35 Atlanta coming over and setting up studio in my house for a few hours. They’re based here in Atlanta, but they were doing a photo shoot in Cancun last week and have one in Seattle next month. If you need fantastic photos taken of just about any subject, in just about any location, I highly recommend them.

Disclosure

In case you’re reading this post before my previous one, I want to be clear that I received a complementary UX31 Zenbook in exchange for reviewing it. If there was any question before, this second review should have made it clear that I only recommend products I would actually use myself and that I’m giving you my fair and honest review. Also, here’s some legalese:

Disclosure of Material Connection: I received one or more of the products or services mentioned above for free in the hope that I would mention it on my blog. Regardless, I only recommend products or services I use personally and believe my readers will enjoy. I am disclosing this in accordance with the Federal Trade Commission’s 16 CFR, Part 255: “Guides Concerning the Use of Endorsements and Testimonials in Advertising.”

Related posts:

  1. The ASUS Zenbook UX31: Initial impressions
  2. Someone should copy these 4 features from the Zenbook


You've been reading A month with my Zenbook UX31, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Targeting WebKit is not like targeting IE6
source: http://feeds.encosia.com/~r/Encosia/~3/Ffz6E7YV-HI/

There’s been a bit of controversy lately concerning the rising dominance of WebKit-based browsers (e.g. Chrome, Safari, and Mobile Safari) and the potential that we’re repeating past mistakes:

Not so long ago, IE6 was the over-dominant browser on the Web. Technically, the Web was full of works-only-in-IE6 web sites and the other browsers, the users were crying. IE6 is dead, this time is gone, and all browsers vendors including Microsoft itself rejoice. Gone? Not entirely… IE6 is gone, the problem is back.

However, I believe there’s one gigantic difference between IE6 then and WebKit now that’s being overlooked.

Microsoft put the brakes on Internet Explorer development after IE6 because they realized that they were helping build the runtime for their own competition. If Internet Explorer releases had continued at the same pace, most everyone would probably be using IE15 today and IE6 would be as memorable as Chrome 4 or Firefox 7.

Conversely, Google has a vested interest in Chrome’s ongoing success (and WebKit’s success by extension). Instead of threatening Google’s primary revenue stream, WebKit and Chrome serve to enhance Google’s golden goose. So, unlike the past situation with Microsoft, Netscape, and IE6, Google has no motivation whatsoever to shutter active development on Chrome and WebKit if it overtakes Internet Explorer and Firefox.

Does that make vendor prefixes and targeting experimental features a great idea? Maybe not. Frankly, I’m not qualified to speak intelligently about cutting edge CSS features.

What I do know is that just because the current climate seems similar to the one ten years ago, that doesn’t mean it’s reasonable to assume history is repeating.

Related posts:

  1. Cooking the books is hard and doesn’t help anyone


You've been reading Targeting WebKit is not like targeting IE6, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Web API is now part of ASP.NET (and you can get it today)
source: http://feeds.encosia.com/~r/Encosia/~3/6IGIz9uWbVE/

One of the hardest parts of being privy to NDA information is keeping my mouth shut about new developments that I wish I could share with you immediately, often for months at a time.

Recent developments around ASP.NET Web API (formerly WCF Web API) are a perfect example of that conundrum. As development on WCF Web API seemingly stagnated on CodePlex, Microsoft had actually rolled the project into ASP.NET itself. The project was in no danger whatsoever, but (frustratingly) I wasn’t able to tell you that.

So, it’s a relief that today’s today’s ASP.NET MVC 4 Beta release has made that news public:

Top Features

  • ASP.NET Web API
  • Refreshed and modernized default project templates
  • New mobile project template
  • Many new features to support mobile apps
  • Recipes to customize code generation
  • Enhanced support for asynchronous methods
Note: It’s not entirely clear, but installing the MVC 4 beta allows you to use Web API in WebForms projects too.

Though Web API isn’t necessarily a gigantic step forward from using MVC’s controllers as a makeshift API for simple scenarios, it’s great that ASP.NET now has common mechanism for creating these endpoints that works the same way on both WebForms and MVC.

I’ve long held out against pressure to move from ASMX to WCF in WebForms projects, because accepting WCF’s complexity primarily only rewarded me with less flexible JSON serialization. By contrast, I’ve begun converting some of my projects from ASMX to Web API, and have been pleased with how easily Web API replaces ASMX.

I believe Microsoft has finally found a good balance between ASMX’s simplicity and WCF’s power with Web API.

Since it was built with jQuery in mind from the very start, I’m finding that Web API is perfect for the sort of work that I usually write about here. It even automatically responses to requests from jQuery with JSON, even if you use simple URL encoded parameters with the request, so adding an endpoint for AJAX interaction in either WebForms or MVC is a breeze now.

I’ll be writing more about actually using Web API here in the future, but I wanted to get this post published right away to help spread the news that Web API isn’t dead.

To learn more about what exactly Web API is and does, have a look at its section in the release notes. To get up and running quickly with some example code, take a look at the new Web API material on the ASP.NET site.

No related posts.


You've been reading Web API is now part of ASP.NET (and you can get it today), originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Read my interview with The Code Project
source: http://feeds.encosia.com/~r/Encosia/~3/CDCE30Pf-Ls/

I took part in The Code Project’s A Coder Interview series recently, and the result was published there yesterday. Terrence happened to send the questions at a rare moment when I wasn’t running in five directions at once, which led to me accidentally writing quite a bit.

Part of it touches on something important to me that I plan to write more about eventually:

What advice would you offer to an up-and-coming programmer?

Write about programming. Start a blog, answer questions on The Code Project or Stack Overflow, or whatever else suits you, but find some way to write about programming.

I can’t count how many times I began writing about something I thought I knew thoroughly, only to find that I had to fill in several important gaps in my knowledge to write about it competently. Just as important, you have to learn topics more comprehensively to distill and teach them in simple terms. The combination of writing about programming and making that writing as clear and simple as you can is a powerful exercise.

[…]

The interview also exposes my shameful stance on tabs vs. spaces, but you’ll have to go there to read that part…

Click here to read the full interview at The Code Project

Related posts:

  1. Learn from my Express.js HTTP status code blunder
  2. Review: The best JavaScript book I’ve read
  3. How I Got Started in Software Development


You've been reading Read my interview with The Code Project, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


The ASUS Zenbook UX31: Initial impressions
source: http://feeds.encosia.com/~r/Encosia/~3/vF4J2LEzkFw/

For over a year now, I’ve been using a 13” MacBook Air as my only laptop. Though it’s a bit underpowered and I prefer Windows to OS X, I was ultimately unable to resist Apple’s build quality compared to the Dell I had used previously.

However, I never fully resigned myself to accepting a dichotomy between quality construction and operating system. Thankfully, the recent proliferation of Windows-based Ultrabook™ machines seems to be rapidly bridging that divide.

Given my already-growing desire to find an alternative, when I was contacted about reviewing the ASUS’ Zenbook UX31 Ultrabook™, I decided to give it a go. I know I’m not alone in having been frustrated with a choice between machines that run Windows well and quality hardware, so I hope that you’ll find my experience of trying to move back from the MacBook hardware useful.

Disclaimer: Up front, I want you to know that I’m receiving a complementary UX31 in return for evaluating it and writing a few posts about that experience. I’ll give you my honest assessment of it and only recommend it if it meets my own standards, but I also think it’s important to be transparent and not potentially abuse your trust.

Unboxing

Lurking Inside the cardboard box that Amazon delivered it in, highly polished packaging awaited. ASUS did a great job with the unboxing experience, from overall presentation to ease of unpacking. It definitely reminded me of opening a high-end Apple product.

The UX31 comes encased in a protective plastic casing to keep the brushed aluminum’s finish pristine until you open the box, and its accessories are neatly packaged up with a canvas carrying pouch:

Along with its power adapter, the UX31 comes with a USB Ethernet adapter and VGA adapter that attaches to its mini-HDMI port. Nothing terribly unique, but both are nice to have right from the beginning (especially the ability to use a wired network connection for all the downloads that accompany initial setup of a machine that may be used for development).

Initial impressions

The first thing you notice about the Zenbook is the distinctive top cover of its lid. None of the photos I’ve seen online do it justice, but we tried with this one:

When I saw the radial pattern in photos online, I worried that it might look overdone or gaudy, but it looks great in person. Color me pleasantly surprised.

Quality construction

Removing it from the packaging, the Zenbook immediately impressed me with its rock-solid construction. One of my favorite things about the MacBook Air is that its unibody case feels solid, and my opinion is that the Zenbook bests the Air in that category, with an even more rigid case.

Superficial or not, that attribute is a significant part of how I judge the quality of a laptop’s construction. A laptop case that flexes or creaks when I lift it from a corner annoys me to no end. Holding the Zenbook with one hand, even from the front corners, there’s not hint of flex in its chassis.

Contrasting with the rest of the case’s angular design, the lid’s convex curvature makes the machine feel more comfortable in my hand than my MacBook Air does when both are closed.

Also worth noting, I felt no flex in the lid when I squeezed it to lift and carry. That lid-flex is something I’ve always found unsettling about my Air (and the Dell before it).

Windows 7, now with Bing Bar?

It only took a few minutes to uninstall later, but having a required Bing toolbar installation at the OS level didn’t feel very zen to me. I understand that preinstalled software helps subsidize the machine, but this isn’t a $200 netbook.

The exterior of the machine sets a high bar, and it’s important that the interior hardware and software live up to that high expectation. Thankfully, the remainder of the UX31′s preinstalled software was more tasteful.

Fantastic sound

I’m listening to music on the laptop’s built-in speakers as I write this post, which is something I’d never bother with on the Air (or any laptop I’ve ever used, for that matter). But, since the Bang & Olufsen audio is something touted right on the case itself, I figured I ought to give it a try.

From the first note that played, I was astonished by the quality of sound that the UX31’s sound system produces. Of course, it’s no rival for a proper set of external speakers, but it’s amazing for concealed, self-contained speakers.

Keyboard concerns

I’ve struggled a bit while typing this entire post on the UX31. The keyboard itself looks and feels very nice, with a setup that’s similar to the “chicklet” layout you’ll see on many modern keyboards:

Unfortunately, there’s something about how the keys respond to quick, light touch typing that I’m having a difficult time acclimating to. I’ve had adjustment periods with other keyboards in the past, so I’m hoping time will improve my ability to coax the desired result out of this one too.

More to come

This post has outlined my very initial impressions of using the UX31 for a few hours. I’ll be continuing to use it over the next couple of months and will publish another post after a few weeks and then a final review after a full two months of use. I hope that the end result is that I’ll be able to shelve my MacBook Air, but I’ll let you know how it turns out one way or the other.

How about those photos?

Those photos of the UX31 looked great, didn’t they? Almost… Professional. Well, that’s because they are. My good friends at 35 Atlanta came over, set up studio in my house, and took 55 amazing photos of the UX31 for me to use in these posts. If you need photos of just about any kind, check them out.

Related posts:

  1. A month with my Zenbook UX31
  2. Someone should copy these 4 features from the Zenbook


You've been reading The ASUS Zenbook UX31: Initial impressions, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Adding your own callbacks to existing JavaScript functions
source: http://feeds.encosia.com/~r/Encosia/~3/mZ6gyCZJm28/

Hey Dave, is there a way to create an event handler so when .tmpl() is done it will fire a function? I’m trying to make it global, so I was hoping I could say, when ANY template gets done, do this…

The question of how to retroactively add hooks before and/or after a pre-existing JavaScript function executes is one that comes up from time to time. Whether it’s a simple method like tmpl(), a server-generated script artifact, or a function in a third-party script, sometimes it’s desirable to alter a JavaScript function without access to change the original declaration of the function.

One of the handy things about JavaScript is that you can combine its functional and dynamic aspects to make surprisingly quick work of tasks like this one. Doing so is fairly straightforward, but it involves an approach you might not consider if you’re more familiar with languages that lack JavaScript’s unique features.

In this post, I’ll briefly cover a few examples of how to “patch” existing JavaScript functions with callbacks. We’ll begin with simple examples, then address an issue that stems from applying this approach to jQuery plugins, and finish with a more elegant way to handle the problem of patching functions that accept parameters.

A simple() example

Let’s start with the simplest possible example, a function that accepts no arguments and returns nothing:

function simple() {
  // I am a black box.
}

Maybe that function is pre-defined and emitted by server-side code. Maybe it’s part of a script you’re referencing from a public CDN. For whatever reason, assume that this function is part of your page, but that you don’t have the ability to directly change its code.

If you need to run some of your own code before and/or after any time the simple() function is called, you can use a technique called monkey patching to achieve that without access to the original function declaration.

// Get a reference to the previously defined simple() function.
var oldSimple = simple;
 
function simple() {
  // Code that runs before any call to simple() here.
 
  // Make a call to the old/previous simple() function.
  oldSimple();
 
  // Code that runs after any call to simple() here.
}

Since functions are just like any other variable in JavaScript, it’s that simple.

Without touching the original simple() function declaration, this snippet has effectively redefined it anyway. Calls to the original function will also execute our before and after code now, unaware that anything has changed.

Parameters and external “event” handlers

If you want to apply this technique to a function that accepts parameters, you’ll also need to capture and relay those parameters.

Take this more complex function, for example:

function complex(foo, bar, baz) {
  // An assortment of black boxes.
}

You could patch in a “before” event, parameters unimpeded, like this:

var oldComplex = complex;
 
// Capture the parameters that the original complex()
//  function expects.
function complex(foo, bar, baz) {
  // Call onBeforeComplex() if it's defined when this runs, and
  //  pass a copy of the parameters that complex() was called with.
  if (typeof onBeforeComplex === 'function')
    onBeforeComplex(foo, bar, baz);
 
  // Call the original function, parameters included.
  oldComplex(foo, bar, baz);
}

Using a separate onBeforeComplex() function instead of inline code isn’t necessary, but I prefer that approach. Now, you can drop this code into a script include anywhere after complex() is defined and then declare the “handler” function anywhere on the page (or not at all).

Passing foo, bar, and baz to onBeforeComplex() is optional, of course, but it’s usually helpful to know something about what sort of call triggered the event.

Applying this to jQuery plugins

Now let’s apply this technique to the real-world problem of updating tmpl(). Doing that isn’t much more difficult than the previous example, but we do need to identify the method’s signature first so that we can apply the patch.

Digging into the last version of jQuery.tmpl.js on GitHub, the function we’ll need to override can be found beginning on line 80:

So, the function we’ll need to patch is jQuery.fn.tmpl. Given the previous examples, you might thing it would be as easy as this:

var oldTmpl = jQuery.fn.tmpl;
 
jQuery.fn.tmpl = function(data, options, parentItem) {
  if (typeof onBeforeTmpl === 'function')
    onBeforeTmpl(data, options, parentItem);
 
  oldTmpl(data, options, parentItem);
}

Unfortunately, that will break tmpl() (in two separate ways, no less).

jQuery plugins make “this” more complicated

Applying the monkey patching approach to functions that operate on and return jQuery collection objects, such as the tmpl() plugin that led to this post, requires extra consideration. The crux of jQuery’s fluent API is that chainable jQuery methods both operate upon and return an instance of the jQuery object.

Now that we’re interjecting an additional level of abstraction, we need to be sure to maintain the scope of this down into the original jQuery plugin method and preserve the original function’s return value. Otherwise, our intermediary function will break jQuery’s chaining.

Using apply() to call the original function allows us to control its this value:

var oldTmpl = jQuery.fn.tmpl;
 
// Note: the parameters don't need to be named the same as in the
//  original. This could just as well be function(a, b, c).
jQuery.fn.tmpl = function(data, options, parentItem) {
  if (typeof onBeforeTmpl === 'function')
    onBeforeTmpl.apply(this, [data, options, parentItem]);
 
  // Make a call to the old tmpl() function, maintaining the value 
  //  of "this" and its expected function arguments.
  var tmplResult = oldTmpl.apply(this, [data, options, parentItem]);
 
  if (typeof onAfterTmpl === 'function')
    onAfterTmpl.apply(this, [data, options, parentItem]);
 
  // Returning the result of tmpl() back so that it's actually 
  //  useful, but also to preserve jQuery's chaining.
  return tmplResult;
};

By capturing the return value of the original tmpl() function and returning that back to the original caller, chaining is preserved at that previous level. That’s particularly important in this specific example because that return value is the rendered template.

Better argument handling

If you’re like me, explicitly capturing and passing each individual function parameter doesn’t feel great. Not only is it extra work to determine how many parameters a method accepts, but our patched version of tmpl() would stop working correctly if the original were updated to begin accepting additional parameters.

We can improve this situation easily enough by taking advantage of JavaScript’s built-in way to capture all of the parameters that were passed to a function. Aptly named arguments, this so-called array-like object is perfect for eliminating the explicit plumbing code to pass parameters between the patched function and the original.

Even better, arguments will capture all the parameters passed into a function even if that function’s declaration doesn’t accept parameters at all. So, now there’s no need to worry about matching the original’s function signature:

var oldTmpl = jQuery.fn.tmpl;
 
jQuery.fn.tmpl = function() {
  if (typeof onBeforeTmpl === 'function')
    onBeforeTmpl.apply(this, arguments);
 
  var tmplResult = oldTmpl.apply(this, arguments);
 
  if (typeof onAfterTmpl === 'function')
    onAfterTmpl.apply(this, arguments);
 
  return tmplResult;
};

Throw that code on a page, anywhere after the reference to jquery.tmpl.js, and then all existing usages of tmpl() will begin triggering the before and after “events”.

Conclusion

We took a circuitous route to get here, but I hope you agree that it was worthwhile to build the solution up step by step. Even if you don’t need to patch an event into tmpl(), you might be surprised how often this technique comes in handy once you’re keeping the possibility in mind.

Related posts:

  1. How to easily enhance your existing tables with simple CSS
  2. Using external templates with jQuery Templates
  3. Composition with jQuery Templates: Why and How


You've been reading Adding your own callbacks to existing JavaScript functions, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Five years of Encosia
source: http://feeds.encosia.com/~r/Encosia/~3/S148V2sKjcI/

As I ponder the title of this post, I’m conflicted.

I clearly remember writing last year’s post and thinking that it didn’t seem like four years could have possibly passed since I started publishing here. As I write this one, I find myself feeling like it’s surely been much longer than five years.

I guess you could say 2011 has been a long year?

Relativity aside, this week saw the fifth anniversary of the night that I hastily threw this site together and published my first post. So, I guess it’s that time again.

Site stats

Page views are far from a perfect metric for measuring the progress of a site like this one, but it’s one of the few consistent, long-term metrics I have. Aggregators come and go, RSS is giving way to Twitter, and social media has decentralized the conversation that would have taken place in a post’s comments years ago (A change for the worse, in my opinion). So, I measure what I can.

Pleasantly enough, the stats have continued to be encouraging.

Since last year’s post, traffic has grown by a healthy 28%. That’s just over 1.6 million page views since this time last year. Insignificant compared to some sites, but I find it truly humbling to think that my little corner of the Internet has been visited 1.2 million times in the last year. Maybe even more incredible to me is that nearly 400,000 of those visits were apparently return visits. Frankly, I have a hard time rationalizing that number.

Interestingly enough, I seem to have benefited from Google’s recent algorithm tweaks aimed at content farms. I saw two distinct, sustained bumps in search traffic this year. I won’t complain…

The Best Posts of 2011

I considered omitting this section this year (and the year-end post itself for that matter). I figured that I probably care more about this than you do and there’s no point wasting everyone’s time, but Joe Brinkman disagrees.

If at least one person finds it useful to have a quick reference of the year’s most popular posts, then who I am to argue?

In JavaScript, curly brace placement matters: An example – This post received the most traffic, primarily due to spending some time on the front page of Hacker News and the JavaScript subreddit. Frankly, I didn’t intend for it to capture the level of attention that it did at all. It was targeted at developers less experienced with JavaScript, but it ended up igniting a light-to-medium religious war around the Allman vs. K&R debate among more seasoned developers instead.

Next year I should post about tabs vs. spaces.

jQuery 1.6.2 syntax error? You may be the victim of SEO. – Similarly, this post did well in the stats simply because it spent some time at the top of Hacker News. Though I did have to endure the predictable abuse from the denizens of Hacker News, exposure there was enough to get some attention focused on the issue and ultimately get it resolved. I’d say that was worth suffering the “Well, Actually” crowd for a couple days.

Cripple the Google CDN’s caching with a single character – Yet another post in this lineup by virtue of the time it spent on the front page of Hacker News. Astute readers correctly pointed out that the Google CDN’s HTTPS assets are served with a header that allows them to be cached. Unfortunately, too many people got stuck on that inaccuracy and missed the larger point.

Since HTTP-delivered scripts aren’t eligible for use as cache hits for HTTPS references to the same script (and vice versa), using the HTTPS reference isolates the potential cross-site caching benefit to only users who have the HTTPS-served script cached. With the vast majority of jQuery CDN references being of the HTTP variety, it’s important to understand that and not use the HTTPS reference unless you actually need it.

Even better, use the protocol-less reference and never worry about it again.

ASP.NET web services mistake: manual JSON serialization – This is one that I felt strongly about. I had been seeing more and more code floating around that used JavaScriptSerializer or DataContractJsonSerializer to manually handle the encoding to and from JSON in ASP.NET services that were automatically doing that anyway. The result being nasty double-serialization of the data, and/or sending values in and out of methods as strings instead of using the strongly-typed objects that the data was usually based on ultimately anyway.

Fun fact: I wrote and published this post, from start to finish, while attending MIX11.

Use jQuery to extract data from HTML lists and tables – This post was somewhat niche, but I‘m a fan of the general approach of using list comprehension methods against the DOM. Particularly, map() is fantastically well-suited to dealing with HTML and the DOM. I’ve subsequently linked to this post to help explain the solutions to all sorts of tangentially related problems. I hope that many of the people who read this post were able to extrapolate the more general usefulness of map() and specifically jQuery’s implementation of it for dealing with selections of HTML elements.

What I expect from 2012

JavaScript is going to continue exploding in popularity. If you’re a web developer and haven’t taken a serious look at Node.js yet, now’s the time. JavaScript is not without flaws, but I think full-stack JavaScript is the future for a lot of platforms and web development in particular.

As new developers begin learning about development, who would choose a platform that requires learning a different client-side and server-side language if a solid platform using a single language from start to finish existed?

Of course, that was part of the promise of failed technologies like Java applets and Silverlight, but JavaScript has the luxury of already being pervasive, native, and well-integrated in every user’s browser. Compared to conquering that client-side morass, ironing out the server-side platform wrinkles and maturing a web framework or two is nothing.

Mobile and touch will change how we approach web development. It’s hard to believe that designing for touch was an obscure niche when I started this site five years ago. More than just avoiding hover menus and making click targets large enough for fat fingers, I think there’s still undiscovered potential for touch and gesture based UIs that we’re going to see begin making its way onto the web as touch input becomes more ubiquitous on a wide range of devices.

Of course, you can’t touch what you can’t see. Making sites work on a wide variety of screen sizes is more important now than ever. Using CSS media queries to build responsive layouts takes a bit of acclimation, but the results are absolutely worthwhile. While responsive layouts aren’t new, I think they will become much more mainstream in the next year. Sites not taking advantage of media queries will probably seem as quaint as sites currently using table layouts soon.

Windows 8 is going to be huge. I don’t know if it’ll be a huge success or a huge flop, but I think it’s safe to say there’s not much middle ground between the two outcomes. It’s certainly a bold move.

As an iPhone, iPad, and MacBook Air owner, I would be overjoyed if I could migrate from those devices to Windows-based devices of comparable quality. I’m rooting for Microsoft to pull this one off.

Thanks

As always, thank you for lending me your eyeballs for a few minutes.

If you’re reading this paragraph, there’s a decent chance that I owe you a bit of gratitude for your support over the past year, be it pointing someone here to solve a problem, a retweet or two, or just sparing me your attention.

Thanks.

And you?

How was your 2011? What technologies helped you succeed or presented challenges for you this year? What do you think’s going to be most important in 2012?

I’m interested to hear what you think. Leave a comment or leave a link to your own year-end post if you’d like.

Related posts:

  1. 3 years of Encosia, the best of 2009, and my gratitude
  2. 4 years of Encosia, and the best of 2010
  3. Announcing the 2010 Encosia Holiday Giveaway


You've been reading Five years of Encosia, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Using CORS to access ASP.NET services across domains
source: http://feeds.encosia.com/~r/Encosia/~3/8NqtWwXnjFY/

Successfully completing a cross-domain request to an ASMX service using CORS

Work on client-side applications long enough and it’s just about inevitable that you’ll eventually want to make an AJAX request that breaches the browser’s XMLHttpRequest security restrictions. Limitations on cross-domain requests are great when they’re preventing malicious sites from malfeasing, but are a thorn in the side when they complicate your legitimate applications.

Traditionally, direct communication across the same-origin boundary required using a rickety (though clever) workaround called JSONP. JSONP is a reasonable compromise if all you need to do is make blind requests to a third-party API like Twitter, but comes up short if you need to use any HTTP verb other than GET. Of course, that’s a deal-breaking issue when you’re working with ASMX ScriptServices or ASPX page methods.

Luckily, a relatively new feature has been making its way into browsers which provides a robust solution to the cross-domain AJAX problem: CORS.

In this post, I’m going to show you how to recognize exactly which requests are cross-origin, how to enable CORS for your ASP.NET site, and the extra configuration necessary when you’re working with ASP.NET’s JSON-enabled services.

Before we get started, I want to emphasize that this approach won’t work with any version of IE prior to IE10. If supporting older versions of IE is a requirement in your target environment, you’re stuck with something like JSONP or a server-side proxy. This will work in any version of IE if Chrome Frame is installed and enabled by your site/server though.

Understanding what constitutes a different “origin”

When it comes to making cross-origin AJAX requests, it’s helpful to understand which requests actually are cross-origin. Of course, a request from a page served under one domain to a resource on an entirely different one definitely falls under the umbrella of cross-origin:

However, the common moniker for these requests, cross-domain, tends to be misleading. While a request from one domain to another is obviously cross-origin, browsers are much more picky than that.

For example, a request from foo.domain.com to bar.domain.com is just as much cross-origin request as one to abc.com. That’s not quite as intuitive as the traditional cross-domain scenario, but requires the same consideration.

A less obvious troublemaker is making a request from localhost:8080 to localhost:8081, which XMLHttpRequest’s security restrictions will also deny you from making. That’s a particularly troublesome scenario for ASP.NET developers since Visual Studio is all too happy to help you spin up a separate services/API project almost transparently hosted at its own separate port.

The easiest way to determine whether a particular request will fall under the umbrella of cross origin resource sharing is to compare the portion of both addresses appearing before the first forward slash. Any difference before the first forward slash, including the port, protocol (HTTP vs. HTTPS), and sub-domain, will thwart a traditional XHR-based AJAX request.

Enabling CORS for an ASP.NET site

Though the conventional wisdom about cross-domain or cross-origin requests has long been JSONP or nothing, a solution called Cross-Origin Resource Sharing has gained broad support in modern browsers over the past couple years. This standard defines a set of HTTP headers that a server can use to instruct browsers that it’s okay for certain XMLHttpRequest requests to that server to cross the same-origin boundary.

In the broadest case, enabling CORS for an ASP.NET site is simple. The enable-cors.org site has handy list of concise examples of how to configure a variety of servers for CORS, including IIS. For sites hosted on IIS7.0+ and Integrated Pipeline, enabling CORS is as simple as adding this to the site’s web.config:

<system.webserver>
 <httpprotocol>
  <customheaders>
   <add name="Access-Control-Allow-Origin" value="*" />
  </customheaders>
 </httpprotocol>
</system.webserver>

That simple change gets you half way there. A regular GET request for an ASPX page’s HTML would work now, for example. Unfortunately, the Content-Type necessary for working with ASMX ScriptServices throws a new wrench in the works:

A partially successful CORS request to an ASMX ScriptService

As it turns out, requests to ASP.NET’s JSON-enabled endpoints require one last configuration step to allow the request to go through unimpeded.

Access-Control-Allow-Headers

Sending the Access-Control-Allow-Origin header allows basic cross-origin access, but calling ASP.NET services like ASMX ScriptServices, ASPX page methods, and WCF services with AspNetCompatibilityRequirements enabled requires jumping through a few more hoops. Namely, sending a specific Content-Type header of application/json.

One of the security precautions that the CORS specification includes is that browsers must tightly control what’s sent along with these cross-origin requests. Among the items that must be explicitly allowed: any but the most basic HTTP headers, including Content-Type.

In order for CORS requests to specify their Content-Type, your site needs to respond with one additional CORS header: Access-Control-Allow-Headers

That brings the web.config modifications necessary to this:

<system.webserver>
 <httpprotocol>
  <customheaders>
   <add name="Access-Control-Allow-Origin" value="*" />
   <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customheaders>
 </httpprotocol>
</system.webserver>

And finally, it’s possible to use the same, familiar jQuery $.ajax() syntax to request our service from same- and cross-domain origins alike:

A successful CORS request to an ASMX service with jQuery

Conclusion

Even as we’re teetering at the precipice of 2012, CORS is still a fairly new feature and lacks ubiquitous support. IE10 should support CORS as fully as Chrome and Firefox already do, but the XDomainRequest implementation in earlier versions of IE does not (to my knowledge) support Access-Control-Allow-Headers, which makes it all but useless in this scenario.

If you’re comfortable leaving the comfy confines of XMLHttpRequest and jQuery’s $.ajax, a more cross-browser friendly solution does exist: easyXDM. I haven’t personally used easyXDM beyond a bit of experimentation, but the approach it takes in older browsers is one that has been proven to be solid by similar libraries like Socket.IO.

However, if you’re working in an environment where you can mandate Chrome (or Chrome Frame in IE9-) and/or Firefox as the browser of choice, CORS is an invaluable addition to your bag of tricks (I feel like I’ve typed that phrase in another post recently…). I hope this post will help you get your feet wet with this new technology which seems to get more lip service than actual usage.

Get the source

If you’d like to browse through a complete working example of what’s been covered in this post, take a look at the companion project at GitHub. Or, if you’d like to download the entire project and run it in Visual Studio to see it in action yourself, grab the ZIP archive.

Browse on GitHubDownload the ZIP

Related posts:

  1. Save yourself some typing when you call ASP.NET services
  2. ASMX and JSON – Common mistakes and misconceptions
  3. Using jQuery to Consume ASP.NET JSON Web Services


You've been reading Using CORS to access ASP.NET services across domains, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Help me organize my posts about using jQuery with ASP.NET
source: http://feeds.encosia.com/~r/Encosia/~3/TIeTEaNW6uc/

Image by OZinOH on Flickr

One of the longest running themes here has been the compelling intersection between ASP.NET and jQuery. Beginning with my post about using jQuery to circumvent ASP.NET AJAX’s client-side apparatus for calling ASMX services, I’ve been writing about using ASP.NET and jQuery since the Spring of 2008.

As these related posts have accumulated over the years, I’ve made an effort to weave a thread of cross-links between them posts where appropriate. However, it’s nearly impossible to anticipate every possible entry point and subsequent path that someone might find themselves following here.

So, I’ve decided to finally do what I should have done a year or two ago: Create a top-level index to organize and improve the accessibility of my content for ASP.NET developers interested in integrating jQuery into their sites.

You can see my first draft of that here: jQuery for the ASP.NET Developer

Unlike the other content here, I’m publishing this one long before it’s “finished”. My hope is that I can solicit early feedback to help better construct a useful narrative while the document is still in its formative stages. So, if you have any feedback on the current page or what you think should ultimately be there, please leave me a comment on either this post or that page, contact me directly, or even @mention it my way on Twitter.

Related posts:

  1. Best of 2008: 5 most popular posts
  2. Best of 2007: 5 most popular posts (and contest winners)
  3. 3 mistakes to avoid when using jQuery with ASP.NET AJAX


You've been reading Help me organize my posts about using jQuery with ASP.NET, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


Learn from my Express.js HTTP status code blunder
source: http://feeds.encosia.com/~r/Encosia/~3/RUO_mqr85Kw/

Screenshot of the 200 Object] HTTP status code in Firebug

If you’re like me, HTTP status code 200 Object] unknown probably doesn’t ring any bells. Of course, that’s mainly because it doesn’t exist.

So, how did I end up with the screenshot above? I’ve been running with scissors again. It was one of the more popular web frameworks for Node.js that I cut myself with this time: Express.js

Unfortunately, a malformed status code like 200 Object] will cause some browsers (including the version of Chrome I was using at the time) to refuse loading the page at all. That quickly elevated the importance of my strange status code from a trivial oddity to an annoying thorn in the side.

As it turns out, my code was running up against a documented Express feature and the remedy was simple enough.

Status code: RTFM

The site I was working on at the time is simple enough, built from a handful of views and a few supporting scripts that act as “models”. Unfortunately for me, the topic of this particular site led me to pass one of those models into a view using an object property named status:

app.get('/', function(req, res) {
  Models.getIndexViewModel(function(model) {
    res.render('index', { status: model });
  });
});

You can probably guess where my bizarre HTTP status code came from now, and a quick search through the relevant Express documentation confirms:

This options object is also considered an “options” object. For example when you pass the status local, it’s not only available to the view, it sets the response status to this number. This is also useful if a template engine accepts specific options, such as debug, or compress. Below is an example of how one might render an error page, passing the status for display, as well as it setting res.statusCode.

Head, meet desk.

Instead an HTTP status code, I was passing a JavaScript object to Express and it was trying to interpret the string representation of that object as an HTTP status code to apply to the response. In JavaScript, objects evaluate to a string value of [object Object], which is how Object] ended up being sent down instead.

I didn’t take the time to dive into Express’ source to determine why the [object Object] string ended up being split on the whitespace, with only the second half showing up in the actual response. The net takeaway is the same regardless of why: don’t pass status into your Express views unless you understand what that actually does.

Everything’s easy in hindsight…

In retrospect, it may seem painfully obvious that my choice of property names was the culprit, but I didn’t benefit from this post’s narrow context at the time.

I didn’t end up finding the issue until days after writing the code that caused the problem. Since the odd status code didn’t break anything while I was testing in Firefox, it wasn’t readily apparent that I had introduced a bug at all. By the time I tested in a browser that choked on the invalid status code, I was far removed from the relevant code, and it wasn’t as easy to debug as it might seem now.

I almost decided against posting this for fear of looking like a dunce, but I can’t be the only person that will run into this problem. So, I hope this post saves at least one person from running into the same self-inflicted injury that I did.

Related posts:

  1. Easy incremental status updates for long requests
  2. Updated: See how I used Firebug to learn jQuery
  3. 4 ASP.NET AJAX JavaScript UI methods you should learn


You've been reading Learn from my Express.js HTTP status code blunder, originally posted at Encosia. I hope you enjoyed it, and thanks for reading.

If you've got any feedback, please click through and leave a comment; I'd love to hear from you. You can click here to jump directly to the comment section of this post.


What's Shakin' on SNI

Popular Communities

» Drug and Alcohol Addiction (258)  » Loans (229)  » Drug Rehab Centers (55)  » Domains (52)  » Entertainment (34)  » Automobiles (13)  » News and Newspapers (12)  » Stocks and Bonds (7)  » Restaurants (7)  » Health and Wellness (6)  » Real Estate (5)  » Travel (5)  » Health (4)  » Business (4)  » Gambling (3)  » Hotels (3)  » Adult (2)  » Business Services (2)  » Mortgage (2)  » Food (2)  » Dentistry (2)  » Home Improvement (2)  » Vacation Destinations (2)  » Shopping (2)  » Information Technology (2)  » Sports - Golf (2)  » Technology (2)  » News (2)  » General (2)  » Cash Advances (2)  » Travel Tours and Groups (1)  » Alcohol Addiction (1)  » Drug Abuse and Addiction (1)  » Internet - SEO (Search Engine Optimization) (1)  » Stock Trading (1)  » Politics (1)  » Sports - Football (1)  » Marketing (1)  » Jobs and Training (1)  » Farming (1)  » Hobbies (1)  » Garden (1)  » Education (1)  » Coupons (1)  » Finance and Banking (1)  » Beauty & Fashion (1)  » Artwork (1)  » Music (1)  » Electronics (1)  

Copyright ©2012 SocialNetworkinc.com. All Rights Reserved.

Sitemap · RSS Feed · Cloud Vision · Contact · Privacy Policy · Disclaimer/Terms & Conditions · CSS and XHTML