67 entries in Development

UI Manager

Save and load rollout settings, such as size, position, control states, items, etc to a preferences file

Thursday, May 1st, 2008

A struct containing methods to save and load rollout settings, such as size, position, control states, items, etc
to a preferences file, as well as methods to accomplish UI control tasks for example keeping one spinner higher or lower
than another when editing ranges.

Usage

To manage a rollout or dialog, you simply:

  1. create a struct instance
  2. initialize it with a reference to a rollout
  3. Manage the rollout by calling the struct's methods

In code, that's as easy as this:

ui = uiManager()
ui.initialize roTools
ui.loadPosition()

All settings are saved to an .ini file named after the rollout title, so in this case, an ini file named "Tools.ini" would be saved to your max installation's /plugcfg folder.

Methods

This is a work in progress, and will be updated from time to time with new methods.

Dialog functions

  • savePosition - save the dialog position
  • loadPosition - load the dialog position
  • saveSize - save the dialog size
  • loadSize - restore the dialog size

Rollout functions

  • autoSizeFloater - resize the floater to exactly the size of all open rollouts
  • toggleRollout - set one or several rollouts open
  • loadRolloutStates - save all rolled-up / down states (not yet implemented)
  • saveRolloutStates - load all rolled-up / down states (not yet implemented)

Control functions

  • updateSpinnerPair - ensure that spinners react as a pair, eg one can never go higher than the other
  • moveListboxItem - move selected Listbox items up or down, and have them remain selected
  • moveMultiListboxItems - move multiple MultiListbox selections up or down, and have them remain selected
  • getValue - abstract function to get a control's value (not yet implimented)
  • setValue - abstract function to set a controls's value (not yet implimented)

Preference functions (WIP)

  • saveValue - save a control's value
  • loadValue - load a control's value
  • saveAllValues - save all controls' values
  • loadAllValues - load all controls' values

Downloads

Download uiManager0.52.ms. Place in your scripts/startup directory, or just include the file when you need it.

These example files will get you started:

Flash “PHPLoadVars” class

Natively send complex / multidimensional variables from Flash to PHP with this extended LoadVars class

Thursday, February 28th, 2008

I was pitching in on a forum thread Send an object to a php script the other day and some chap wanted to send complex objects to PHP using LoadVars. "Can't be done!" was the reply.

Oh yeah? Well if PHP can deserialize array variables from HTML forms, I don't see why we can't do the same with Flash.

Well it took about 15 minutes to work up a rough proof-of-concept that worked for GETs only, but it got me thinking to do something nice with:

  • a proper class
  • that works with POST (so you can send BIG objects!)
  • and has a recursive serialization routine (so you just give it any nested data-structure, and it chews through all of it)

PHPLoadVars (also works with Ruby)

Well it couldn't be simpler, really. Just create a new PHPLoadVars object, ask it to serialize your data, and send:

var data :Object      = {data:[1,2,{sub_object:{name:'Dave',age:33,gender:'male'}},3,4,5]}
var lv	 :LoadVars    = new PHPLoadVars();
lv.serialize(data)
lv.send('process.php')

Then PHP receives the complex variables natively like so (a quick print_r($_POST); shows the results):

Array
(
    [data] => Array
        (
            [0] => 1
            [1] => 2
            [2] => Array
                (
                    [sub_object] => Array
                        (
                            [gender] => male
                            [age] => 33
                            [name] => Dave
                        )

                )

            [3] => 3
            [4] => 4
            [5] => 5
        )

)

Just to be absolutely clear - this result isn't manually de-serialized, or run through any processing routines - PHP automatically reads in data serialized using square brackets (which is how things were serialized in Flash) as numeric or associative arrays, so your data is literally ready to go as soon as the headers have been processed!

And you can make your data-structure as deep as you like...

Could it be any easier!? No. It couldn't! Not even XML is this easy!

Download

Download the class file, sample .fla, and a basic PHP file to echo the variables to screen.

LoadPHPVars.zip

jQuery Favelet

