BASE64 and JSON

I have been working on a project that requires me to make an AJAX request to a ColdFusion service that returns a BASE64 version of an image wrapped in JSON. This JSON packet is used by the client-side to populate the SRC argument of an <IMG> tag. The process was working fine most of the time. But, every once and a while the image is broken.

After doing some checking I noticed that on the client-side the BASE64 string was not the same as the server-side.  The issue was that parts of the string were being transposed. It seems that the browser(s) were thinking that parts of the string were Unicode because some images strings contained sub-strings of u+a4f7 or u+c19b.

To correct the transposing issue ended up adjusting the client-side code and the ColdFusion service. First, on the server-side I wrapped the BASE64 process in the URLEndcodedFormat()function. Second, I adjusted the client-side code to decodeURI() the string from the JSON packet.

This process resolved the issue.

How to save DOS and shell output to a file

This is an old trick that does not get much use these day. But, from time to time I need to run something in DOS or in shell (terminal) and save the output.

For example, say that I need to list a directory out and write into a Word document. I could fight with the the DOS screen copy function in Window. Or with a simple use of “>” I can save the information to a file.

dir > c:\root_directory_list.txt

This should work with just about everything that you can write to the terminal window. And, comes in handy with logging ping, traceroute, nslookups, and netstat.

Windows Registry Hack to “Edit with Notepad”

Over the last 20 years I have acquired a lot of tools to help me with things. One that I add to every machine I can is a Windows Registry hack that allows me to open/edit any file in Notepad with a simple right-mouse click.

This is useful when you want to look at a file without have to associate a program to it or use the default program to load it into. For example, say that I have an HTML file. I want to make a quick change. The default program is Internet Explorer. But, that only allows me to view the rendered HTML not edit. The “Open With >” right-mouse click menu option point to a large IDE program like Eclipse or Vim which might take several moments to load. With this registry item added I can just right-mouse click on the file and select “Edit with Notepad” and quickly make the change.

It also comes in handy when verifying the file you are looking has the correct tag extension so that it is associated to the right default program. Some times a user may use .PNG at the end of a file. But, when you use Notepad to review the header information in the file it may list it as a .MP3 file. With a simple right-click you can verify the type of file it really is.

This registry hack seems to work on must Windows Workstations and server. Simply open a new text file, Copy the code listed below and paste it into a file called edit_with_notepad.reg. Once saved just double-click on the file and it will add it to the Windows Registry. Then right-click any file to view/edit it in Notepad.

REGEDIT4

[HKEY_CLASSES_ROOT\*\Shell\Edit_with_Notepad]
@="Edit &with Notepad"

[HKEY_CLASSES_ROOT\*\Shell\Edit_with_Notepad\command]
@="notepad.exe %1"

Standard Error Codes

100 = Continue
101 = Switching Protocols
200 = OK
201 = Created
202 = Accepted
203 = Non-Authoritative Information
204 = No Content
205 = Reset Content
206 = Partial Content
300 = Multiple Choices
301 = Moved Permanently
302 = Found
303 = See Other
304 = Not Modified
305 = Use Proxy
306 = (Unused)
307 = Temporary Redirect
400 = Bad Request
401 = Unauthorized
402 = Payment Required
403 = Forbidden
404 = Not Found
405 = Method Not Allowed
406 = Not Acceptable
407 = Proxy Authentication Required
408 = Request Timeout
409 = Conflict
410 = Gone
411 = Length Required
412 = Precondition Failed
413 = Request Entity Too Large
414 = Request-URI Too Long
415 = Unsupported Media Type
416 = Requested Range Not Satisfiable
417 = Expectation Failed
500 = Internal Server Error
501 = Not Implemented
502 = Bad Gateway
503 = Service Unavailable
504 = Gateway Timeout
505 = HTTP Version Not Supported

Use jQuery to Change a Select Field to Different Value with the Text

At my job one of things I am working on allows the end-user to select a point on a map this changes the select fields on the page to be rebuilt and reflects the selected map point.

The issue that came up was that the map link uses string. While the ODATA service to popluate a select field uses an integer for the option taga value. But, the text in the option tag matches the link.

So, this code will show you how change the option tag of a select box if you only have the text value.

The Select Field

The filed thing needed is to build a select field. In this example we only need the text and not the value of the select options.


<label>Location</label>
<select id="alphabet">
  <option></option>
  <option>Alpha</option>
  <option>Beta</option>
  <option>Gamma</option>
  <option>Delta</option>
</select>

Javascript Function

The function below used jQuery’s $.each() to loop over all the option tag values for the select field and find the exact match. Once found we change the field option the one we are looking for and then use return false;to break out of the loop.


function changeLetter( L ) {
  $( "#alphabet option" ).each(
    function () {
      if ( L === $( this ).val() ) {
        $( "#alphabet" ).val( L ).change(); 
          return false;
        }
      }
    );
  }

Full Sample


<html>
  <head>
    https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js
	
      $( document ).ready(
        function() {
          $( "button" ).on(
            {
              "click" : function () {
                changeLetter( "Gamma" );
              }
            }
          );
        }
      );

      function changeLetter( L ) {
        $( "#alphabet option" ).each(
          function () {
            if ( L === $( this ).val() ) {
              $( "#alphabet" ).val( L ).change();

              return false;
            }
          }
        );
      }
    
  </head>
  <body>
    <label> Location </label>
    <select id="alphabet">
      <option></option>
      <option>Alpha</option>
      <option>Beta</option>
      <option>Gamma</option>
      <option>Delta</option>
    </select>

    <button id="changeToGamama">Change Select Option to Gamma</button>
  </body>
