HTML Formatter ColdFusion-friendly code cleanup tool

No matter how clean your code, there's something to be said for a fast, clean pre-launch cleanup with a reliable code formatter . My favorite by far is the HTML Formatter from LogicHammer.com:  http://www.logichammer.com/html-formatter/

Complete with a full set of ColdFusion-friendly options, this simple tool makes cleaning your code a snap. I use it as I'm working, to clean up the work-so-far at any point, and before final launch to make sure the production code will be as easy as possible to maintain and revisit later on. It is a standalone executable, which means there's no installation, and you can put in anywhere you like on your hard drive.

I simply create a taskbar shortcut on my Windows PC and drag the files I want to clean directly from the 'project' view in Eclipse onto the icon - couldn't be faster, simpler or easier. I prefer to have my original files altered, with the originals automatically put in a specified backup location - you can also assign the option to leave the original alone and create a cleaned-up copy.

Among other fav features, HTML Formatter ships with a simple text-based config file which makes it incredibly easy to specify tags to ignore or to indent, and file extensions to be formatted or skipped ( you can run the formatting on specific files, or an entire directory).

For only $14.99 you get all the features and 2 years of updates (there is also an 8.99 version with a basic feature set). The program's developer has answered every question I ask directly and has been very helpful with customizations, even building in some features I requested a while back (for the record - I'm not affiliated with logichammer in any way, just very pleased with this slick little tool).

How to find lowercase (no caps) values in mySQL (and Capitalize them with ColdFusion)

I have a request from a client to help clean up some customer-entered data in a mySQL database, specifically, we need to capitalize all of the values in a column called 'user_city'

For the actual capitalization, I am using the very handy CapFirstTitle() function from CFlib : http://www.cflib.org/index.cfm?event=page.udfbyid&udfid=116

But first, I need to find all of the entries that are not already capitalized. This dataset has tens of thousands of records , including some with a blank value in the 'city' field - no need to loop all of that just to fix our caps!

So, here's the SQL query code to find all of the records with no capital letters at all, by comparing to a lower() all lowercase version of the same value:


SELECT user_city, ID
FROM site_users
WHERE user_city = lower(user_city)
AND NOT user_city = ''
ORDER by user_city

And here is the full CFoutput / CFquery code for the loop and update with Coldfusion, and the CapFirstTitle() function in the head of the page:


<cfoutput query="myQueryAbove">
    <cfquery datasource="#application.dsn#">
    UPDATE site_users
    SET user_city = '#capFirstTitle(myQueryAbove.user_city)#'
    WHERE ID = #myQueryAbove.ID#
    </cfquery>
</cfoutput>

for other columns you could use OR in the first query and an additional statement in the second, or just change the queries, run the page again, or even, make the column name a variable and just change it once in the head of the page... easy.

mySQL str_to_date converts text formatted dates and times to real SQL timestamps

I am working on a site where dates have been stored as text strings in a mySQL database, such as '2009-10-17' , and I need to create a 'search by date' function where a given start and end date can be compared to the date stored in the database. In other words, i need to convert the text-formatted date to a real 'datetime' value , that can be compared with (greater than) and (less than) logic within the query itself.

Like all things CF/mySQL , there are usually multiple ways to get things done. After kicking it around a few different ways, I settled on mySQL's built-in "str_to_date" function as the easiest and most efficient solution.

The str_to_date()  function takes two arguments: the string that is to be converted, and a format string, which uses the same syntax as mysql date_format() and other related mySQL date functions.

Since the dates are entered in 'yyyy-mm-dd' format, my format string is" %Y-%m-%d "
(Note the capital Y which signifies a 4-digit year)

My query now looks something like this - note the second line:

SELECT
str_to_date(aa.date_published,'%Y-%m-%d') as articleDate,
aa.title, aa.ID,
aa.author,
aa.article
FROM articles_table ...

This converts the date, 2009-10-17,
to a datetime stamp,
{ts '2009-09-17 00:00:00'},
which can now be used for any type of date comparisons.

To keep things clean, if an article happens to be entered with a different format that does not match our format pattern (i.e. somebody types in '10/17/09'),  str_to_date() will simply return an empty string in that column, rather than throwing an error.

The mySQL specification for this and other functions is here:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_str-to-date

 

 

 

