Getting WordPress URL migrations to work when all else fails!

Recently, I modified the permalinks for my blog posts from: http://nizarnoorani.com/index.php/archives/%postid% to just be: http://nizarnoorani.com/%postname%

This new permalink structure will now apply to any new posts that I create. Which of course begs the question:

Will the links to all my existing blog posts break??

And the answer sadly and obviously is: Yes, they will!

Can we fix this unfortunate issue? Sure, we can! And there are quite a few WordPress plugins that do exactly this. A search for “WordPress URL migration plugins” will serve up links to many such plugins. One that I particularly liked and recommend is Advanced Permalinks.

If installing/activating/configuring one of these plugins fixes your problem – great! Things for me, however, weren’t quite so easy.

For some reason, which I still haven’t been able to figure out, none of the migration plugins worked for me! Maybe its because my blog was originally hosted under Windows and then I later moved it to Linux. Or maybe I wasn’t configuring the plugins correctly. Or maybe something else. I don’t know.

Anyways, IF you are in the same boat then here is one hacky solution to get your existing permalinks working again. Once again – Only do this IF you can’t get the WP migration plugins to work!

Okay, here goes:

  1. Log in to your WordPress Dashboard: http://yourwebsite.com/wp-login
  2. Set up your new permalink structure by navigating to Settings -> Permalinks. After you set up your new permalink structure, you’ll notice that your existing permalinks will now be re-directed to a 404 Not Found page. Browse to one of your existing permalinks to verify that this is the the case.
  3. Okay, time to put in our little hack to get the existing permalinks working again. Open up the WordPress 404 template page inside the WordPress editor by navigating to Appearance -> Editor and clicking on the 404 Template link on the right-hand side bar.
  4. Insert the following code snippet just below the get_header() line:
    <script type='text/javascript'>
     
    <?php 
     
         // extract the post_id from the URL. In my case, my existing permalink was of the 
         // structure http://nizarnoorani.com/archives/%postid%.
         // modify the extraction code below for our particular structure as needed.
         $postId = (int)trim($_SERVER['REQUEST_URI'], '/archives/');
     
         $post = get_post($postId);
     
          if($post != null) {
             // again, modify the URL as needed to match your new permalink structure.
             echo "window.location = 'http://nizarnoorani.com/".$post->post_name."';"; 
         }  
    ?>
     
    </script>

    Note: Be sure to modify the code snippet to match your specific new and old permalink structures!

  5. Save your changes. Your existing permalinks should start working again!

Basically, what we’ve done here is added some logic to extract the post_id from the old link, retrieve the post with that post_id from the database, construct the new URL and then re-direct the user to the new URL.

Cheers!

Twitter Email Linkedin Digg Stumbleupon Subscribe

Unobtrusive JavaScript with HTML 5

HTML 5 supports a new feature known as Custom Data Attributes. These attributes give us the ability to define custom attributes for ANY HTML tags. The only restriction is that the tag must start with “data-”. For instance, we can add a custom attribute to a link as follows:

  <a href="#" data-search-by-type="<value>">My link with custom attribute</a>

This feature comes with a neat benefit that we no longer need ANY inline javascript inside our HTML content. For instance, say, we’ve got a commonly-used javascript function that performs a search by searchType:

function search(var searchType)
{
   ...
   ...
}

Prior to HTML 5, we would invoke the function using inline javascript inside our HTML tags:

<a href="javascript:search('byName')" class='search-link'>Search By Name</a>  
<a href="javascript:search('byType')" class='search-link'>Search By Type</a>

With the introduction of Custom Data Attributes, we can now completely do away with the in-line javascript and write the links as follows:

<a href="#" data-search-by='byName' class='search-link'>Search By Name</a>
<a href="#" data-search-by='byType' class='search-link'>Search By Type</a>

We would then add the following to our common.js file that contains the search() function:

$(document).ready(function() {
  $(".search-link").click(function () { search(this.getAttribute("data-search-by")); })
})