Add jQuery functionality to any browsable web page

Saturday, February 23rd, 2008

Any developer worth his salt knows about Firebug and its JavaScript console. I use it all the time to tinker with web pages, test stuff out and debug my own pages.

But sometimes, if I'm *cough* hacking *cough cough* someone else's page, I need the added power of jQuery! But what if the page doesn't have it?

Simple - load jQuery from a remote source manually through a javascript: call.

Save Favelet

Just drag the link below to your Links toolbar, then click it on any page to jQuery-enable it.

Add jQuery to page

Test it out!

Save the Favelet and click on it (or just click the link above), then: animate page.

Simple!

Wordpress “Page Redirect” template

Have any page in the Wordpress "Pages" list invisibly redirect to a static page or other url

Wednesday, February 20th, 2008

The very nature of Wordpress demands that you work within it's infrastructure in order to maintain flexibility. Sometimes, though, the structure of your pages demand that you need to operate outside of this constraint.

This template lets you specify a single URL as the page content, then as the page loads, the template automatically redirects the page to this new location.

Usage

Once you've uploaded the template-redirect.php file to your themes directory...

1 - Create a new Page in your Wordpress control panel

2 - In the Page Content panel, just enter the URL (or local path) you want to redirect to:

3 - Set the Page Template dropdown to "Page Redirect":

That's it!

Examples

Examples of URLS might be:

  • category/flowers (a relative link to the permalink for "flowers")
  • ../page.html (a page outside of a Wordpress subfolder (the WP folder being /blog/) but still in your site)
  • http://www.davestewart.co.uk/resources/ (a page on a completely different site)

The "Latest developments…" page in my sidebar automatically redirects to /category/development/ - or in other words, the archive for my "Development" category, as my home page is not the standard "last-post first" format.

Download

template-redirect.zip

jQuery “Highlight” plugin

Highlight a form field’s parent tag (or any other selector) as you tab into it.

Tuesday, February 12th, 2008

Highlight increases usability by highlighting elements as you interact with the page.

Its primary use is for forms, but it can also be used for tables, lists, or any element you specify. It can also be used to toggle elements on and off, for example, table rows.

Examples uses:

  • Form-filling can be made clearer by highlighting the element around a control as you tab into it
  • Table rows can be made more visible as you pass the mouse over them, or click them
  • Elements can be toggled as you click them

Code example

Because of the defaults, basic usage can be as simple as:

$('form').highlight()

The method signature for Highlight is:

$(selector).highlight(parentSelector, highlightClass, startEvent, endEvent)

Demo

View the Highlight demo which has examples for forms, tables, and lists.

Download

jQuery “Populate” plugin

Populate a form or an element's child elements using a JSON object.

Tuesday, February 12th, 2008

I don't like mixing HTML and PHP when I build my forms. Instead I like to keep my HTML completely clean, then if a form needs to be pre-filled (for example retrieving a bunch of database results), get JavaScript to fill it in for me after the page has loaded.

This plugin supports full PHP naming and deep data structures, as well as checkbox arrays and other non-standard UI controls. The plugin can be used as part of your AJAX toolkit, or for separating server-side code from HTML by populating a form after the page has loaded eg:

$('form').populate({text:'text', radio:1})

and not inline as the page is processed, such as:

<input type="text" name="text" id="text" value="<?php echo $text; ?>" />
<input type="radio" name="radio" id="radio-1" checked="<?php echo $val == 1; ?>" />
<input type="radio" name="radio" id="radio-2" checked="<?php echo $val == 2; ?>" />

You can also populate non-form controls such as <div>s, by specifiying the id and an identifying attribute (defaults to id):

$('div').populate({'text-1':'text', 'text-2':'More text'})

This can be useful when you want to show the results of a database call, but don't want the text to be editable.

Instructions and demos

I've now FINALLY put up a full set of instructions and a working demo, with examples of:

  • Populating a simple form, using string variable types for textfields, radiobuttons, dropdowns and checkboxes
  • Populating a complex form, using array variable types for checkbox arrays and multi-list boxes
  • Populating a hierarchical form, using hierarchical JSON data