New TinyMCE lets you paste as plain text automatically

When building web applications, one of the most common functions involves allowing a site administrator to add or edit content on a page via some sort of 'wysiwyg' (what you see is what you get) editor. My tool of choice for this purpose is the very versatile, relatively light TinyMCE ( tinymce.moxiecode.com)

As great as these tools are, it is inevitable that the average site administrator will want to copy and paste some text from a word processing function like MS Word or WordPerfect, both of which add invisible formatting to the copy-and-pasted text, which in turn can really mess up even the best of web designs.

TinyMCE has had a very nice 'paste from word' plugin for as long as I can remember, but it still requires the user to click a tiny icon for the 'paste from word' popup, and then paste their text into that. ( There is also a 'paste as plain text' option which removes all formatting just as if you'd copied into notepad first, then pasted into the web form). So, even with these great options, I still find myself answering more than a few support calls related to text not looking quite like it should (or worse) when copying from Word.

Much to my delight, I've found a much better solution - the newest version of TinyMCE has the "paste" plugin built in, and it now includes options for cleaning up the text automatically when pasting right into the main text box (without needing to use the littlepopup icons).

As seen on the paste plugin page (TinyMCE:Plugins/paste - Moxiecode Documentation Wiki) you simply need to include 'paste' in the list of plugins when initializing the tinyMCE script, and then can call the cleanup options like this:

            paste_auto_cleanup_on_paste : true,
            paste_remove_styles: true,
            paste_remove_styles_if_webkit: true,
            paste_strip_class_attributes: true,

This runs the 'paste from word' function automatically, then removes any remaining inline style and class attributes , leaving you with nice clean paragraph-formatted html.

so, whether your clients remember to use that little button or not, whatever they paste (via ctrl+v on their keyboards) will be stripped clean, ready to be shown in pristine valid html format on your site.

Keyboard Shortcuts I use all the time

WIN 7
--------

Win + Arrow left/right: 
snap open window to 1/2 monitor frame

Win + Arrow up/down: 
up: full screen (maximize window)
down: restore / minimize

Alt + F4:
Exit program / close window

Win + D:
Show desktop

 

Eclipse (w/ CFeclipse)
----------

Ctrl+Alt+Up/Down arrows
Duplicate line

Alt+Up/Down arrows
Move line

Alt + F > A
Save as

Ctrl + Shft + R
Open file w/ search by name


Firefox
----------

Ctrl+T
New Tab

Ctrl+T
New  Window

Ctrl+Shift+Q
Inspect Element (Firebug)

Ctrl+Shift+F
Display Element Information (Web Dev Tools)

Ctrl+Shift+W
Close window (close all tabs)

Ctrl+W
Close current tab

How to show changed input and select fields with jQuery

Here are a few quick easy jquery functions that will add a class of 'changed' to any input or select box if it is changed, and will remove that class if the value is reset to the default.



        // inputs
        $('form.myForm :input').change(function(){
        var defval = $(this)[0].defaultValue;
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

        // select boxes
        $('form.myForm select').change(function(){
        var defval = $(this).find('option[defaultSelected=true]').val();
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

Note in both cases we use keyup (onkeyup) to trigger the 'change' event. This allows the browser to show the changed class as soon as the user changes the value using a keyboard, rather than 'onblur'.

How to find Specific Column Names or Types in a mySQL Database

I'm working on a rather extensive CMS admin application, and need to make some adjustments to all of the "sort" fields in the database. Many of the tables have either a 'sort' or 'sort_order' (and in one case, I think I saw 'SortOrder'), and I need hunt them down, creating a list of column names and table names so i can quickly find the columns I want to edit.

I could open each table one by one, and look for those column names... but of course, there's a much better way:


SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE lower(column_name) LIKE '%sort%'
AND TABLE_SCHEMA='//my database name here//'

This returns a perfectly formatted query of table names and column names, along with the 'data type' for any column containing 'sort' (or 'Sort'). Now it will be a snap to make my changes to all of the numeric sort fields in the entire database.

The query can be modified to return all sorts of useful info, such as all columns in the entire database:


SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='//my database name here//'

or all columns with a specific data type


SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='//my database name here//'
AND DATA_TYPE='varchar'

And then, if you wanted to get really lazy, er, creative... you can loop the results of that query, and 'do stuff' to all of the columns automatically with just a few more lines:


alter table #table_Name# modify #column_name# VARCHAR(55) ;

(this would set the size of your varchar field to 55 characters, for example)

Installing SQL Server 2008 Management Studio Express

I don't do much work on MS SQL, but a recent project requires I connect to a remote SQL 2008 database, so I went looking for the new version of the SQL Server Management Studio Express program which has worked so well, and so simply, for SQL 2005 databases.

Simple enough, right? Not quite. It didn't take me long on Google to realize i was far from the only one having trouble installing just the Management Studio, without the server components. Microsoft has managed to make this process incredibly unintuitive, including links and download pages which don't actually point you to what you think you are getting.
( for examples, see the google link above... i'm being really nice in this post by comparison!)

The best compromise i could find was the official MS download page, which offers a 160+mb file containing the full database server system. Blog posts mention compatibility issues (Win7 did throw up some warnings of its own when i started the process, so i backed out and kept looking), incomplete installations and the need to run the installer twice so you can 'add' the Management Studio as a component to an existing installation.

Huh? Exactly.

So, anyway...  for those that might be in the same plight... I have the solution!

Go here: http://www.microsoft.com/web/Downloads/platform.aspx and install the MS 'Web Platform Installer'.  Then, when the installer loads up, find the little 'customize' link under the "Database" section, where you can tick the boxes for the components you want to install. ( see image )

Once i got it going, this was actually a slick little installer.
(So finally I have SQL 2008 Management Studio ready to go.
Now, what was i going to use it for?)

 

How to find Duplicate Entries in a mySQL Database

Here's a quick easy query that will return all records where a given column's value appears more than once.

The trick is the 'group by' phrase, combined with the selection of the 'count(*)' value, which simply counts the records found for each match of 'Name'.

This query will return any records where the same value appears more than one time in the given column (in this case, the 'Name' column), along with the 'Counter' value showing how many times the duplicate appears.


SELECT Name,count(*) as Counter
FROM Table_Name
GROUP BY Name
HAVING Counter >
1

Javascript How To: Add a Number of Days to a Date

I have a form where a user can input a date in the format mm/dd/yyyy, and we need to add an 'expiration date' that is 30 days from the date entered, regardless of calendar month, leap years, or other complex calculations.

Thankfully, javascript already has the 'setDate()' function built in. We just have to parse the date object (a full javascript formatted date string) out of the given form input ( e.g. '11/10/2009').

Easy enough - first we parse out the numeric date/time object, and in this example, write it to the screen.

Then, we add 30 days (the number of days can be changed in the setting for the 'interval' variable - use a negative number to remove days)

Again, this example simply writes the date to the screen. In the current usage, I will use that date value to populate another text input in the same form as the initial date being entered.


<script type="text/javascript">
function setExpDate(formDate){
    // set number of days to add
    var interval = 30;
    var startDate = new Date(Date.parse(formDate));
    document.write('start: ' + startDate);
    var expDate = startDate;
    expDate.setDate(startDate.getDate() + interval);
    document.write('<br>expire: ' + expDate);
};
</script>

Example usage on a form input:



<input type="text" size="10" maxlength="10" id="startDate" name="startDate" onblur="setExpDate(this.value)">   

jQuery Cycle slideshow demo with next/back/paging links

This demo uses some of the advanced features of the jQuery Cycle plugin to create a mixed content slideshow (html/text/images) with a visual navigation bar, and next/back arrows

In this setup, the slideshow advances automatically, until somebody clicks one of the links, which stops the automatic action and allows the user to control the advancement of the slides. The Cycle plugin allows for pausing, resuming or stopping the slideshow with a simple click action.

See the demo (includes css/jquery code for easy reuse) http://www.gowestwebdesign.com/demos/jquery-cycle-gallery-next-back-paging/

Thanks to Mike Alsup for the versatile Cycle plugin: http://www.malsup.com/jquery/cycle/

Feel free to use the code for any purpose, and please drop me a comment or link to check out your work. As always, comments/suggestions/fixes are welcome.

More Entries

blogcfc 5.9.1.002 by raymond camden
contact michael evangelista