The Custom Data Attributes in HTML 5 gives us a benefit that is similar in nature to the benefits provided by the CSS model – namely, separations of concerns. CSS enables us to separate content from the presentation of that content, thus enabling our HTML pages to follow a well-defined structure.

Similarly, with Custom Data Attributes we can now separate logic or functionality from HTML content. This provides with the following benefits:

  1. We no longer need to pollute our HTML with in-line Javascript.
  2. Keeping all our Javascript functionality centralized makes it much easier to manage.
  3. The use of Custom Data Attributes increases code re-usability since they can effectively serve as parameters to our javascript functions.
Twitter Email Linkedin Digg Stumbleupon Subscribe

JQuery snippet to detect keystrokes on the numeric key-pad.

The below JQuery snippet returns the character corresponding to the key that was pressed on the QWERTY keyboard or the numeric key-pad. For instance, pressing the ’1′ key will return the text ’1′. Similarly, pressing the ‘+’ key will return back the text ‘+’.

$(document).keydown(function (event) {
      toCharacter(event.keyCode);
 });
 
function toCharacter(keyCode) {
 
    // delta to convert num-pad key codes to QWERTY codes.
    var numPadToKeyPadDelta = 48;
 
    // if a numeric key on the num pad was pressed.
    if (keyCode >= 96 && keyCode <= 105) {
        keyCode = keyCode - numPadToKeyPadDelta;
        return String.fromCharCode(keyCode);
    }
 
    if (keyCode == 106)
        return "*";
 
    if (keyCode == 107)
        return "+";
 
    if (keyCode == 109)
        return "-";
 
    if (keyCode == 110)
        return ".";
 
    if (keyCode == 111)
        return "/";
 
    // the 'Enter' key was pressed
    if (keyCode == 13)
        return "=";  //TODO: you should change this to interpret the 'Enter' key as needed by your app.
 
    return String.fromCharCode(keyCode);
}

A little explanation is probably in order…

Javascript provides the

String.fromCharCode()

method that converts an ASCII character code into it’s equivalent text value. For instance,

String.fromCharCode(65)

returns the character ‘A’. The method works great until to try to use it for keys that live on the numeric keypad.

The ASCII code for the ’1′ key on the numeric key pad is 97. If you look this up on the ASCII Table, you will find that the ASCII code 97 corresponds to the character ‘a’ and not the character ’1′ denoted on the numeric key pad! The reason for this, as far I can tell, is that the numeric keys simply overload on the existing the ASCII codes.

A little calculation will reveal that subtracting 48 from the ASCII code of the numeric keys will give us the “correct” ASCII code. For instance, subtracting 97 (which is the ASCII code for the ’1′ key on the numeric keypad) from 48 gives us 49. Look up the ASCII code 49 on the ASCII Table and you will find that it maps to the character ’1′!

For the keys that correspond to the various symbols such as ‘+’, ‘-’, etc., I am simply returning back the corresponding character. No mystery there.

Hope this helps!

Twitter Email Linkedin Digg Stumbleupon Subscribe

A case for C#’s dynamic keyword

Many developers feel, myself included, that C#’s ‘dynamic’ keyword is…well, a little too dynamic. But, recently, I faced a challenging problem which I was only able to solve through the use of the ‘dynamic’ keyword! Here goes…

In short, I had to write a method that adds a WCF behavior to a VS-generated WCF proxy class. What I wanted to do is something like the following:

public void AddCommonWcfBehavior(ICommunicationObject wcfClientProxy)
{
    ClientBase wcfClientBase = wcfClientProxy as ClientBase;
    wcfClientBase.Endpoint.Behaviors.Add(new MyCommonWcfBehavior());
}
/* Note that the method is taking in an object to type 
    'System.ServiceModel.ICommunicationObject' which is the base-level 
    interface for all WCF client proxies.
*/