View the jQuery Populate Demo here.

Download

JavaScript

PHP

Form builder

Convert a list of text into fully validated, accessible HTML form controls

Monday, February 11th, 2008

I've got really, really tired of re-inventing the wheel (alright, HTML, CSS, JavaScript) every time when it comes to site forms.

I do so much database stuff these days that seems to be virtually every site I'm starting from scratch, or hacking an old site's template to work on a new site. Then once the CSS has been hammered out, comes the laborious task of form validation - tidying up all the names and ids, dusting off my RegExp-foo to validate emails, usernames, etc, etc.

It's very time-consuming and just feels like I'm missing a trick!

Wouldn't it be great if there was a magic bullet to convert a list of text into fully validated, accessible HTML form controls!?

Form Builder

Enter "Form Builder" - an online JavaScript application that will build accessible, cross-platform and validated form HTML in literally 10 seconds flat. Just type or paste in your form labels, edit some options (if you want to) and view the Live Preview and HTML.

Form builder does pretty much everything you might want...

So I've done some hard research and have employed best-practices for:

  • HTML Code
  • Styling
  • Accessibility
  • Validation

For example, what about:

  • Ease of use: copy all your labels to one text field and a whole set of controls built on linebreaks, tabs, commas
  • Live preview: not happy with the code? Edit the HTML and watch the Live Preview update
  • Intelligent attribute naming: for example, a form label is "Blood pressure (mmHg)", your names and ids are truncated at the first illegal character and re-named "blood_pressure" / "blood-pressure"
  • Automatic values: values are automatically built from the label names, or you can just paste in another list of values
  • PHP (or other) naming styles: specify a data sub-group, or use your own square bracket naming [] to group data into discrete chunks
  • Accessible HTML: all controls are married with labels, and where appropriate wrapped within <fieldset> tags
  • Validation: Optionally include basic validation attributes on elements using jQuery's Validation plugin.

Jump in and play here, then go do something more useful with all that spare time!

XML / XSLT site management tool

1-click login to all your site logins, databases, password-protected pages, memberships, ftp areas etc.

Friday, December 14th, 2007

Fancy a quick & easy, yet extensible & robust login manager to organise & store all your urls, usernames and passwords, in whatever categories your care to put them?

Simple. Just store your user / site details in an easily editable XML file like this and use XSLT to transform it (on the fly) into a really easy HTML page like this...

Intrigued? It's not as difficult as you think.

Information overload

At the last count, I have about 15 - 20 sites that I manage for myself and my clients. This means I have to remember a

  • url
  • username
  • password

For:

  • Site login
  • Site database
  • Wordpress login
  • Wordpress database

So for 15 - 20 sites we're looking at anywhere between

  • 45 (15 sites x 1 login x 3 url, username & password) to
  • 240 (20 sites x 4 logins x 3 url, username & password) bits of information.

What a headache!

From bookmarks to JavaScript to XML

So, for the last few years or so, I've resorted to keeping bookmarks in each client's folder, along with a text file with the relevant details. However, a few months ago I realised that I may be able to bypass some of the manual login palaver by storing the whole login url as one long GET string, and calling it straight through the browser:

http://www.mysite.co.uk/login.php?username=dave&password=ilikefish

This works on some sites, but for others that don't like GET and take only a POST, it didn't work.

So, I thought how about having an HTML / JavaScript page with a form that has it's values (name, password, etc) set dynamically by selecting a drop down, then connects to the server and does the login like that?

Eureka! It worked very nicely thank you. So I've been going along with this quite happily for a while until I had to add a few more sites, and started to get a bit overwhelmed with the sheer amount of data I was having to put into all these JavaScript arrays.

Hmm... what do do now? How best to store all this data? Well, XML seems like the logical choice, but how to actually parse and search that XML from within the HTML file? Embed it as HTML and use some DOM manipulation? Regular expressions? Perhaps I should use jQuery and it's AJAX capabilities?