</html>

htop

I was looking for a tool that would allow me to SSH into a server and see what services are running and the performance output. Top does provide good general stats on memory usage and what is running on a Linux server. But, I wanted some real-time visualization on CPU usage. So, I found htop.

htop gives me a way to actively see CPU, RAM, and swap memory in a visual context. Other features allow me to tree out services and programs that are running. Function keys allow me to toggle layout and to quickly exit the program. I can even scroll the complete list of running items.

Installation notes:

sudo apt-get install htop

For more information on htop see https://en.wikipedia.org/wiki/Htop

JSON data wrapping

While working with a development team on a RESTful solution I start proposing wrapping the service response/output in another object. This would allow us to write some META data about the response.

This META data would help developers with understanding what was going on with their request and the response provided by the service. A kinda talk back method to AJAX or REST responses.

A lot of people would say why would you need this? Well maybe you have a service that is open to the public like Twitter. You want developers to be able to access your service and understand your data without them calling or emailing you all the time. Maybe your information is labelled or structured differently than theirs. The META data provided in the wrapper would allow them to determine how to interpret the information to suit their needs.

Wrapper structure sample:


{
  "statusCode" : 1000,
  "requestID" : "63D62A09-AA1F-88CF-E890EDBF000F4F8E",
  "data" = {
    "message" : "Success", 
    "totalRows" : 1, 
    "columns" : {}, 
	"results" : []
  },
  "eventName" : "",
  "requestParams" : {}
}

Elements/Attributes of the wrapper

Path Notes
statusCode This status code is used to denote what is going on with the service or method being accessed.It is different from that of the Header status or AJAX request status.

These values can be set to reflect your status indicators.

requestID The requestID is optional and has many possible uses.First, it can be used to let developers know that the response is not cached.

Second, if you are keeping a log of requests for security, debugging, or user statistics this value will come in handy. Developers could submit a bug with the JSON packet that they received. This could help you debug possible issues with the data they supplied the service.

data This is where we would store data that the developer might want to display to end-users.
data.message The message field allows the service to send text or human messages back to end-user or developer. This message can be related to the numeric status indicator or independent.For example, say that the developer was making a request to log in. The statusCode could be 5000 letting the developer know that the method is working correctly. But, the was an error. The message element would hold the server response Password is not correct.

These messages can be handing in notifying the user of bad/missing parameters or with debugging of where the service broke.

data.totalRows This is an optional element. It is here to help the developer display the number of records being returned.
data.colmuns This is a optional element. I sometimes use it to display the column names of the query and denote if the column is a string, integer, boolean, array, UUID, GUID, or date.This helps the developer know you are returning 1 or 0 for a boolean response. And not for a number count.
data.results This is where you would normally store all the data that would be displayed to the end user.
eventName This element is used to help the developer verify that the are accessing the right method.

I normally user the path to the service. /com/members/readMembers/

requestParams This array would list all of the parameters that were sent as part of the request. This helps the developer debug responses.

Full structure sample


{
  "statusCode" : 1000,
  "requestID" : "63D62A09-AA1F-88CF-E890EDBF000F4F8E",
  "data" = {
    "message" : "Success", 
    "totalRows" : 3, 
    "columns" : {
      "productID" : "UUID", 
      "title" : "string", 
      "price" : "integer", 
      "availableUnits" : "integer"
    }, 
    "results" : [
      {
        "productID" : "502AD47D-05C6-4A47-9DD11458B8211EEB", 
        "title" : "Dell Inspiron 15 15.6\" Laptop Computer - Black", 
        "price" : 229.99, 
        "availableUnits" : 24
      },
      {
        "productID" : "93E84FE4-5367-4DD3-87F15C6A862ADA11", 
        "title" : "AOC e2252Swdn 22\" LED Monitor", 
        "price" : 99.99, 
        "availableUnits" : 102
      },
      {
        "productID" : "605C7476-7673-4C62-9E506D4331E03AAE", 
        "title" : "Apple iPad mini 16GB Wi-Fi Space Gray", 
        "price" : 259.99,
        "availableUnits" : 0
      },
    ]
  },
  "eventName" : "/com/products/resaleProducts/",
  "requestParams" : {
    "isSaleItem" : 1
  }
}

Uninstalling VMware Player

I need to uninstall VMware Player to from my Ubuntu 13.04 Desktop. I was having problems after upgrading from Ubuntu 12.10. Seems the Kernel and C libraries are a little different. Therefore my copy of Player would not load.

I search several discussion boards and learned that if I uninstall the program and re-installed the program it might work again.

To uninstall the program open a terminal window and type the following.

sudo vmware-installer --uninstall-product vmware-player

You should not need to reboot when finished.

VMware and Kernel updates

This week I made my laptop dual boot Windows 7 and Ubuntu 12.11 workstation. This morning I updated the Kernel to 3.5.0-26. After restart I tried running VMWare Player and it failed.

Seems that kernel update did not download update or install the latest lunix-headers that VMWare were missing for the new kernel. I located to command lines to download the the linux-headers.

First I ran the following command to see what version of the kernel I had installed.

uname -r

Next I downloaded the linux-headers for that kernel.

sudo apt-get install linux-headers-3.5.0-26-generic

This downloaded the linix-headers for 3.5.0-26 and 3.5.0-26-generic. The files that I needed were added to the /usr/src/ folder.

I then tried to run VMWare Player again. It asked me here the header files were for the kernel were. The application allowed me to browse to the folder /usr/src/linux-headers-3.5.0-26-generic/ and select it. Then VMWare Player used those linux-header files to compile to the code it needed.

Once completed I was able to start and run VMWare Player.