Modal Helper for ColdMVC

So during my spare time I have been working on a wedding site for myself and its written in a coworker's Coldfusion framework ColdMVC. Within learning the language I decided I was going to create my own custom helper for a modal window. I went with the jQuery modal library jQModal. The way I created the helper you can use whatever modal window library you want this is just one that I like. But anyways enough with that let's look at some code.

So a typical ColdMVC directory will look like this. Inside I have a Helpers folder. This folder is where you will put your CFCs that contain your helper functions. I do believe you can override the built in functions if they are the same name and function name? I am not positive but I can find out.

My modal CFC contains one function called display and this is where you would put your HTML to render your modal window. Since I went with jQModal I have had to add some certain classes that only pertain to that library. Your function might be different.

view plain print about
1<cffunction name="Display" returntype="any">
2        <cfargument name="ID" required="true" />
3        <cfargument name="URL" required="false" default="" />
4        <cfargument name="Content" required="false" default="" />
5        <cfargument name="Label" required="false" default="" />
6        <cfargument name="Title" required="false" default="Modal Window" />
7        <cfargument name="Loading" required="false" default="" />
8        
9        <cfset var html = "" />
10        
11        <cfsavecontent variable="html">
12            <cfoutput>
13            <script type="text/javascript">
14                $(document).ready(function() {
15                    $('###arguments.ID#').jqm({
16                            modal: true,
17                            trigger: 'a.modal_link#arguments.ID#'
18                            <cfif arguments.URL NEQ "">
19                                ,ajax: '#arguments.URL#'
20                                ,ajaxText: "#arguments.Loading#"
21                            </cfif>
22                    });
23                });
24            </script>
25            
26            <div id="#arguments.ID#" class="jqmWindow">
27                <div class="modal_title">#arguments.title# <div class="floatright text_right"><a href="##" class="jqmClose">Close</a></div></div>
28                <div class="text_left">
29                    <div class="modal_content content">
30                        #arguments.Content#
31                    </div>
32                </div>
33            </div>
34            <a href="##" class="modal_link#arguments.ID#">#arguments.label#</a>
35            </cfoutput>
36        </cfsavecontent>
37        
38        <cfreturn html>
39    </cffunction>

The function itself accepts an ID which is required and must be unique. This is for the fact that if you want to have multiple modal windows on your page we need them to be unique. The URL argument is used if you are doing an AJAX call. This will do a refresh every time you make a call to the modal window. The content argument is used if you want to send in content to the window by using cfsavecontent and passing the variable to the function. The label argument is used for the link. This can be modified if you want to do something different to display for the user to trigger the modal window. Title is the title of the argument. By default the window will just say "Modal Window" this is incase I forgot to include a title of course you don't HAVE to have a title, but I like it. Loading is just some HTML that I display for the AJAX calls so the user just doesn't see a blank window.

So that's the function now how do we use it? Well there are two ways I use the modal window. Well there is two different ways you can use it. First is if you want to take some content and pass it to the modal window. Here is how I do that:

view plain print about
1<cfsavecontent variable="text">
2Hello World!
3</cfsavecontent>
4
5<cfoutput>
6#$.modal.display(label="Click Me", Content=text, id="displaycontent", title="How We Met")#
7</cfoutput>

Now if you are not familiar with ColdMVC I suggest visiting: Tony Nelson's blog and read up on some of his posts explaining the ins and outs on the framework. But just for this blog I will explain that $ replaces the helper scope inside ColdMVC so you don't have to type out helpers every time. That's one way I call the modal helper. The next way is by making an AJAX request.

This way is a bit more trickier:

view plain print about
1#$.modal.display(ID="loginWindow", URL="#linkTo({controller='wedding',action='loginform'},'currentView=#cgi.path_info#')#",label="Login", loading="<div class='text_left'>Loading<marquee style='width: 1.5em;'>.....</marquee>")#

The first thing I do is use the built in ColdMVC linkTo() function to link to my controller and pass the action of loginform. Again, ColdMVC is going to know how to use that and render the correct view. The only other thing different is I pass in some HTML for loading so I can display loading to the user while the page loads. *note my best use of the marquee tag ;)* And that's pretty much it. I have some custom css for displaying the modal window and it comes out looking like this:

Example of non AJAX modal:

Example of AJAX modal:

Note I am in no way the best designer. I am sure someone could design a better window. I am up for suggestions.

Also here is a link to the jQuery plugin I used jQModal

Reverse Loop An Array of Structs

So I was trying to figure out how to loop an array of structs backwards. I found ways to loop arrays backwards but it only worked with using the reverse() function and that only works on a list of strings. Something that I was aware of until recently cfloop has a step attribute. So really it just came down like this, pretty simple:

view plain print about
1<cfloop from="#ArrayLen(ArrayofStructs)#" to="1" index="i" step="-1">
2 <cfdump var="#ArrayofStructs[i]#" abort="true" />
3</cfloop>

This is probably well known, but I wanted a reference so I can use it again later. Hope this helps someone.

Weird Coldfusion Error

So a coworker found this out if you run this test page Coldfusion will return that the cfcatch is not a struct even though when you dump the variable it says that it is a struct. Also on the argument in the function if you put a type="struct" Coldfusion will error out saying that it is not a struct. I have filed a bug here: Bug Also it turns out that it is not just a CF9 issue I have seen it as well in my local CF8 instance.

view plain print about
1<cffunction name="testFunction" output="true">
2    <cfargument name="exception" required="true"/>
3    <cfdump var="#arguments.exception#">
4    <cfdump var="#isStruct(arguments.exception)#">
5</cffunction>
6
7<cftry>
8    <cfthrow message="Help!!!!" />
9    
10    <cfcatch type="any">
11        <cfset testFunction(exception=cfcatch) />
12    </cfcatch>
13</cftry>

cfObjective(): SQLite Database Development for AIR with Raymond Camden

Ray did a good job at talking about SQLite and the basic information on SQLite. I have not used SQLite before and wasn't aware of some of it's functionality and it's limitations.

  • Features
    • Typeless
      • You can enter characters into an integer field
  • What's Missing?
    • Right outer join, full outer join
    • When altering tables only rename table and add column
    • Views are read only
    • No grant/revoke
    • No stored procedures
  • What's Missing in AIR?
    • FK Constraints
    • SQLite_Version(), Match()
  • SQLite In AIR
    • Support in both FLEX and HTML
    • Actionscript API
    • Connecting/Performing Questions/Table Analysis
    • Synchonous and Asynchronous
    • Encryption for "Sensitive" Data
  • Getting Started
    • Creating a DB
    • SQLConnection.open()
    • SQLConnection.openAsync()
    • Any filename is valid (and any extension)
    • In memory database are supported
  • Creating Tables
    • With SQL!
    • Create Table if not exists
    • Can also copy a "seed" db
    • Types: Integer, real, text, blob, null
    • Typeless: you can put text in integer
    • Column "Affinities" are used as hints
    • Affinities: Text, Numeric, Integer, real, Boolean, Date, XML, XMLList, Object, None
  • Performing Queries
    • Uses SQLStatement class
    • Speicfy SQL, Parameters, Connection, events
    • Returns a SQLResult Class
    • Contains Complete, data
  • Parameters
    • Performance, typing, security
    • Named
      • Values(:name, @rank)
    • Ordered
      • Values (?, ?)
  • Error Handling
    • Uses SQLErrorEvent Class
    • Focus on:Connection issues, sql syntax, constraint errors
  • Selecting With Class
    • Select results can be bound to ActionSCript Classes
    • Allows for Typed Results
  • Transactions
    • Gives much better performance for multiple inserts/updates
  • Paged Results
    • Allows you to paginate through large result sets
    • Stmt.execute(n)
    • Stmt.next(n)
  • Encryption
    • Uses a key for connection
    • Must be done at creation!
    • Can't change your mind...
    • Keys can be changed (reencryption())
    • Encryptions keys are bytearray (16 bytes)
  • Schema
    • Gives you access to tables, views, columns.
  • Tips
    • Using a pre-populated DB
    • Use On SQLSTatement per action
    • LITA is your friend
  • Air 2?
    • DB Transactions have save points

cfObjective(): Common Sense Approach to Object Orientated Coldfusion, 2010 Ed. with Brian Meloche