Then all of a sudden it struck me. XSLT! My only real memory of XSLT (Extensible Stylesheet Language Transformation) were from the chapters in my XML book, and I knew that it was pretty dry stuff that I'd probably never use... however here it was, about to come to my rescue.

XML + XSLT = HTML

In a nutshell, XSLT allows you to take a skeleton XML document and "transform" (move it around, add stuff, repeat stuff) it into a fleshed-out HTML (or any other markup) document by applying rules and templates to individual XML tags.

In a way similar to how CSS styles HTML by using selectors to select nodes, and change the visual result...

 p {
    color:red
    }

...XSLT can apply your own rules and templates to nodes...

<xsl:template match="category">
<h2><xsl:value-of select="@name"/></h2>
<div class="category">
<xsl:apply-templates/>
</div>
</xsl:template>

...to physically change their structure and markup, creating a brand new hybrid document.

You can think of XSLT as a set of "templates" with some basic logic for transforming individual tags.

For example, let's say you want to transform a list of names, phone numbers, and addresses specified in <ul> and <li> tags to something a little more presentational. You could specify that the first <li class="name"> should be transformed to a <h3>, and the second <li class="number"> be transformed to a <div>, then the rest of the list remain as a list. Finally, wrap the whole thing in a <div class="entry">, and for the fun of it, add a <hr/> to the end.

The end result is full HTML output viewable in the browser, and if CSS styling is applied, looks and behaves no differently from an HTML document that you'd created yourself.

The advantage of styling XML with XSLT is that you keep data and presentation completely separate, and therefore your data is far easier to manage.

To make the XSLT act upon your XML is as simple as specify a link to the XSL file in the head of the XML file, in the same way a CSS file is specified in the head of an HTML document.

<?xml-stylesheet type="text/xsl" href="login-manager.xsl"?>

Requirements

So - back to my Login Manager scenario. I wanted to process my skeleton XML of all my urls, usernames and passwords to create a new document that had:

  • Clear sections for each of my top-level categories: Misc, Personal, Business
  • In each category, a list of sites with a title and text-based link
  • For each site, a list of login types
  • For each login type, a mini login form that replicates a standard login, with
    • hidden form fields for username, password, or ANY attributes I specify
    • target url specified as the form's action
    • a login button to send the variables and perform the login

Basic XML structure

Login data is not that complicated (url, username password) so there's only need for a few basic tags, plus some extra tags to organise the data:

  • category - groups together particular sites under a common heading, e.g. "Business", "Personal"
  • site - groups together all the different logins for a single site
  • application - group together any application-specific login data, such as Wordpress admin & database logins