However, I couldn’t do this for the simple reason that ClientBase<> is a generic class and .NET does not provide a non-generic version. Go figure! And no, for reasons that are too detailed to list here, I could not make AddCommonWcfBehavior() a generic method. I wish .NET offered a non-generic ClientBase class. But it doesn’t and thus I was stuck!

It was then that I remembered reading about the dynamic keyword not too long ago. Using the dynamic keyword, the method looks like the following (and works as expected):

public void AddCommonWcfBehavior(ICommunicationObject wcfClientProxy)
{
    dynamic wcfClientBase = wcfClientProxy;
    wcfClientBase.Endpoint.Behaviors.Add(new MyCommonWcfBehavior());
}

So the moral of the story: Keep the dynamic keyword in mind! In some cases, it may be your one and only savior!

Twitter Email Linkedin Digg Stumbleupon Subscribe

WordPress on a GoDaddy hosted site – 500 internal server error!

  • Is your blog site returning the infamous “500 – internal server error” more often than not?
  • Are you using WordPress as your blog publishing platform?
  • Are you using GoDaddy as your website hosting provider?
  • Are you using IIS as your web server (as opposed to Linux)?

If yes, continue reading to fix this issue:

There is weird configuration issue with running WordPress with a IIS web server on GoDaddy. Taking the following actions will resolve this issue:

  1. Upgrade WordPress to the latest version. Detailed instructions at: Upgrading WordPress
  2. Install WP-Super-Cache plugin. Here is the download link for it. In order to enable the plugin, you have to do a little tweaking. Below are the steps you need to follow:

    • First off, extract the ‘wp-super-cache’ folder into your ‘wp-content/plugins’ directory.
    • Log in to your GoDaddy account and navigate to Hosting -> Manage Account.
    • Click on the Content tab and select File Manager.
    • Here you will see all your files and folders. Check the wp-content folder and click the Permissions icon on the top. Uncheck Inherit and check the Read and Write checkboxes. Don’t worry this is only temporary to get your plugin working correctly. Save your changes.
    • Now Enable the plugin by going to your WordPress Plugins page.
    • Next you will have to enable caching. For this, go back to your File Manager and browse to the “wp-content/cache” folder. Change the permissions on this folder to Read/Write as well.
    • Now open up the wp-config.php page that’s in the root directory and add the following line towards the end: define(‘WP_CACHE’, true)
    • Go back to the Settings page for the wp-super-cache plugin and set the status to ON. Make sure to save your settings. You may see a warning about apache mod_rewrite not enable or installed. Don’t worry about this warning. This just means that your caching will only be HALF-ON which is fine because even it being HALF-ON will fix our ’500 – internal error’ issue.
    • Go back to the File Manager and change the permissions on the wp-content folder to Inherit.
    • Your website should now respond faster and stop generating the 500 – internal server error issue.
  3. As an additional security measure, I would also recommend installing the WP-SpamFree plugin. This is a very effective plugin that will eliminate virtually all SPAM comments. Thus decreasing the load on your website.

If that still doesn’t fix the “500 internal server error” issue, then try updating your current WordPress theme or switch to a different WordPress theme. If that doesn’t work either, then it’s time to bite the bullet and switch to Linux! :)

Twitter Email Linkedin Digg Stumbleupon Subscribe

What the heck was I working on??

Does it ever happen to you that you go to work in the morning, look at the screen and then ask yourself : What the heck was I working on?? Happens to me all the time. Maybe I was in the middle of debugging some code the previous day, or writing a unit-test or finishing up the implementation of a class or going through existing code to understand what it’s doing or something else. Given the detailed nature of software development, it’s sometimes hard to remember where you left off and from where you need to pick things up again.

Below is an approach that’s worked quite well for me:

Tells me where I left off

Tells me where I left off





I write myself a little MS Outlook note and put right in the middle of the screen. Simple, but very effective!

Twitter Email Linkedin Digg Stumbleupon Subscribe