I was unsure of what to expect at this presentation. But I agreed with Brian on a lot of how Object Orientation in Coldfusion has become over complicated when developing Coldfusion is supposed to be simpler.

  • Pre-MX Coldfusion
    • Though OO Coldfusion didn't become popular until components, you could do using custom tags since CF 4 with some issues, Remember Spectra?
    • You'd typically write CF apps old school. Procedurally
    • Many CF developers still build apps this way today
    • Many more still build procedural
    • Before MX you started seeing procedural MVC promoted mostly within the FuseBox community
  • Modern OO CF
    • Mach-ii was the first modern framework written for OO CF (2003)
    • Soon
      • Model-Glue
      • Coldbox
      • Fusebox
      • Coldfusion on Wheels
    • Controller/view Based
    • Steeper learning curve
  • We need design patterns
    • As we started building model, we started seeing accepted ways to build model we need:
      • Beans
      • DAOs
      • Gateways
      • Services
      • Value Objects
      • Validators
    • As our apps got more complex, we needed more design patterns:
      • Singletons
      • Object factories
      • Dependencey injection
      • Inversion of control
      • Coldspring, Lightwire
  • OO Coldfusion
    • Coldspring both simplified code, and added additional complexities to learn
    • Models grew...we need something to manage all this data
    • ORM! Reactor, transfer
    • That's not to say that you need these frameworks to develop OO CF; all are optional.
  • Modern OO CF - The Good and the bad
    • Good:
      • Modular code
      • Separation of business logic, data & presentation
      • Easier to maintain as apps grow
      • Encapsulate logic
      • Reduces the dependences
      • Predictable way of building apps
      • Code generates: illudium, IDEs to generate CFCs CAN* help speed up development
    • Bad (in currently accepted OO CF Practices)
      • Adds a pretty steep learning curve over old school CF
      • Greatly increases the amount of code needed
      • Takes longer to develop (even with shortcuts)
      • One small change could require changes in for or five files
      • Frameworks have:
        • Performance issues
        • Instantiation Times
        • Memory Requirements
        • Some or all of above
      • Beware of code generators!
        • Tables = objects (a table is not an object)
        • Beware of anti-patterns!!! Can over complexify the model
  • Lightfront, lightfront.riaforge.org

cfObjective(): Understanding Security In Adobe Air Apps with Jason Dean