Then we have some specific login types:

  • login | database - login to an application using HTTP (form data)
  • folder - connect to a password protected folder using URL syntax (protocol//user:pass@domain/path)
  • page - just load a page without passing any variables

And finally there's a few basic attributes:

  • name - the name of the category, site or application
  • url - the full http: url of the site
  • username - user name
  • password - password

If you need to pass any other attributes, just add them to the specific login or database tag and they will be included in the final login forms the XSLT will create.

This is how the XML structure would look for one site with 4 login types, organised under a category heading. Note only the few tags listed above.

And here's the final XML as it looks in XML Notepad (click to see a dummy XML file):

How I've leveraged XSLT in this application

Although XSLT is markup (in fact it's XML), it's not just dumb text. XSLT is actually a language, and is capable of making decisions as it processes the XML. Each kind of XSLT tag is in effect a different command, with it's attributes acting as parameters to that command.

For example, the <xsl:choice> tag could be seen as an if/then or switch/case construct in a real programming language, so you can use it to make decisions as you process the document. In other words, when the parser is processing one of your "mini-templates" and it comes across an <xsl:choice> tag, you could change exactly how your XSLT rule will build the next bit of HTML output. I've used this to map the username and password attributes stored in the XML file to custom field names, depending on each login application's form requirements.

For example, Wordpress expects log and pwd rather than username and password, so with a <xsl:choice> tag I just instruct the XSLT parser to output these preferred field names where any login tag has a parent tag of type application, with it's name attribute set to "Wordpress".

I've put a lot of comments in the XSL file so it should all become clear.

Speaking of which, it's about time to take a look at the XSLT file. Note the:

  1. XSL templates for each kind of tag, for example:
    • the root tag: <xsl:template match="/sites">
    • any site tags: <xsl:template match="site">
    • any folder tags: <xsl:template match="folder">
    • any login or database tags (which are treated the same): <xsl:template match="login|database">
  2. the actual HTML inside each of the templates that get printed to the page for each tag
  3. Any logic associated with the rules, e.g. <xsl:choose> and it's children
  4. How XSL outputs actual values from the XML, e.g.
    • a node's name: <xsl:value-of select="name(.)"/>
    • the value of a url attribute: <xsl:value-of select="@url"/>
  5. How XSL builds HTML manually, including
    • tags <xsl:element name="form"> and also
    • attributes <xsl:attribute name="method">

End result

Below is the end result of XSLT applying all those tag-specific mini-templates to the XML. Click the image to see the live results with a dummy XML file.

Pretty comprehensive I think you'll agree.

And in case you still haven't quite cottoned on - yes - this is an XML file you are looking at! If you don't believe me, just do a "View Source" to see the actual XML, and marvel at what a stunning job the XSLT has done.

Taking the file and using it yourself

I'm a big fan of choosing the right tool for the job, and in this case XSLT has been absolutely perfect. I wrote a fairly basic XML file and it didn't take long to learn the few commands I needed to turn it into a really useful HTML document.

If you want to use this to handle your own site logins, feel free to take and update the file. As long as you stick to the category > site > (application) > login > attributes structure, the XSLT will give you a user-friendly front-end to your XML, every time.

Just place any standard login and database settings under a login or database tag, and group any application-specific settings under an application tag, and the XSLT will create a new named sub-section for you.

If you wish to pass any other specific variables to a login script (for example you may have a landing page specified, ala Google Analytics), just add these attributes to your login or database tags.

Files and Links

I'm certainly no expert on XSLT so I'm not here to provide the world with tutorial, but I am up for sharing the code I've written, as well as providing links to the pages on the Internet that helped me.

These pages got me most of the way:

And here's some software you'll find useful:

  • Microsoft XML Notepad. Lightening quick XML editing with a small footprint. Great for editing small xml files.
  • Architag XRay. Real-time XSLT processing so you can see your code in action without having to preview in a browser

Hopefully someone will find this as useful as I have!

Cheers,

Dave

Adding Google Analytics to your web pages dynamically

Single-script Google Analytics inclusion

Friday, December 7th, 2007

I've just started using Google Analytics and it f*cking rocks. It's simply amazing the amount of information it provides, but more amazing still is the way it shows you how people are using your site.

Installation is as easy as copy and pasting two scripts into each web page you want tracked. What could be easier than that!? Well, how about one script?

Here's the code needed to run the tracking functions automatically:

<script type="text/javascript" src="js/google-analytics.js"></script>

Here's the code to load the tracking functions without running them (works in ALL browsers, not just IE!) so you can call the code yourself later (for example, tracking an AJAX call):

<script type="text/javascript" src="js/google-analytics.js" defer="defer"></script>

Of course, there's a few of these out there already, but here's the specifics on my take:

  • easy: a single external script that loads the Google code dynamically
  • intelligent: calls tracking function only when remote script has fully downloaded
  • versatile: use of defer attribute to run automatically (or not)
  • customizable: provides a wrapper function to execute your own custom code
  • tidy: intermediate setup variables are created privately via a function closure

Just be sure to add your tracking id to the initialization function!

Download google-analytics.js

Network-Render all Cameras

Automatically submit all cameras to a network render, rendering the correct frames, and save the output to the correct directories

Friday, October 26th, 2007

This MAXScript entry has not yet been completed...
(more...)