Monthly Archives: June 2009

Never worry about ASP.NET AJAX’s .d again

When I recently received this message from a frustrated reader:

After hours and hours of slamming my head into the desk it turns out it was the darn "d" in the response. My home computer is on .NET 2.0 and my work computer is on 3.5. Jimminie Christmas!

I realized that the “.d” introduced in ASP.NET AJAX 3.5’s JSON responses is still all too common a stumbling block when calling ASP.NET AJAX services through a library such as jQuery. In fact, with jQuery’s popularity among ASP.NET developers on the rise, this appears to have become an even more frequent problem.

Since a lot of people are having trouble with it, I want to share one method you can use to completely isolate your code from the problem. If you bake this into an $.ajax() code snippet or otherwise use it as a template for calling ASP.NET AJAX services in jQuery, you should never have to think or worry about the “.d” again.

In this post, I will show you how to detect the “.d” and how you can completely isolate your $.ajax success handler from it.

“.d” what?

If you aren’t familiar with the “.d” I’m referring to, it is simply a security feature that Microsoft added in ASP.NET 3.5’s version of ASP.NET AJAX. By encapsulating the JSON response within a parent object, the framework helps protect against a particularly nasty XSS vulnerability.

Before ASP.NET 3.5, “ScriptServices” and page methods returned their data at the top level of the JSON response, like this:

2.0 JSON Response in Firebug

In ASP.NET 3.5 and later, the same server-side code returns this:

3.5 JSON Response in Firebug

For more information about the change and why the change is a good one, be sure to see my earlier post: A breaking change between versions of ASP.NET AJAX.

However, what my previous post lacks is a solution for mitigating the inconsistency entirely. Using different client-side code against 2.0 and 3.5 based services is workable, but far from ideal. Wouldn’t it be nicer to not have to worry about it?

Determining whether or not the “.d” is there

In order to isolate ourselves from the “.d”, we first need a reliable way to test for its presence. Though JavaScript provides several methods for determining this, I suggest hasOwnProperty, as recommended by Douglas Crockford.

By using hasOwnProperty, your code is protected against unexpected changes to an object’s prototype chain. Though it is an unlikely problem to encounter, it’s always best to code defensively in JavaScript. The browser is a hostile environment!

Using hasOwnProperty to test for “.d”, you might end up with something like this:

$.ajax({
  type: "POST",
  url: "WebService.asmx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType:"json",
  success: function(msg) {
    if (msg.hasOwnProperty("d"))
      // Leave the .d behind and pass the rest of 
      //  the JSON object forward.
      DoSomething(msg.d);
    else
      // No .d; no transformation necessary.
      DoSomething(msg);
  }
});
 
function DoSomething(msg) {
  // Do something with the response data here.
  //  Expect it to consistently have no .d.
}

This code will perform identically against any version of ASP.NET AJAX.

Unfortunately, this might still get in your way. You may not always want to use the response in a call to another function, and you’ll have to remember the conditional every time you write a success handler.

Don’t make me think

I prefer a solution that doesn’t touch the success handler at all. Then, you’re free to integrate the “.d” handling into a generic $.ajax code snippet in Visual Studio and/or easily copy-paste it between files without modification.

Luckily, jQuery provides a mechanism that allows us to do just that: dataFilter.

The dataFilter parameter to $.ajax allows you to arbitrarily transform a response just before the success handler fires. Specifically tailored to this sort of situation, it passes response data into a callback function, captures the return value of that callback, and then passes the modified data into your success handler.

Hence, you can forever stop worrying about that pesky “.d” like this:

$.ajax({
  type: "POST",
  url: "WebService.asmx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataFilter: function(data) {
    // This boils the response string down 
    //  into a proper JavaScirpt Object().
    var msg = eval('(' + data + ')');
 
    // If the response has a ".d" top-level property,
    //  return what's below that instead.
    if (msg.hasOwnProperty('d'))
      return msg.d;
    else
      return msg;
  },
  success: function(msg) {
    // This will now output the same thing 
    //  across any current version of .NET.
    console.log(msg.foo);
  }
});

Now, regardless which of these JSON forms the server returns:

// ASP.NET 2.0 with the ASP.NET AJAX Extensions installed.
{'foo':'bar'}
 
// ASP.NET 3.5 and 4.0.
{'d':{'foo':'bar'}}

Your success handler will simply receive this consistent JSON object every time:

{'foo':'bar'}

dataType: none of your business

It’s important to note the removal of the dataType parameter in the $.ajax() code above. This is required in order to prevent a double-eval of service responses containing only a single string.

Internally, jQuery uses a combination of the dataType parameter and the implicit type the response. If the dataType is "json" and typeof(response) is “string”, then jQuery uses eval() to deserialize the response.

In the example above, manually deserializing the response in dataFilter results in it being of type Object, jQuery leaves it alone, and our dataFilter’d object makes its way back to the success callback either way.

However, if the dataType is set to “json” and the “.d” sanitized response happens to be of JavaScript type “string”, jQuery will assume that it is a JSON response from the server and still needs to be deserialized. That will throw an error at best.

