Category Archives: CodeProject

Connecting the dots with jQuery, JSONP, and WebAPI

No problem!

This morning, I jumped in to help out my friend Julie Lerman with a question about using jQuery with ASP.NET WebAPI.  In my mind, that’s easy… something I’ve wired up lots of times and shouldn’t be a problem. I offered to pair program for a bit and take a look at the code, after all… how hard could it be?

This was an interesting and simple block of jQuery that was expecting JSON from a service.  A simple WebAPI controller, similar to the one we were attempting to query looked a little like this:

  public class ValuesController : ApiController
  {
    // GET api/values
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }
  }

That’s easy to get data from with jQuery, I can use an AJAX call to get the data from my server with JavaScript like the following:

$.ajax({
  url: "http://localhost:64948/api/values",
  type: 'GET',
  dataType: 'json'
}).done(function(data) { alert(data.length); });

When I run this page from the same server that is hosting my service, no problem.  I get a simple alert box with the number 2.

That wasn’t our problem.

In this scenario, Julie was querying a different server that was hosting WebAPI and needed the services of JSONP to make that cross-origin request.  The jQuery documentation indicates that you can simply switch the dataType of your AJAX call to “JSONP” and everything will just work.

No...

No dice… nothing.  We poked and prodded that JavaScript code and got nothing from it.  Then it hit us:  the problem isn’t the JavaScript, its the callback coming from the server.  WebAPI needs to know how to issue a command back to our script.

To complete the task and get WebAPI responding properly to a JSONP request, install the JSONP MediaTypeFormatter from NuGet.  Once that is installed, enter your App_StartWebApiConfig.cs and add to the bottom of the Register method the following line:

GlobalConfiguration.Configuration.AddJsonpFormatter();

Rebuild and re-run the JavaScript and now the done method of the AJAX call is being executed.

We were happy, and all was right in the world.  

What did we learn about this problem and how to write better software?

The short answer is: JavaScript development is REALLY HARD without proper error messages and with connections that fail silently.  There was no indication that the WebAPI was not attempting to call the Done callback method from jQuery.  Additionally, WebAPI wasn’t throwing any warning message to indicate that there were arguments passed in that it didn’t know what to do with.  This lack of verbose messaging in a debugging environment made it difficult for two experts to be able to track down a problem.

How would an average developer handle this?  We can do better…  I’ll write more about this approach to making debuggable (yea, I just invented that word…) software tools next time and how we can improve this experience.

 

MultiTasking is a Myth

Yesterday, I took my family to the Franklin Institute in Philadelphia (we have a membership there) and visited their new permanent exhibit on the brain.  While going through, I found this display and it really hit home for me:

I have always had a problem with multitasking.  Its not something that I can do well, as I prefer to focus on one thing at a time, giving it my undivided attention.  Once I’ve completed that task, I move on to the next task.  As someone who works from home, I’ve found several benefits from this approach, and I’ve also found several pitfalls.

Successful Techniques

1. Make a list and stick to it

I’ve made task lists all sorts of ways in the past.  I’ve used a paper notepad, notepad.exe, Outlook Tasks, OneNote, and Trello.  They all are used for the same thing: allow me to forget future tasks and only focus on the current item.

This is one of the concepts behind Kanban and Scrum.  You can only take one task card at a time to be worked on.  Once the task card is finished, it gets placed into another queue for review and validation by other team members.  Trello is an excellent free tool for this, but has its drawbacks, as do all online task managers.

The biggest problem I have with the online task list manager is what I can the “in your face” problem.  I need to open the application or navigate to the website in order for me to face my task list of the day.  It is all to easy for me to say, “lemme open Facebook first” or “hey what’s going on at LinkedIn” before I face my list of tasks for my work session.

However, by keeping a paper list of tasks and leaving them on my desk chair, or on my keyboard.  Now, I need to look at my to-do list before I begin working on anything.  It may seem simple, but it keeps someone like me who can get distracted very easily on task right from the get go.

2. My Office is My Work Space

This sounds like a simple idea, but let me describe for you my mindset.  I have a room in my home dedicated as my home office.  When I am in that room, I am in there for one purpose only: to accomplish ‘work tasks’.  After a bit of practice of this habit, I now get in the “working mood” just when I walk into the room.  My mind knows that good stuff will be accomplished once I sit down.

This also has the side-benefit of ‘training my family’ that when Daddy is in his office, he’s working and we should leave him alone.  Not that I want to be an office hermit, but this bit of training can grant me several hours at a time of uninterrupted work.  In a home with two young daughters, this can be a welcome retreat.

3. Get in “The Zone”

If you’ve ever been there, you know what I’m talking about.  “The Zone” or “Flow” as psychologists call it can be intoxicating.  This is when your mind is fully immersed in a task and everything around you just falls away as unimportant.  You’ll exit the zone and find out that five to ten hours have gone by and you haven’t eaten or been to the restroom in that time.

In the film The Social Network, they refer to this phenomena again and again as being “wired in”.  The coders in the movie are oblivious to what’s going on around them and solely focused on their code:

This is, how programers should be working

For me, when I am analyzing some source code to better understand it, I start to enter this mindset.  I’ll move further into it as I begin to write code and see the fruits of my progress.  When I need to wait for a compilation or other process to complete, I’ll grab a Rubik’s cube and solve it while sitting at my desk.  I can usually complete a cube in less than two or three minutes, and this has been an effective tool to keep my mind active.

Another trick I use to keep my mind going involves poker chips.  Yes, I enjoy an occasional game of hold ’em, but in this case I’m not playing poker, just shuffling the chips.  What I do is take a stack of 10 chips, typically of two different colors, and break them into two equal stacks of the same color.  I then merge the two stacks, inserting a white chip between two blue chips.  This should result in the stack perfectly merged, with white chips alternating between blue chips.  I’ll repeat this separate and merge process until I get the chips back in a state where the two sets of colored chips are completely isolated from each other, like in the pic above.

Former co-workers will tell you, when they hear the sound of the shuffling poker chips, they know I am deep in thought and stuff is getting accomplished.

Carl and Richard on .NET Rocks had a great episode this week talking to Mark Seeman about getting in the zone.  They have some great tips there, and its worth a listen.

Problem Areas

These are 3 great ideas to help me get in the zone, get focused and get going at a high speed.  Unfortunately, the following problems arise that prevent my productivity.

1. The list runs empty

When I run out of tasks on my list, I end up wandering aimlessly.  This can be a good thing, but typically its a bad thing.  It is a good thing when I can take time to relax, grab a frosty adult beverage from my friends at Redds Apple, and take it easy.  However, my mind is constantly racing at new ideas, and even when I’m not actively working on something, I like to write down ideas in OneNote on my phone.

2. Interruptions – Arrgh!

This is the killer one for me, and where that passage I read at the Franklin Institute grabbed me.  Interruptions murder my productivity.  This can be anything from a text message, a new tweet that mentions me, or some great post from a friend on Facebook.  Kids wandering in to my office complaining about what their mother has chosen for dinner and buggy software that I’m using that prevents me from working productively are more time sinks that I try to avoid.

Like the sign at the beginning of this piece said, you can’t truly multi-task.  The best you can hope for is context switching, and synchronizing your current mindset to paper or some other medium that you can use to pick up and return to your previous state quickly.  Coworkers and family members have gotten very frustrated at me when they have attempted to engage me while I am ‘in the zone’ and I need to take that minute to “save my progress” so that I can resume after I’ve addressed their questions.

I’ve also learned to shut those things out, to silence my phone and to use a pair of gaming headphones with decent noise cancelling capabilities to limit the amount of ambient (read: distracting) noise that enters my head.  Combine that with some mellow music (my current preferred tunes are from Lindsey Stirling) and I can stay very focused for hours on end.

3. Outside of my space

When I’m out of my space and can’t get comfortable, it is very hard for me to get in the zone.  Sitting at the airport, in a coffee shop, in an office with lots of traffic going by my desk… these are all places that I have found very difficult to enter the zone.  However, I have found tremendous value in the desk in a quiet hotel room.

I’ll pull the drapes shut, turn the lights down, so that the only light is coming from my laptop.  With a nice venti caramel macchiato by my side, I can code anything!  Its a strange experience, being away from home and feeling like I’m back in my comfortable office, but it works.

Summary

This is just a collection of tip about what works for me.  Productivity and getting in the zone are difficult things to manage, and I like to manage them as best as possible through these simple environment management techniques.  What works for you?  Share your tips in the space below.

That Annoying ASP.NET Issue with Postback

Stop me if you’ve heard this before:

I’m working through an ASP.NET project and suddenly Postback stops working.  I know!  This is the simplest of interactions with an ASP.NET web forms application, and its not WORKING!!  What the heck is wrong with this stupid website?  I mean, I didn’t change anything.. I just want my default.aspx form to be able to have a button click button handler.  Is that so DIFFICULT?  Get your act together FRITZ!1!!

I did some digging and digging on this one.  Did I bring in an add-in or library to my project that was preventing the postback from capturing the click event?  I broke out Fiddler and analyzed the traffic, to ensure that the form content was indeed being submitted properly back to the server.  Everything looked good there.

My next analysis step was to take a look at the Request.Form collection.  I should see the __EVENTARGUMENT being populated.  When I opened the Immediate Window and inspected Request.Form, this is what I found:

How is the Request.Form collection empty?  What’s the deal with THAT?

I started thinking about the ASP.NET pipeline, and it hit me:  FriendlyUrls.

There’s this interesting thing that happens when web forms attempt to post back to pages managed by FriendlyUrls and lack a filename.  This could be any of the following pages in your site:

  • /
  • /Products/
  • /Orders/