Jason Dean did a very good job on this presentation. It was VERY informational on AIR security.

  • Is Air secure?
    • Air is not a web application
    • Security is the Developer's Responsibility
  • AIR is client-side
    • 100% client-side
    • Just like a web browser
    • Traffic to server can be intercepted
    • Even if over SSL
  • Installation and Security
    • Install screen cannot be modified
    • Except for the certificate
    • Code-signing Certificate
      • Applied through a company like Versign
      • Proves that the developer is you
  • Updating
    • Ye, updating is a security concern
    • Do NOT count on your users
    • YOU need to push new security fixes / features
    • Update notifications are required
    • If you do nothing else in your first version, make sure your app is self updating.
  • File System
    • Has same permissions as the user logged in
      • Any permission to the files the user has the AIR app has as well
    • Developers should not use the file system that could harm the system.
  • File System Best Practices
    • Apply to reading and writing
    • Do not allow Dynamic paths to be set
    • Try to use user and app specific file storage
    • The Static flash.fileSystem.File class has properties for system locations
    • Sensitive data should be encrypted before placing on the file system
  • Open Files in Default Application
    • AIR 2.0 offers the ability
    • It does limits the type
      • Does not allow execute zip, terminal, app, automater, exe, url, cdm, bat, csh, com, lnk, pif, jar, and more
  • Encrypted Local Store
    • Alternative to storing data on the file system or in the db
    • Uses the OS sore
      • Keychain for OSX
      • DPAPI for Windows
      • Either KeyRIng or Kwallet for Linux
    • Stores Binary data
    • Persistent Storage but can be lost.
    • Great for small bits of data (severe performances issues at 10mb)
    • Per-user, per-application store
    • Uses 128-bit AES/CBC Encryption
  • ELS StronglyBound
    • Normally, ELS certification is bound only to publisher ID
    • The stronglyBound property allows you to more strongly bind the ELS
    • Binds to the bits of app as well
    • If the app changes, then the ELS data will be inaccessible and need to be re-created
    • This includes when the app is updated
    • Really does not offer additional security
    • Better off not using it
  • Certificate Replacement
    • Vulnerability in the ELS
    • Installed app get replaced by a copy with a different publisher certificate
    • All Data prior to replace is safe
    • All data after replacement is threatened
    • Difficult to perform this attack
  • Native Processes
    • AIR app must be packaged as a native installer
      • DMG,EXE,RPM,DEB
    • Extended Desktop profile
    • Uses the same type of code-signing certificate
    • ANY executable can be run
    • BAT files are still prohibited on Windows
    • Is any part of the dynamic statement from a third-party?
  • AIR has sandboxes
    • Used to separate content
    • Used to separate permissions that your application
  • Application Sandbox
    • Directory where the application is installed
    • Allowed full access to the AIR API
    • All subfolders and files too
    • Restricted from loading JS files from remote locations
    • Only files in the sandbox can use the local file system
    • Restricted from using code that converts string into executable code
    • Except while the page is loading.
  • Non-Application Sandboxes
    • Flash Player Security Model/Browser Model
      • Remote
      • Local-trusted
      • Local-with-network
      • Local with filesystem
    • Have NO access to the AIR API
    • Can run code that turns string into executable code
    • Some other minor restrictions to JS apply
  • Code restrictions
    • Application Sandbox
      • Eval
      • innerHTML
      • Src Attrib
      • Javascript:
      • setTimeout
      • setInterval
      • Document.write
      • XMLHTTPRequest (onload)
    • Non-Application Sandbox
      • AIR API
      • XMLHTTPRquest???
      • Window.Open()
  • Avoiding Restriction Errors
    • Map app content to a different sandbox
    • Rewrite code to not use EVAL
    • Rewrite code for setTImeout and setInterval
      • Pass in a unanymous function into settimeout
    • Rewrite JS URL syntax
  • Sandbox Bridge
    • A path for one sandbox to access properties and methods from another
    • Involves a parent and a child
    • Works both ways
    • Uses properties childSandboxBridge and parentSandBoxBridge
  • Cross-Domain Requests
    • Request to a domain other than the originator
    • AIR Apps can run on the desktop, so any request to remote resources are corss-domain
    • Flash and Flex require cross-domain.xml
    • HTML/JS apps do not.
    • Of course just like in the browser, traffic is viewable.
    • SSL will only protect from eaves droppers.
  • Inter-Application Communication
    • Two applications on the local machine to talk with each other
    • With AIR appps can be done through localConnection class
    • Allows communication between an AIR app and a SWF in browser
    • Communications between two LocalConnections(same domain) is Secure
    • Traffic between domains can be allowed using
      • AllowDoman()
      • AllowInsecureDomain() (allows non-SSL)
    • In AIR 2.0 communication between AIR app and native app can be done using Sokcets
  • Local Database
    • AIR and SQLite Security
      • By default not secure
      • Unless locked in a closet
      • Susceptible to SQL Injection
      • Unencrypted, over-writable, and accessible by other apps
      • Other apps can read contents or even all.
    • Encrypted Database
      • Prevent Snooping
        • AIR provides support for Encrypted SQLLite DBs
        • Easy to do
        • Strong Encryptions (AES-128)
        • Keeps other apps from being able to open the DB
        • Will NOT prevent them from deleting or copying the DB
      • Using an Encrypted Database
      • Encrypted DB Considerations
      • Don't hard-code the encryption key
      • Weak Password == Weak Key
      • Data in memory is unencrypted
      • Shared DBs mean shared DB key
      • Keys can be stored in the ELS
      • If the key is lost, so is the data
  • Coldfusion AIR Offline Support
    • Coldfusion 9 introduced
    • AIR Sync with CF9
  • User Input Validation
    • Validate everything
  • Code Transparacy
    • Everything can be seen
  • Best Practices
  • Sign your code
  • Validate, validate, validate
  • Understand sandboxes
  • Enable self-updating
  • Use the ELS and Encrypted DBs
  • Think wisely about sandbox bridges
  • XML signature validator
  • Use the EncyrptionKeyGenerator
  • Read the docs and try things out

cfObjective(): Speedy Websites: Through Better Front-End Optimization with Peter Farrell