The solution is to simply drop the dataType parameter from the $.ajax() call. It is only needed for purposes of instructing jQuery how to deserialize the response, and we’re handling that ourselves now.

Thanks to Brett for pointing this out.

Wait, isn’t eval() supposed to be evil?

If the eval() usage gives you pause, don’t worry. For now (as of jQuery 1.3.2), this is the same mechanism that jQuery uses to deserialize JSON too. Though eval() is potentially evil, it is still a necessary evil in many browsers.

In my next post, I’ll show you how to modify this to leverage a native browser implementation of JSON.parse instead of eval(), available in some newer browsers.

That post is available now: Improving jQuery’s JSON performance and security.

###

Originally posted at Encosia. If you’re reading this elsewhere, come on over and see the original.

Never worry about ASP.NET AJAX’s .d again

Build a Cheaper Backyard Greenhouse [DIY]

Greenhouses are invaluable to gardeners. You can start seedlings earlier, grow plants later, and otherwise extend the window of warmth that Mother Nature gives you. Best of all, you can build one without going broke.

The Door Garden, a blog devoted to getting gardeners the most for their dollar, put together a tutorial for making an inexpensive garden greenhouse. The author of the tutorial, a self-identified pack rat, was able to construct the greenhouse for $50, thanks to having many of the basic supplies horded away from other projects. Even if you have to buy brand new pieces, the cheap construction means you won’t spend more than $150 for a sizable backyard greenhouse.

I’ve rounded up all of the materials and it looks like I’m going to end up with about $50 in a 165 square ft. green house … even if I had bought everything new just for this polytunnel It would still only come to about $120 $150 – less than a dollar per square ft.

Check out the full tutorial at the link below to see the build process and finished greenhouse. The end result is quite sturdy and snow-friendly for such a small budget. If you don’t need that much greenhouse space, make sure to check out some of our more modest gardening DIY projects, like recycling old windows into seedling greenhouses.

$50 Hoop Greenhouse [The Door Gardner]





Bake Delicious and Economical Homemade Sourdough Bread [Food]

If you tried out the technique we shared earlier this week for easy homemade bread and want to bolster your baking chops, you’ll definitely want to check out this detailed guide to homemade sourdough bread.

Laura and Barb, the two sisters behind the culinary blog My Sister’s Kitchen, post an excellent and detailed tutorial on homemade sourdough. It isn’t as simple as some of the other bread recipes and bread baking techniques we’ve shared in the past, like the aforementioned easy homemade bread, or five-minute quickbread, but based on the rave reviews their technique has received, we think you’ll find it worth the extra effort. While it’s a bit more intensive than some of the other methods we’ve covered, it’s still quite economical:

A very important detail to note is that this method makes extra large loaves that are approximately 4.5 pounds each. Each loaf costs only $0.68 to make. That is sixty-eight cents. I buy flour and yeast in bulk, so it’s possible that if you buy your ingredients at a regular grocery store, your loaf might cost twice that….a whopping $1.36! As you’ll see, that’s for a loaf that’s about 3 times the size of a loaf of grocery store bread.

They have a step by step tutorial on Instructables, linked below, and then a companion post on their blog with additional information about sourdough, creating your own sourdough starter, and various recipes. If you bake your own sourdough bread, due either to thrift or refined taste, we want to hear about it in the comments below.





Follow fork for dtrace pid provider?

 

There is a ongoing request to have follow fork functionality for the dtrace pid provider but so far no one has stood upto the plate for that RFE. In the mean time my best workaround for this is this:

cjg@brompton:~/lang/d$ cat followfork.d
proc:::start
/ppid == $target/
{
 stop();
 printf("fork %dn", pid);
 system("dtrace -qs child.d -p %d", pid);
}
cjg@brompton:~/lang/d$ cat child.d
pid$target::malloc:entry
{
printf("%d %s:%s %dn", pid, probefunc, probename, ustackdepth)
}
cjg@brompton:~/lang/d$ pfexec /usr/sbin/dtrace -qws followfork.d -s child.d -p 26758
26758 malloc:entry 22
26758 malloc:entry 15
26758 malloc:entry 18
26758 malloc:entry 18
26758 malloc:entry 18
fork 27548
27548 malloc:entry 7
27548 malloc:entry 7
27548 malloc:entry 18
27548 malloc:entry 16
27548 malloc:entry 18

Clearly you can have the child script do what ever you wish.

Better solutions are welcome!

 

Activate Windows 7 Jumplists with the Left Mouse Button [Windows 7]

Reader Dan writes in with a small but interesting tip: You don’t have to right-click on the taskbar buttons to activate Windows 7's Jumplists—you can hold the left mouse button and drag upwards.

At first glance, this tip might seem like we're trying to teach you how to use the mouse, but laptop or touchscreen users might want to take a closer look—on a touchscreen all you need to do is tap and swipe your finger up to activate the jumplist, but if you have a laptop touchpad, you can mimic the same action with a double-tap and swiping your finger upward. Once you get used to it, being able to access the menu without clicking a button might just come in handy—and even if it doesn't, it's always fun to know more tricks for controlling your computer.

