Posts Tagged 'Tips And Tricks 2'

January 10, 2013

Web Development - JavaScript Packaging

If you think of JavaScript as the ugly duckling of programming languages, think again! It got a bad rap in the earlier days of the web because developers knew enough just to get by but didn't really respect it like they did Java, PHP or .Net. Like other well-known and heavily used languages, JavaScript contains various data types (String, Boolean, Number, etc.), objects and functions, and it is even capable of inheritance. Unfortunately, that functionality is often overlooked, and many developers seem to implement it as an afterthought: "Oh, we need to add some neat jQuery effects over there? I'll just throw some inline JavaScript here." That kind of implementation perpetuates a stereotype that JavaScript code is unorganized and difficult to maintain, but it doesn't have to be! I'm going to show you how easy it is to maintain and organize your code base by packaging your JavaScript classes into a single file to be included with your website.

There are a few things to cover before we jump into code:

  1. JavaScript Framework - Mootools is my framework of choice, but you can use whatever JavaScript framework you'd like.
  2. Classes - Because I see JavaScript as another programming language that I respect (and is capable of object-oriented-like design), I write classes for EVERYTHING. Don't think of your JavaScript code as something you use once and throw away. Write your code to be generic enough to be reused wherever it's placed. Object-oriented design is great for this! Mootools makes object-oriented design easy to do, so this point reinforces the point above.
  3. Class Files - Just like you'd organize your PHP to contain one class per file, I do the exact same thing with JavaScript. Note: Each of the class files in the example below uses the class name appended with .js.
  4. Namespacing - I will be organizing my classes in a way that will only add a single property — PT — to the global namespace. I won't get into the details of namespacing in this blog because I'm sure you're already thinking, "The code! The code! Get on with it!" You can namespace whatever is right for your situation.

For this example, our classes will be food-themed because ... well ... I enjoy food. Let's get started by creating our base object:

/*
---
name: PT
description: The base class for all the custom classes
authors: [Philip Thompson]
provides: [PT]
...
*/
var PT = {};

We now have an empty object from which we'll build all of our classes. We'll go I will go into more details later about the comment section, but let's build our first class: PT.Ham.

/*
---
name: PT.Ham
description: The ham class
authors: [Philip Thompson]
requires: [/PT]
provides: [PT.Ham]
...
*/
 
(function() {
    PT.Ham = new Class({
        // Custom code here...
    });
}());

As I mentioned in point three (above), PT.Ham should be saved in the file named PT.Ham.js. When we create second class, PT.Pineapple, we'll store it in PT.Pineapple.js:

/*
---
name: PT.Pineapple
description: The pineapple class
authors: [Philip Thompson]
requires: [/PT]
provides: [PT.Pineapple]
...
*/
 
(function() {
    PT.Pineapple = new Class({
        // Custom code here...
    });
}());