The first of the sessions I attended. This session I really liked. I have never really looked at the different rules that websites can break causing pages to be slower. This session was VERY informational and probably one of my favorites. Peter Farrell did a really good job with this session. And here is the notes. Also this is just a copy paste from OneNote so I apologize for the weird icons.

  • 80% of the time a page loads is spent on HTTP request.
    • 20% is spent on back end requests like queries.
  • Tools
    • Firebug
      • Yslow
        • Developer.yahoo.com/yslow
      • Google Page speed
        • Code.google.com/speed/page-speed
  • The 34 Rules
    • It's not wise to violate rules until you know how to observe them - T.S. Elliot
    • Content RUles
      • Minimize HTTP requests
        • Reduce # of components on files
        • Combine JS files into 1 file.
        • For images use CSS sprites
        • Imagemaps
      • Reduce the # of DNS lookups
        • 20-100 seconds to do a DNS lookup
        • IE caches DNS lookups for 20 minutes.
        • Firefox caches for 1 minute
        • Too many hosts can penalize a page. Limit to 2-4 hosts per page.
      • Avoid Redirects
        • Redirects are slow
        • Browsers will NOT cache redirects
        • Trailing /s can cause penalties.
      • Make AJAX cacheable
        • Set expires header with cfhttpheader
        • Post loading components instead of pre loading
          • Drag and drop features could be post loaded
          • Photo gallery
            • Load first image instead of the rest.
        • Preloading
          • Unconditional Preload
          • Conditional Preload
          • Anticipated Preload
        • Reduce the # of DOM elements
      • Split your components across domains
        • Ex: static.google.com
      • Minimize iframes
        • If iFrame stalls out, your page stalls out
      • No 404 errors
        • Slows down user experience
        • Send back light 404 error pages
    • Server Rules
      • User a Content Delivery Network (CDN)
        • Using a CDN improved Yahoos load time by 20%
      • Add Expires or Cache-Control Header
        • Turn expire headers on specific static stuff (images)
      • Gzip Components
      • Configure Etags
        • Turn eTags on when serving one host
      • Flush Buffer Early
      • Use GET for Ajax Requests
        • POSTs are 2 step process
        • IE only allows for URLs that are 2KB long
      • Avoid Empty Image Src
        • Browsers do weird things with blank src tags
        • Makes request to the directory of current page
    • Cookie Rule
      • Reduce the size of cookie
        • When making a request all the cookies get sent
        • *.mydomain.com = bad. Be mindful of domains
        • Set expire date
      • Use Cookie-free domains
    • CSS Rules
      • Put stylesheets in the head
        • Allows for the page to load progressively
      • Avoid CSS expression
      • Choose to use XML link over at import
      • Avoid filters
        • _ filter hack
    • Javascript Rules
      • Put Javascript rules as far on the page as possible
      • Make css and js external files
        • Cacheable
      • Minify external css and js files
        • Minimize can be a 21% reduction
        • Jasmine
      • Remove duplicate script
        • IE will request a file if it finds a duplicate
      • Minimize the access to the DOM
    • Image
      • Optimize Images
      • Use CSS Sprites
      • Don't scale with HTML
        • Create thumbnail
      • Make your favicon small and cacheable
        • Under 1 Kb
        • Set an expires header

cfObjective 2010

I am currently attending this great conference. I will probably post my notes on here that I take throughout the conference.

Switching Back To CFEclipse From CFBuilder

So I have been on the private beta of CFBuilder since it was Bolt when it first went to private testing and have loved most of it. I love the Extensions, the RDS is pretty cool, and being able to manage my servers inside the IDE is pretty slick. Although I have dealt with all the performance issues between each release I do have to say that I am in love with CFBuilder. Unfortunately what has killed most of my love for Builder is the price tag. $300 is a bit much for an IDE. Especially since there are a few really good ones that are free. Now you don't get as much of the cool stuff Builder offers, but it is pretty darn close. Also, $300 is fine when you are purchasing one license and that is it. As some people know I work at a pretty big Coldfusion shop. There are probably about 50 CF developers maybe. And at $300 bucks its a bit much. Event if they could do half off that is that is still $7,500 total. I don't know, it hurts me to switch off but I think I will live.

Quick Coldfusion Shoutout: ColdMVC

So one of my co-workers has released their new framework for people to test out. ColdMVC is a pretty cool framework I have seen him present on it and seen some of the code. You can check it out at ColdMVC Available On Github

Previous Entries / More Entries

BlogCFC was created by Raymond Camden. This blog is running version 5.9.6.004. Contact Blog Owner