For more, check out how Windows 7 creates new folders with a hotkey, maximizes windows vertically with a double-click, and closes applications with a middle-click. Thanks, Dan!





Whip Up Homemade Bread without a Bread Machine [Food]

If you’d like to get hands-on and make your own bread, but need a little more guidance than a recipe, this simple bread recipe with step-by-step photos is a good place to start out.

If you’d shied away from baking your own bread because you thought it required all sorts of arcane grandmotherly magic or a pricey bread machine to create, you’ll love the simplicity of the tutorial we found on Instructables. You’ll need a handful of inexpensive ingredients from your local grocer like bread flour and yeast, a kitchen with an oven and a bread pan or two, and you’re in business.

The recipe is as simple as spending a few minutes mixing ingredients, waiting for the bread to rise, baking for a bit, and then devouring your yummy oven-fresh bread. It’s highly similar to the well-circulated no-knead bread recipe, but the helpful Instructables baker has documented each step of the process. If you’re a home-baking connoisseur with a favorite quick bread recipe, tell us how it wins the race in the comments.





Jumplist Launcher Consolidates Windows 7 Taskbar Launchers [Downloads]

Windows 7 only: Tiny utility Jumplist Launcher does application launching using Windows 7′s new Jumplists feature. It’s simple, lightweight, and doesn’t waste memory.

When you start Jumplist Launcher, you’ll be presented with a configuration dialog allowing you to create your Jumplists. You can manually use the controls to add items, but it’s probably easier to simply drag and drop shortcuts onto the panel. Once you’ve completed this process, click the Create Jumplist button, pin the application to your taskbar, and you can access the list using the right-click menu on the taskbar icon.

The great thing about this application is that it doesn't even need to be running—all of the menu items are still available, even when it's closed. There does appear to be a small bug where the top item in the list shows up as a folder icon—but it still works without issues. It's a great little tool worth a look if you want to consolidate some space on your Windows 7 taskbar.

Jumplist Launcher is a free download for Windows 7 only. For more, check out how Winfox adds jumplists to Firefox, and then read about some of the other great underhyped features in Windows 7.

Jumplist Launcher [Ali's Dünnpfiff via Addictive Tips]





Windows 7 Will Cost Less than Vista [Windows]

If you’re looking to buy a new Windows system starting today or plan to upgrade immediately, you’re in luck: Windows 7 will be a free upgrade for new Vista buyers, and upgrades are going for half-price.

Microsoft announced today the basic structures for Windows 7 pricing, and the big headline is that Windows 7 will be, at every level, the same price or cheaper than Windows Vista. Starting today, Vista Home Premium buyers (both pre-installed and retail) get a free upgrade to Windows 7 Home Premium when it lands on Oct. 22, Vista Business owners can upgrade to Windows 7 Professional, and Ultimate users get Windows 7 Ultimate.

Those with Windows XP or Vista already installed can start pre-ordering Windows 7 upgrade discs, costing $50 for Home Premium and $100 for Professional. Those deals are for a “limited time,” with no specifics given, from Microsoft directly and most computer retailers, and Ultimate may or may not see an upgrade pre-order deal.

Hit the links below for a seriously thorough and slightly compacted read, respectively, on Windows 7 pricing at every level, and tell us what you think of 7′s pricing strategy in the comments.





Test Office 2010 Intensively, Get it Free [Microsoft Office]

Microsoft is looking for volunteers to try out a pre-release copy of Office 2010—which drops as a Technical Preview next month—on a "loaner laptop," with daily home and office use, and with regular reports back and, potentially, being used in marketing or press opportunities. Do all that as part of Office 2010 Real Life Stories, and you’ll get a free full copy, unlimited technical support and training, and maybe a shot at net legend (or notoriety). Would you guinea pig your take on Office 2010 for a free copy? [via Ars Technica]





The Credit Scores You Don’t Get to See [Credit Report]

You have a right to see your credit score once a year, but that’s not the only credit knowledge lenders and sellers base their decisions on. MSN Money runs down eight “secret scores” that the credit world keeps on you.

Photo by TrinityCreditServices.

These non-FICO scores don’t factor into that seemingly all-important trio of credit bureau numbers, but they do affect how credit issuers and contracts will be negotiated. Besides looking at credit histories to determine if a borrower is likely to be late or go bankrupt, credit histories allow companies to fine-tune their marketing to you, even if you’ve been strong-willed in the past:

Attrition-risk score: Attrition risk refers to the likelihood a user will stop using a card, and attrition-risk scores are typically used in combination with other scores to determine what to do next if you look ready to bolt. If your account generates a lot of revenue and is deemed at low risk for default or bankruptcy, for example, the issuer might aggressively try to keep your business by jacking up your credit limit, lowering your rate and pelting you with convenience checks. If your account isn’t that profitable or is deemed risky, on the other hand, the issuer might just let you go.

Hit the link to see seven other “secret” scores the junk mailers and lenders of the world are looking at.





WP Like Button Plugin by Free WordPress Templates