Author:


Nested Grids in YUI Grids CSS

Posted by – February 17, 2009

Today I was trying to achieve a 25%|50%|25% layout within the main block of my YUI Grid CSS layout. Everything I read in documentation seemed to indicate you could nest grids in any way you desire. So I tried doing the following:


    <div class="yui-gf">
      <div class="yui-u first">
        <p>First Column (25%)</p>
      </div>
      <div class="yui-u">
        <div class="yui-gc">
          <div class="yui-u first">
            <p>2nd Column (50%)</p>
          </div>
          <div class="yui-u">
            <p>3rd Column (25%)</p>
          </div>
        </div>
      </div>
    </div>

However this didn’t work, it appears you can only nest grids in the ‘first’ column, unless you are using ‘yui-g’ (instead of one of the alternate layouts, such as yui-gc above). I couldn’t find this documented anywhere, but I don’t know why else the above code wouldn’t work.

I asked for help on twitter, and senior Yahoo engineer and CSS component author Nate Koechley (@natekoechley) was kind enough to point me to this solution. It appears that moving the nested grid under the ‘first’ unit fixes the problem. Of course, then you have to change which grids you are using, as follows:


<div class="yui-ge">
  <div class="yui-u first">
    <div class="yui-gd">
      <div class="yui-u first">
        <p>First Column (25%)</p>
      </div>
      <div class="yui-u">
        <p>2nd Column (50%)</p>
      </div>
    </div>
  </div>
  <div class="yui-u">
    <p>3rd Column (25%)</p>
  </div>
</div>

This seems to reinforce my hypothesis that nesting of alternate grid layouts can only be done under the first grid unit. Is this by design, or is it a bug? If anyone has any insight, please let me know in the comments.

Working off the above code, I decided I might as well clean it up a little bit. Nate Koechley himself says that if you are going to use a nested grid, you do not need to enclose that grid in a grid unit div (in other words, a grid container can act as a grid unit). This was said during his YUI CSS Foundation speech (about 24 minutes in).

However, I quickly found that removing the first grid unit div broke the layout. As this goes against what Nate has said publicly, I am curious if this is a bug or if he misspoke in his presentation. Here is the non-working code:


<div class="yui-ge">
  <div class="yui-gd first">
    <div class="yui-u first">
      <p>First Column (25%)</p>
    </div>
    <div class="yui-u">
      <p>2nd Column (50%)</p>
    </div>
  </div>
  <div class="yui-u">
    <p>3rd Column (25%)</p>
  </div>
</div>

I would like to point out that I am loving the idea of the YUI Grid CSS, and am hoping to utilize it in all my future projects. All of the issues I have discovered thus far are not deal breakers. I am simply looking to master the framework in a basic testing environment, so I’m not wresting with it in a complex, large scale implementation. So again, if anyone has any insight, I would be happy to hear it!

PHP Namespaces

Posted by – October 26, 2008

I have been seeing alot of complaining lately regarding PHP namespaces, and I thought I would chime in with my (often opposing) views. First off, let me explain the issue.