You get the idea.  These pages for some reason don’t handle postback properly.  With that in mind, I set forth to drop a quick and dirty change to enable this throughout the website.  Fortunately, I can make that change through a URL Rewrite operation.  I added the following event handler to my global.asax.cs file:

    void Application_BeginRequest(object sender, EventArgs e)
    {
      var app = (HttpApplication)sender;
      if (app.Context.Request.Url.LocalPath.EndsWith("/"))
      {
        app.Context.RewritePath(
                 string.Concat(app.Context.Request.Url.LocalPath, "default"));
      }
    }

With that, my pages started posting back properly… all was right in the world.

Please note:  you will have this problem with the default ASP.NET project with web forms when FriendlyUrls are enabled.

How to automatically schedule posts to Twitter, LinkedIn, and Facebook

Over the past few months, I’ve been publishing a LOT of content on this blog, my Telerik blog, and on Twitter.  To simplify the publicity of these blog posts, I have configured a small handful of services to automatically detect new content and broadcast it appropriately.  What follows is a brief run-down of how I have configured this Rube-Goldbergian publicity machine.

It all starts with IFTTT

The main cog in this whole machine is a wonderful web application called IFTTT.  Don’t be intimidated by the acronym, it stands for If This Then That.  This is a web application that listens for events from services that you use and triggers actions on other services that you use.  The beauty of this whole thing is that the application is completely connected with OAuth tokens.  My password never enters any of their screens.

IFTTT runs with a concept called recipes.  These are the mini-programs that you will write to connect a trigger service with an action service.  The almost 50 trigger services vary from the date, to foursquare checkins, and even ESPN sports score reports.  The 60 action services are all kinds of notifications and publications like Twitter, SMS, and even a voice phone call.

Among the collection of trigger services are RSS feeds.  This blog, along with my other blogs, all expose an RSS feed that IFTTT can consume.  From there, I trigger a free service called Buffer.

Scheduling Tweets with Buffer

Buffer is a free web service that will publish messages to Twitter, LinkedIn, Facebook, and App.Net  With this service, you add links and messages to your Buffer message queue and at scheduled times the application writes one message at a time to the target service.  The first messages added to the queue are written first, but the Buffer dashboard gives you an easy drag-n-drop interface to change the order of publication.

Once again, all authentication is done with OAuth, so I am not publishing passwords to this service either.  I also have a plugin installed in Chrome (my current browser of choice) that enabled me to add links and retweets to my buffer without navigating to Buffer.  Very handy.

Buffer has a free plan that will schedule posts to a single account on each of your connected services.  On the free plan, you can only configure one schedule for messages to be posted.  If you need more accounts or more schedule options, there is a paid subscription option that will manage more activity.

When Should I Post Those Tweets?

Finally, to ensure that I have the correct times to schedule these messages, I use another service called Tweriod.  Tweriod has a free service that will analyze your tweets and interactions on Twitter and report a schedule of the best times to post tweets.  This analysis can take some time, and operates asynchronously from your web interaction.  Once you request a report, you should get a notification emailed to you in just a few minutes with your results.

Tweriod can be connected directly to Buffer, so that the scheduled times in Buffer can be automatically configured.  Be sure to set your timezone properly in Tweriod so that you get a report with times that make sense to you.

Putting it all together

The connection of these items is a snap.  With the Tweriod schedule configured in Buffer, I simply created a series of recipes on IFTTT with a Feed trigger that sends a message to Buffer.

Give IFTTT, Buffer, and Tweriod a try and let me know in the comments below if you figure out a better way to manage your publications or other cool IFTTT recipes that you’ve put together.

Yes, you can use GitHub for Windows with BitBucket

I’m a big fan of both GitHub and BitBucket as online version control applications.  I’ve been using git as a source control mechanism since 2010, and these online services since that time as well. Full Disclosure: I’ve been a paying customer of GitHub in the past, discontinuing when I was completed with the project I needed their full services for.  

I have always been very familiar with the command-line and using it to interact with the git source control seemed natural to me. To assist with those less comfortable with the command-line, a front-end for Windows-based developers was released by GitHub called “GitHub for Windows”  In this application, the entire interaction with the source code repository is streamlined and made simple for the user.  The user-interface is configured to make storage of your content with GitHub a “no-brainer”.  But it leads people to question:  “Can I use GitHub for Windows with BitBucket?”

Yes… yes you can.  In the rest of this article, I will show you how to configure this client app to interact with a BitBucket repository.

From the main screen of GitHub for
Windows, click “+ add”

In the resultant “new
repository” window, key in whatever you’d like to name the repository and be
sure to NOT mark the “Push to github” checkbox.  Click ‘Create’ at the
bottom to create the local repository:

Next, in the repository list
window, click the “right arrow” next to the name of the repository you just
created to open that repository:

Click the “tools” gear at the
top of the repository details screen, and select the ‘settings…’ menu item.

In the ‘primary remote (origin)’
textbox, enter the text of the SSH link for the repository on BitBucket. 
You should see this on the right side of the screen on BitBucket:

You’ll need to enter the
command-line to finish this…  from the repository details window, click
“tools” and then “open a shell here”.  This should open either Git Bash or
Windows Powershell configured for git.  Once that is open simply run:

git pull origin master

.. and you’re all synced up