Our final class for this example will be PT.Pizza (I'll let you guess the name of the file where PT.Pizza lives). Our PT.Pizza class will require that PT, PT.Ham and PT.Pineapple be present.

/*
---
name: PT.Pizza
description: The pizza class
authors: [Philip Thompson]
requires: [/PT, /PT.Ham, /PT.Pineapple]
provides: [PT.Pizza]
...
*/
 
(function() {
    PT.Pizza = new Class({
        // Custom code here that uses PT.Ham and PT.Pineapple...
    });
}());

Before we go any further, let's check out the comments we include above each of the classes. The comments are formatted for YAML — YAML Ain't Markup Language (you gotta love recursive acronyms). These comments allow our parser to determine how our classes are related, and they help resolve dependencies. YAML's pretty easy to learn and you only need to know a few basic features to use it. The YAML comments in this example are essential for our JavaScript package-manager — Packager. I won't go into all the details about Packager, but simply mention a few commands that we'll need to build our single JavaScript file.

In addition to the YAML comments in each of the class files, we also need to create a YAML file that will organize our code. This file — package.yml for this example — is used to load our separate JavaScript classes:

name: "PT"
description: "Provides our fancy PT classes"
authors: "[Philip Thompson]"
version: "1.0.0"
sources:
    - js/PT.js
    - js/PT.Ham.js
    - js/PT.Pineapple.js
    - js/PT.Pizza.js

package.yml shows that all of our PT* files are located in the js directory, one directory up from the package.yml file. Some of the properties in the YAML file are optional, and you can add much more detail if you'd like, but this will get the job done for our purposes.

Now we're ready to turn back to Packager to build our packaged file. Packager includes an option to use PHP, but we're just going to do it command-line. First, we need to register the new package (package.yml) we created for PT. If our JavaScript files are located in /path/to/web/directory/js, the package.yml file is in /path/to/web/directory:

./packager register /path/to/web/directory

This finds our package.yml file and registers our PT package. Now that we have our package registered, we can build it:

./packager build * > /path/to/web/directory/js/PT.all.js

The Packager sees that our PT package is registered, so it looks at each of the individual class files to build a single large file. In the comments of each of the class files, it determines if there are dependencies and warns you if any are not found.

It might seem like a lot of work when it's written out like this, but I can assure you that when you go through the process, it takes no time at all. The huge benefit of packaging our JavaScript is evident as soon as you start incorporating those JavaScript classes into your website ... Because we have built all of our class files into a single file, we don't need to include each of the individual JavaScript files into our website (much less include the inline JavaScript declarations that make you cringe). To streamline your implementation even further if you're using your JavaScript package in a production deployment, I recommend that you "minify" your code as well.

See ... Organized code is no longer just for server-side only languages. Treat your JavaScript kindly, and it will be your friend!

Happy coding!

-Philip

October 17, 2012

Tips and Tricks - jQuery Select2 Plugin

Web developers have the unique challenge of marrying coding logic and visual presentation to create an amazing user experience. Trying to find a balance between those two is pretty difficult, and it's easy to follow one or the other down the rabbit hole. What's a web developer to do?

I've always tried to go the "work smarter, not harder" route, and when it comes to balancing functionality and aesthetics, that usually means that I look around for plugins and open source projects that meet my needs. In the process of sprucing up an form, I came across jQuery Select2, and it quickly became one of my favorite plugins for form formatting. With minimal scripting and little modification, you get some pretty phenomenal results.

We've all encountered drop-down selection menus on web forms, and they usually look like this:

Option Select

Those basic drop-downs meet a developer's need for functionality, but they aren't winning any beauty pageants. Beyond the pure aesthetic concerns, when a menu contains dozens (or hundreds) of selectable options, it becomes a little unwieldy. That's why I was so excited to find Select2.

With Select2, you can turn the old, plain, boring-looking select boxes into beautiful, graceful and more-than-functional select widgets:

Pretty Option Select

Not only is the overall presentation of the data improved, Select2 also includes an auto-complete box. A user can narrow down the results quickly ad easily, and if you've got some of those endlessly scrolling select boxes of country names or currencies, your users will absolutely notice the change (and love you for it).

What's even sexier than the form facelift is that you can add the plugin to your form in a matter of minutes.

After we download Select2 and upload it to our box, we add our the jQuery library and scripts to the <head> of our document:

<script src="jquery.js" type="text/javascript"></script> 
<script src="select2.js" type="text/javascript"></script>

For the gorgeous styling, we'll also add Select2's included style sheet:

<link href="select2.css" rel="stylesheet"/>

Before we close our <head> tag, we invoke the Select2 function:

<script>
$(document).ready(function() { $("#selectPretty").select2(); });
</script>

At this point, Select2 is locked and load, and we just have to add the #selectPretty ID to the select element we want to improve:

<select id="selectPretty">
<option value="Option1">Option 1</option>
<option value="Option2">Option 2</option>
<option value="Option3">Option 3</option>
<option value="Option4">Option 4</option>
</select>

Notice: the selectPretty ID is what we defined when we invoked the Select2 function in our <head> tag.

With miniscule coding effort, we've made huge improvements to the presentation of our usually-boring select menu. It's so easy to implement that even the most black-and-white coding-minded web developers can add some pizzazz to their next form without having to get wrapped up in styling!

-Cassandra

August 29, 2012

Demystifying Social Media: Get Involved

A few weeks back, Kevin handed me The Thank You Economy by Gary Vaynerchuk and said we should give it a read. I'm only halfway through it, but I thought I should share some of Vaynerchuk's insights on social media with the SoftLayer blog audience while they are still fresh in my mind.

The best summary of The Thank You Economy comes straight from its pages:

"The Thank You Economy explains how businesses must learn to adapt their marketing strategies to take advantage of platforms that have completely transformed consumer culture and society as a whole."

The book looks at how human nature hasn't changed, but everything else has. The rise of social media is as game-changing as the radio and the television were, and that presents a combination of challenge and opportunity for businesses. In Vaynerchuk's words, "What we call social media is not media, nor is it even a platform. It is a massive cultural shift that has profoundly affected the way society uses the greatest platform ever invented, the Internet."

I've been "in the trenches" with SoftLayer's social media presences for over a year now, and I realized that I take advantage of the fundamental openness of the company. Vaynerchuk urges businesses to dive into social media, and he shares some of most common reasons companies aren't getting involved — I could list all eleven reasons here, but you'd probably recognize them all as excuses you've heard.* The common theme: People (and companies) fear uncertainty, and while that fear is understandable, it shouldn't be paralyzing. The opportunity and necessity of engagement outweigh the excuses.

When you clear all the hurdles preventing your entrance to the world of social media, you need to execute. Vaynerchuk explains how "Cultural Building Blocks" of a company dictate that company's success in social media, and while they aren't exactly an Easy Bake Oven recipe to viral success, they are profound in their simplicity:

  1. Begin with Yourself
  2. Commit Whole Hog
  3. Set the Tone
  4. Invest in Employees
  5. Trust Your People
  6. Be Authentic

The "trust your people" and "be authentic" building blocks resonated the most when I thought of how SoftLayer's social media is managed. The level of trust my boss has in me is both refreshing and challenging, and I find myself working harder to prove I deserve it. A cynic might read that sentence and scoff at its over-the-top positivity, but I'm as honest as I can be ... And that's an example of the challenge of being authentic. SoftLayer employees are passionate about their responsibilities and the company culture, and that kind of enthusiasm is so rare that there's a tendency to assume that it's manufactured.

If I see someone talking to us via social media about a bad experience at SoftLayer, I'm more concerned about changing their experience than I am about what they share with their social network. Often, when I follow up with those customers, when the problem is resolved, it's amazing how surprised people are that someone actually took the time to make things right. I want to hear if someone has a bad experience because I take pride in turning it around. Are we "in control" of what people say about SoftLayer on social media? No. We are in control of how SoftLayer responds to what people are saying about us, though.

Your business needs to be active in social media.

You don't need a "social media team" or a budget or a strategy ... You need to be passionate about your employees, customers and products, and you need to make time to reach out to your community — wherever they are.

What roadblocks have you run into when it comes to your business's social media engagement? If you've been successful, what tips could you share with me (and the rest of the SoftLayer audience)?

-Rachel

*If you're toying with the idea of social media engagement or you're working for a company that hasn't embraced it yet, it's worth it for you to buy The Thank You Economy to read how @garyvee dismantles those excuses.

April 3, 2012

Tips and Tricks - How to Use SFTP

Too often, new customers can get overwhelmed by a small administrative task on a Linux server. One of the more common questions I see in technical support is when a drive partition runs out of space. The website appears offline, and on of my coworkers advises you to just free-up some space. "Just?! Where can I find files that are deletable without affecting my website?"

Don't worry ... it's really quit simple. If you can use FTP (File Transfer Protocol), you can handle this bit of server management. Depending on the exact problem, we might instruct you to free up space by removing files in one of the following directories:

  • /var/log
  • /usr/local/cpanel
  • /usr/local/apache/logs
  • /usr/local/apache/domlogs

The reason these directories are usually overlooked is because they are not accessible by normal FTP users — users who only upload website content. When you upload website content to the server via FTP, the FTP user is limited to the directory structure for that website. Directories starting with "/var" and "/usr" cannot be accessed by these non-root users (The "root" user can access anything). And while root is a powerful user, for the sake of security, it is not normally allowed to log in over FTP because FTP is not secure ... That's where SFTP (Secure File Transfer Protocol) comes in.

Most FTP clients support SFTP, so you don't have to learn a new environment to securely access any file on the server. Every FTP client is different, but I'll illustrate with FileZilla because it's free and available on Mac, Windows and Linux. If you don't already have an FTP client, I highly recommend FileZilla. Because there are a few ways to use FileZilla to get an SFTP connection, I can share different options for you to try:

Quick Connect

The Quick Connect bar is the quickest way to connect to your server. Start FileZilla and look immediately under the toolbar for the Quick Connect bar:

SFTP Tutorial

Enter the hostname (IP address or domain name), “root” in the Username field, the root password in the Password field, and “22″ in the port field. Remember, port 22 is for SFTP, the same as SSH. Click the Quickconnect button to connect.

Using the Site Manager

The Site Manager lets you save your login details. Start FileZilla and you'll see the following:

SFTP Tutorial

To open the Site Manager, click the left-most icon in tool bar or go to File >> Site Manager in the menu.

SFTP Tutorial

Enter an IP address or domain name for your server in the Host field, and select "SFTP" as your protocol. You'll enter the root user's login information, and you're ready to connect by clicking the "Connect" button or you can click the "OK" button to save and close the dialog box.

If you just saved your settings and the Site Manager is not open, click the Site Manager icon again. From there, you can select the site under the "Select Entry" box, and you just have to click "Connect" to initiate the SFTP connection with your saved settings.

If you see a pop-up that warns of an "Unknown host key," clicking the "Always trust this host, add this key to the cache" option will prevent this interruption from showing in the future. Once you click "OK" to complete the connection, your FileZilla screen should look like this:

SFTP Tutorial

Notice the "Remote site" section on the middle right of the FileZilla screen:

SFTP Tutorial

This area in FileZilla is the directory and file listing of the server. Navigate the server's file structure here, and click "/" to access the top of the folder structure. You should see the "/usr" and "/var" directories, and you can explore the filesystem to delete the files technical support recommended to create space!

Message Log

If you have a problem connecting to your server by FTP or SFTP, the open area below the Quickconnect bar is the Message Log. If you can copy and paste this text into a ticket, you'll help technical support troubleshoot your connection problems. Below is an example log of a successful FTP session:

Status: Connecting to server.example.com...
Response:   fzSftp started
Command:    open "root@server.example.com" 22
Command:    Trust new Hostkey: Once
Command:    Pass: **********
Status: Connected to server.example.com
Status: Retrieving directory listing...
Command:    pwd
Response:   Current directory is: "/root"
Command:    ls
Status: Listing directory /root
Status: Calculating timezone offset of server...
Command:    mtime ".lesshst"
Response:   1326387703
Status: Timezone offsets: Server: -21600 seconds. Local: -21600 seconds. Difference: 0 seconds.
Status: Directory listing successful

And here's an example of a failed connection:

Status: Resolving address of example.com
Status: Connecting to 192.0.43.10:21...
Error:  Connection timed out
Error:  Could not connect to server
Status: Waiting to retry...
Status: Resolving address of example.com
Status: Connecting to 192.0.43.10:21...
Error:  Connection attempt interrupted by user

If you have any questions, leave them in a comment below. Enjoy your new-found SFTP powers!

-Lyndell

February 28, 2012

14 Questions Every Business Should Ask About Backups

Unfortunately, having "book knowledge" (or in this case "blog knowledge") about backups and applying that knowledge faithfully and regularly are not necessarily one and the same. Regardless of how many times you hear it or read it, if you aren't actively protecting your data, YOU SHOULD BE.

Here are a few questions to help you determine whether your data is endangered:

  1. Is your data backed up?
  2. How often is your data backed up?
  3. How often do you test your backups?
  4. Is your data backed up externally from your server?
  5. Are your backups in another data center?
  6. Are your backups in another city?
  7. Are your backups stored with a different provider?
  8. Do you have local backups?
  9. Are your backups backed up?
  10. How many people in your organization know where your backups are and how to restore them?
  11. What's the greatest amount of data you might lose in the event of a server crash before your next backup?
  12. What is the business impact of that data being lost?
  13. If your server were to crash and the hard drives were unrecoverable, how long would it take you to restore all of your data?
  14. What is the business impact of your data being lost or inaccessible for the length of time you answered in the last question?

We can all agree that the idea of backups and data protection is a great one, but when it comes to investing in that idea, some folks change their tune. While each of the above questions has a "good" answer when it comes to keeping your data safe, your business might not need "good" answers to all of them for your data to be backed up sufficiently. You should understand the value of your data to your business and invest in its protection accordingly.

For example, a million-dollar business running on a single server will probably value its backups more highly than a hobbyist with a blog she contributes to once every year and a half. The million-dollar business needs more "good" answers than the hobbyist, so the business should invest more in the protection of its data than the hobbyist.

If you haven't taken time to quantify the business impact of losing your primary data (questions 11-14), sit down with a pencil and paper and take time to thoughtfully answer those questions for your business. Are any of those answers surprising to you? Do they make you want to reevaluate your approach to backups or your investment in protecting your data?

The funny thing about backups is that you don't need them until you NEED them, and when you NEED them, you'll usually want to kick yourself if you don't have them.

Don't end up kicking yourself.

-@khazard

P.S. SoftLayer has a ton of amazing backup solutions but in the interested of making this post accessible and sharable, I won't go crazy linking to them throughout the post. The latest product release that got me thinking about this topic was the SoftLayer Object Storage launch, and if you're concerned about your answers to any of the above questions, object storage may be an economical way to easily get some more "good" answers.

Subscribe to tips-and-tricks-2