The new version of PHP will have a new feature, called namespaces. (I wrote about it in my post”PHP 5.3 Feature Preview“. This is a great featured, and one that the community as a whole is excited about. So what is the problem, then?

Well initially PHP was going to use the standard “::” syntax to invoke the namespace. For example:


namespace Foo;
   function bar() {
      echo "Namespace Foo";
   }
   Foo::bar();

However, this became a problem for the parsing engine, as it is the same way to call a static function.

class Foo{
   static function bar(){
      echo "Class Foo";
   }
}
Foo::bar();

So instead, PHP changed the syntax to a blackslash. So now, in the first example, you have ‘Foo\bar();’ while in the second, you still have ‘Foo::bar();’ Seems reasonable to me (and the PHP core members) but not to some.

For example, Ninh complains on his blog that if you put the invocation in double quotes, it will interpret things like “\t” as a tab, and that you have to use 2 backslashes. I really don’t see this being a problem. First off, why on earth would you use double quotes? There are no variables or single quotes being used in the string, so one should be using single quotes anyways. That is just good programming practice.

Even if you do use double quotes, there is a tried and true, standard solution to escape the backslash character. It is so obiquitous, that Ninh didn’t have to learn how to use it, he already knew about it, yet is still complaining. His problem with this method? “It looks like crap”. I’m sorry, I though we were using logic to code web applications, not painting a picture. And even at that, why does “::” look awesome, but “\\” look like crap? I don’t get it.

My favorite quote if from the very end of his post. He claims “Last time I checked, the world wasn’t filled with scrawny developers that would come crying to their mommies after getting their first facepalm of ‘AmbiguousInvocationError’.” And yet he is crying to his mommy (or rather, the blogosphere) because if he uses double quotes (which he doesn’t have to) then he has to escape the backslash character (a standard practice) and that’s “ugly”.

So what are your thoughts? Maybe I’m crazy, and this is a huge deal. I just don’t see it.

Google adds ‘Suggest’ feature to homepage

Posted by – August 30, 2008

Google suggest is a handy feature that displays a list of likely search terms as you are typing them. This feature is usefull for several reasons:

  1. It often stops you from having to type your entire search phrase in
  2. It’s a quick way to check the spelling on a word
  3. It gives you an idea of what a good search phrase is that is related to what your after

This feature has been around in google labs for awhile. A form of it is also used in the search bar of firefox (although the search bar only displays phrases, and not the number of results each will return). So the feature itself isn’t new, but making it the default on the homepage for all users (even guests) is a big deal.

I think it is a good move. Of course they want their homepage lite and responsive, but I believe the functionality is worth the extra pageload. Beside, an Ajax search like this really doesn’t take much javascript when done right. In fact, I recently implemented a similar feature for searching tags on able2know.

I implemented it without the help of javascript libraries, although I do have a javascript file I’ve written that contains a small set of usefull tools, such as targeting elements, sending ajax requests, or validating json data. Using these helper functions, my search code becomes this simple:


var tagSearch = {
	init : function(){
		tagSearch.e = $('tagSearch');
		tagSearch.resultBox = $('tagSearchResults');
		tagSearch.original = tagSearch.resultBox.innerHTML;
		tagSearch.e.onkeyup = function(e){
			if(tagSearch.e.value != tagSearch.lastValue){
				tagSearch.lastValue = tagSearch.e.value;
				if(tagSearch.e.value.length > 1)
					Ajax.get('/rpc/tag/search/?s=' + tagSearch.lastValue, null, tagSearch.update);
				else if(tagSearch.e.value.length == 0)
					tagSearch.resultBox.innerHTML = tagSearch.original;				
			}
		}
	}, 
	update : function(r){
		var data = JSON.parse(r.responseText);
		if(data.html){
			tagSearch.resultBox.innerHTML = data.html;
		}
	}	
}

On the php side of things, I am returning html to keep things simple. Pretty easy, eh?

Useful Software for the Agile Developer

Posted by – August 14, 2008

Robert’s recent post setting up an agile webmaster workstation got me thinking about what software I utilize as an agile webmaster. While I agree (mostly) with his list, I have a few additions and alternatives.

Browsers

I agree with Robert’s list here wholeheartedly. (for those just tuning in, Robert recommends installing the lastest Firefox, Opera, and Safari browsers. He also has both IE6 and 7 installed). I would just like to expand on the IE bit. Microsoft does not allow you to have both versions of internet explorer installed at the same time, so a workaround is needed. I prefer using software called Multiple IE by Tredosoft. It uses DLL redirection to allow you to install as many versions of IE as you want (from 3.0 to 6.0!)

Development Tools

  • Zend Studio – I spend most of my time developing PHP, and as such I find Zend Studio to be a godsend. It is not free software, but the Standard Version can be had for $99, and provides all basic functionality. With this software, you never had to worry about misspelled variables, forgotten semi-colons, or the order of arguments for a function ever again. If you are a PHP developer who hasn’t used it, download the trial, you’re in for a treat.
  • PSPad – when I coding in a language other then PHP, or I just need to make a quick edit, I prefer PSPad. It is an excellent piece of freeware that has some powerful built in text manipulation tools, all with keyboard shortcuts. It also allows you to record your own macros, and play them back in a variety of ways. This has saved me countless hours when doing monkey work.
  • SQL Yog – PHP and Mysql kinda go hand in hand, so I spend a decent amount of time writing mySQL queries. SQL Yog is an excellent desktop application to manage mySQL databases. Its like a desktop version of phpMyAdmin, which is very handy.

FTP

  • Smart FTP – This is my favorite FTP software, for one killer feature: It allows you to lock the local directory to the remote directory, so when you open a folder on one side, it opens on the other side. This is very handy for keeping your local file structure the same as remote. It also supports live editing, server to server transfers, and everything else you would expect. Its only downside is its not free. However, it is reasonably priced at $37 – $50 for a single user.
  • FileZilla – If you don’t feel the need to pay money for an FTP solution, then you probably want to be using FileZilla. FileZilla is a free client, and is a great implementation of all the standard features you’d expect.

Other Utilities

  • KeePass – Most web developers have many many passwords to remember. Also, most web developers are smart enough to realize good passwords contain special chars, and are generally hard to remember. These 2 facts make password managers very useful. Keepass is my favorite. It stores all passwords in a safe, encrypted file. Then you just have to remember one ‘master’ password to unlock the application, where you can double click an entry to automatically copy the password to your clipboard. It allows you to easily categorize your passwords, store notes, search, etc. Also, it is a standalone app which will run from a USB key, so you can take your passwords with you, but they are safe if the usb key is lost or stolen.
  • Open Office – Robert mentioned cases when clients send you word documents, and you need something to open them. Google Docs is great, but is no replacement for a desktop app. However, I have found that Open Office fulfills all my needs. Admittedly, I use it very rarely. However, I have yet to run into an office file it couldn’t open, and yet to have a client complain that they couldn’t open a file I saved. There hasn’t been much talk about Open Office recently, as all the hype is moving to web apps. However this is one application that I feel still makes sense as a desktop app, and is a great example of quality open source software.

PHP 5.3 Feature Preview

Posted by – August 13, 2008

Earlier this month the PHP development team released an alpha version of the PHP platform (Read the Official Announcement). Of course there are many bug fixes, improvements, and new features. Here is a quick breakdown of the new features I am most excited for:

  • Namespaces – Finally! No longer do you have to worry about variable, function, or class names in the global scope interfering with other code libraries you may be using. A namespace essentially gives you your own personal global namespace, which you get to define. This means if you create a class called ‘user’, you can use someone else’s codebase even if they have a ‘user’ class as well.  Other languages such as C++ have had this feature for years, so its great to finally have it available to PHP. This may convince some that PHP is a viable solution in more huge, enterprise level codebases.
  • Late Static Binding – this is for those hardcore OOP coders. What this allows you to do, is reference an objects type (class name) from a function that is only available via inheritance. Its a confusing concept, but can prove useful in some situations. For a better example, see the Late Static Bindings Manual (procedural programmers need not apply).
  • Lambda Functions and Closures – Lambda functions are essentially anonymous, throw away functions. They can be useful if you want to use a simple function when you are already inside a function. Without Lambda functions, it would need to be defined elsewhere. However in some cases this can be hard to follow when reading the code, and seems wasteful when you only need to use the function once. A perfect use-case for Lambda functions is when they are defined for callbacks for other functions, such as array_walk(), or preg_replace_callback(). With Lambda functions, you can assign the function to a variable. Javascript programmers will recognize these as anonymous functions, as they are something many javascript programmers use heavily.

These are all very welcome additions, and I can’t wait till the stable version is out. The current roadmap estimates a stable version will be available by mid-October. Kudos, PHP Development team, keep up the good work!

Sitemeter disables IE browsing, hopes no one notices.

Posted by – August 2, 2008

Web Analytics service Sitemeter pushed out an update to their tracking code sometime early this morning. Unfortunately, it contained a bug that would stop Internet Explorer users from being able to access any site using the code. Apparently Sitepoint needs a few more QA testers on their team.

A bugfix has now apparently been pushed out, and the issue no longer exists. Whats interesting, however, is that Sitemeter has made no mention of their snafu. I understand that when the bug is discovered, their primary goal is to get it fixed, not issue official statements. However once they pushed out the fix, a simple “Sorry we screwed up, we just pushed a fix out, let us know if there are any more problems” should be in order.

Extending Firebug through plugins

Posted by – July 30, 2008

It’s happened. My favorite Firefox plugin, firebug, is so useful and well-designed, that developers have decided to add on to it’s functionality through plugins. While these are still installed and managed the same as a normal Firefox plugin, they require firebug to be installed first. In fact, they are not extending the functionality of Firefox, they are extending firebug itself. They are plugins for a plugin.

It started (AFAIK) with Yslow. This plugin, developed by Yahoo!, analyzes the page, and determines why it is loading slowly. It is based on their own best practices for high performance websites. This is most likely not the type of tool you will use daily, but when you get to the optimization stage of a project it is very handy.

Just the other day, I had the need to analyze the cookies one of my sites was using, and to do so installed Firecookie. Overall I was impressed. It provides a dead-simple way to view, edit, and delete any cookies associated with a page. The one feature I wish it had, was the ability to temporarily disable cookies, without deleting them. This is handy if you want to quickly check what something looks like while logged out of a site, without having to actually log out, and then back in.

There are other firebug plugins I have yet to use, and I’m sure more are currently being developed. All of this added functionality strengthens my belief that firebug is becoming less of a nicety for developers, and more of a necessity. It is definitely one of the larger tools in my development toolbox.

Convert UTC dates to local timezone offset automatically

Posted by – September 11, 2007

So I was working on an application that printed out lots of dates to the user. However, I get traffic from all over the world, and as this is kind-of time sensitive information, I wanted to display the time in their own timezone. I have don’t this before on things like forums, where you allow the user to select their timezone when they register. But what if your users don’t register?

I decided to build a javascript function that would automatically convert from UTC time to the users’ local timezone. This is a pretty simple task, and should work very effectively. I already store the dates in my database as UTC format, which is a good idea to do so that there is never any confusion later as to what timezone a date is in (What if you and/or your server moves?). Also because this is a javascript function, we have the ability to determine the users local time – something that we normally wouldn’t have.

Without further ado, here is the code:


var dateFunction = {
  convertDate : function (gmtDate){
    var originalDate = new Date(gmtDate);
    var retStr = (originalDate.getMonth()+1) + "-" + originalDate.getDate() + "-" + originalDate.getFullYear();
    return retStr;
  },
  init : function(){
    var elems = YAHOO.util.Dom.getElementsByClassName('utcDate');
    for(var i=0;i

As you can see, I am using the YUI library to do some DOM parsing, and unobtrusively add some event listeners. The code should be pretty straight forward, when the page loads I look for all elements with a class of "utcDate" and pass the innerHTML into a separate function. The other function create a new date object, using the original UTC date as the time. By doing this, javascript automatically will display this new date in the users' local time. I can then return the date in whatever format I want. Finally, I replace the innerHTML of the element with the new date string, and we are all set

This provides a simple way to convert dates to local timezone offset, and all the is required is for you to wrap any date you want converted in an element with a class equal to "utcDate". It also degrades gracefully, because without javascript users will simply see the date in UTC format, which isn't really a bad thing, and probably what you would be showing them anyways, if you didn't have this nifty script!

rss 2.0 feed format tutorial for .NET

Posted by – August 22, 2007

I have been creating custom blog software using csharp.net. One task that I accomplished today was getting both an RSS and an ATOM feed setup. This will allow people to read the blog on sites like netvibes, my yahoo, or google IG. So heres how I did it:

  1. Change the content type of the page to text/xml

    This is needed so that other computers and browsers will know that it is an XML page they are reading, and not the standard HTML. Luckily this is simple to do, simply add ContentType=”text/xml” to the Page directive, like so:

    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="rss.aspx.cs" Inherits="rss" ContentType="text/xml"%>
    
  2. Setup RSS 2.0 XML Document

    Now in our code behind file, we can write directly to the output stream, as the proper header is already set. You may think about using Response.Write to create the RSS XML tags, but there is a much easier way. You can use an XmlTextWriter to achieve the same result, without needing to escape all characters that can’t normally be in an xml file

    
            // Create a new XmlTextWriter instance
            XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
    
            // Create Document
            writer.WriteStartDocument();
                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                    //Set Channel Information
                    writer.WriteStartElement("channel");
                        writer.WriteElementString("title","[SITE_TITLE]");
                        writer.WriteElementString("link",[SITE_URL]);
                        writer.WriteElementString("description",[SITE DESCRIPTION]);
                        writer.WriteElementString("lastBuildDate",[RFC-822 DATE]);
    

    Here we setup the start of the XML document with all required fields. The lastBuildDate element should be the last time the xml feed has changed, which should also be the last time something new was posted.

  3. Output Post information

    The standard is to display them in reverse chronological order. Most likely you will be creating these in a loop, like so:

    
    for (int i = 0; i < postList.Count; i++)
    {
    
        writer.WriteStartElement("item");
            writer.WriteElementString("title",postList[i].pageTitle);
            writer.WriteElementString("link", postList[i].url);
            writer.WriteElementString("description", postList[i].content);
            writer.WriteElementString("pubDate", postList[i].postDate);
            writer.WriteElementString("guid", postList[i].url);
        writer.WriteEndElement();
    }
    

    Here I am assuming postList is a list of object containing post information. The pubDate tag is the date that the post was published, and guid is a globally unique identifier for the post. If you have a GUID setup in the database for the post you can use it, otherwise it's easiest to just use the permalink (url).

  4. Close Document

    Now that we have displayed all relevant information, we simply need to close open tags, and end the xml document

    
                    writer.WriteEndElement();
                writer.WriteEndElement();
            writer.WriteEndDocument();
    writer.Close();    
    

    Thats all there is to it. You can now use this page to submit to sites such as netvibes, google ig, my yahoo, or any other services that will parse rss 2.0 xml feeds.

CSharp Blog ping code using xml-rpc and weblogupdates.ping for Pingomatic, Technorati

Posted by – August 1, 2007

I am currently writing a custom blog application in csharp.net (c#.net). One requirement for the software was that it needed to send update information to sites like Technorati or Ping-o-matic. After some research, I’ve found that sites allow you to do this utilizing xml-rpc. The process is called pingback, but it more commenly refered to as simply pinging. Basically every time you write a new post, you can ping these services to tell them you have updated content, and let people know about it.

The specific method we want to access via xml-rpc is called “weblogUpdates.ping”. This function is implemented on all blog ping services. Below is a function which defines a list of sites to ping, then goes through and pings them one by one. It takes as parameters the name of your site, and the url of your site.


private void sendPing(String name, String url)
{
ArrayList listToPing = new ArrayList();
listToPing.Add("http://rpc.technorati.com/rpc/ping");
listToPing.Add("http://rpc.pingomatic.com");
listToPing.Add("http://blogsearch.google.com/ping/RPC2");

for (int i = 0; i < listToPing.Count; i++)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(listToPing[i].ToString());
    request.Method = "POST";
    request.ContentType = "text/xml";

    Stream stream = (Stream)request.GetRequestStream();

    using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8))
    {
        xml.WriteStartDocument();
        xml.WriteStartElement("methodCall");
        xml.WriteElementString("methodName", "weblogUpdates.ping");
        xml.WriteStartElement("params");
        xml.WriteStartElement("param");
        xml.WriteElementString("value", name);
        xml.WriteEndElement();
        xml.WriteStartElement("param");
        xml.WriteElementString("value", url);
        xml.WriteEndElement();
        xml.WriteEndElement();
        xml.WriteEndElement();
        xml.Close();
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            string result = sr.ReadToEnd();
            sr.Close();
        }
        response.Close();
    }
}