CFPOP – deleting an email when there is a comma in the UID

It seems that a problem has existed with the CFPOP delete action for a number of versions and it has not been fixed. The problem occurs when trying to delete a single email (or a list of emails) from the mail server where the mail server has included a comma in the UID. eg “1382396111.12731.mydomain.net,S=965″

The CF docs for the CFPOP Delete action says: “UID or a comma-separated list of UIDs to get or delete. Invalid UIDs are ignored.”

So, the abovementioned UID gets split into 2 uids (notice that it has a comma in it) and of course the email is not located so cant be deleted. CFPOP does not include a DELIMITERS parameter to use with the UID paramater which would solve the problem, I think. eg

 
<cfset myUIDlist = "1382051456.15221.mydomain.net,S=965|1382051456.18000.mydomain.net,S=966" />  
<cfpop server = "********" username = "********" password = "******** 
	action = "Delete" uid="#myUIDlist#" delimiter="|" >

Fortunately, there is a solution – use POP CFC instead of CFPOP! Thanks to Paul Vernon.

So, here is a sample page to demonstrate a way to use POP CFC.

<cfscript>
/**
 * Example of reading, processing then deleting individual emails from the pop mail server
 * using the POP CFC custom component.
 * http://popcfc.riaforge.org/
 */

	// To make it easier to rescope this example (local, variables ... whatever)
variables.s = {};

			// Initialise the custom POP CFC component. Used instead of CFPOP
			// Set your values here
s.popAccount = createObject("component", "pop").init(myPopServerHostname, myUsername, myPassword)

			// Specify a non-comma separator for the UID lists. 
			// You must do this in order for the list functionality
			// of POP CFC to work (including deletions)
s.mySeparator = "|";
s.popAccount.setProperty("separator",s.mySeparator);

			// Get an array of the UIDs of the messages in the mail account.
			// ie retrieve them from the mail server
			// This is a necessary step to solve the comma-in-uid problem
s.UIDArray = s.popAccount.getUIDList();

if (arrayLen(s.UIDArray)) {
			// Convert the array to a list
			// Keep the list to use for deletions
	s.UIDList = ArrayToList(s.UIDArray, s.mySeparator);

			// Get an array of the raw messages - one entry per UID supplied
			// This gets the raw email data from the pop server for whichever
			// emails are in the UIDList
	s.msgSrcArray = s.popAccount.GetRawMessageByUID(s.UIDList);

			// Turn the array into a query of email structures
	s.messagesQry = s.popAccount.parseRawMessage(s.msgSrcArray);

			// Loop over the array of email messages
	for( s.i=1; s.i <= s.messagesQry.recordcount; s.i=s.i+1) {

			// Process the message as you wish
			// ....
		
		writeOutput("<br/>" & s.messagesQry.subject[s.i]);


			// Now, delete this email from the server 
			// Note: you can also delete all the emails in your query 
			// in one go after the loop. See below.

			// The UID is NOT present in the messagesQry. Therefore,
			// you need to look up the UID by list position.
			// Obviously, you can also selectively delete single messages 
			// based on your criteria.

		s.uid = listGetAt(s.UIDList, s.i, s.mySeparator);
		s.popAccount.deleteMessagesByUID(s.uid);

	}

			// Uncomment to delete all messages in the list in one go, 
			// instead of one by one as above
	//s.popAccount.deleteMessagesByUID(s.UIDList);
}

</cfscript>

POP CFC has lots of other useful functions too.

Cheers,
Murray

Sublime Text – exclude / include search folders using regex

I recently switched from Eclipse to Sublime Text 3 and am very happy I did. It is fast to load, lots of extensions, active community.

One thing that I couldnt figure out was how to exclude folders from the search within files (project). I mostly code in JS (Sencha Ext/Touch) and ColdFusion and keep my JSDuck API Docs etc in the same project folder as my source files. That means that when I search within files in my project I end up with matches from the docs folder, which is not what I want. Also, and probably more importantly, when using Sencha Cmd to build production apps there is a /build folder which I do not want to search in since that is the “compiled” output.

There is a forum post about using -/my/path/to/folderToExclude (ie prefix the path with a – ). http://sublimetext.userecho.com/topic/97052-find-in-files-exclude-directories/

For Windows (which I use) you need backslashes instead of forward slashes and the syntax becomes odd (IMJ). At the end of that post was an example of using regex in the Where input box. This was a revelation.

So, to exclude the various folders within my project that I never want to search in, my where box looks like:

-*/docs/*,-*/build/*,-*/ext/*,-*/sass/*

which means search in all folders and subfolders in the project except these ones. Brilliant!

By the same method you can be specific about which folder to include. eg:

*/app/* will find a match in all “app” folders (and sub folders of course) eg myappname/app and myappname/build/app. However I want the first one but not the second one (build). So:

*/myappname/app/*

does the trick, only searching in folder (and sub folders of) myappname/app.

And, of course you can combine exclude and include:

*/myappname/app/*,-*/controller/*

ie only search in myappname/app/ but NOT in myappname/app/controller (or any sub folder with ‘controller’ in the path)

Finally, dont forget that the Where box is cached and previous contents are available by clicking the down arrow at the end of the input box. So, you can easily switch between saved search strings.

All very nifty!

ColdDuck – beautiful documentation for ColdFusion CFCs

Background

I have been a consumer of the Sencha ExtJS documentation for a while now and wanted to be able to use JSDuck for my ColdFusion CFCs. But how? While I am a JSDuck novice I figured that trying to make JSDuck produce documentation directly from ColdFusion CFCs was likely to result in tears (mine!). So, after some thought, I came up with another strategy that users of other programming languages might want to consider.

My CF to JSDuck strategy

Mark Mandel’s ColdDoc can be extended to produce different kinds of output by utilising a “strategy” cfc. It comes with one that produces the JavaDoc style HTML format. Strategies utilise the CF ComponentMetaData. So, I made my own strategy that takes ColdFusion CFCs and makes a pseudo-app in JavaScript code that is annotated using JSDuck formatting. Of course it auto-documents functions etc and picks up the ‘hint’ attributes where it finds them and uses all that to produce the raw material for rich documentation. It also works with CF ORM CFCs (although this part could be made even richer than it is at present).

Video overview

Here is a really quick video to give an overview of what ColdDuck does: http://www.screencast.com/t/5p4JqbvNR

Documentation

The ColdDuck package includes the documentation. You can also view it here http://murrah.com.au/coldduck/docs

Sample output

Here is the sample SuperBlog app documented with ColdDoc in JavaDoc format

Here is the sample SuperBlog app documented with ColdDuck in JSDuck format

A full implementation of JSDuck style documentation is here http://docs.sencha.com/extjs/4.1.3/

Almost all of that JSDuck functionality is available for you to use for your ColdFusion projects. I say “almost” because there are a few JSDuck features that are JavaScript specific (eg view JS class source).

Installation

Get it at GitHub https://github.com/murrah/ColdDuck

I hope you find this useful and fun. Please leave your comments below.

Thanks,
Murray

Solved: The CFML compiler encountered an unexpected java.lang.StringIndexOutOfBoundsException exception.

Just a quick one. I received the following error while working a a Coldfusion entity cfc.

The CFML compiler encountered an unexpected java.lang.StringIndexOutOfBoundsException exception.

The line it pointed to as the error condition had no errors in it.

It turned out the the problem was that just before the error line I had an empty comment (an artifact of testing) like /**/ ie no space between the comments “braces”. After changing it to /* */ the error is not thrown. Just in case someone else encounters this message.

Outlook 2007 – take care when switching from Exchange Server!

Our company recently switched it’s email server from Exchange Server. Not thinking, I deleted the Exchange item: Tools / Account Settings / Email / Remove. Not a good move!

Normal Outlook data files are PST files (e.g. outlook.pst). Exchange Server files are .OST files. Microsoft intentionally do not provide a way to convert an OST file to a PST file! Oh shit! There are commercial solutions and other solutions that may or may not work to convert the file.

After the panic subsided, I realised that I still had the company’s Exchange Server setup on my old laptop’s Outlook. So, I copied the OST file across to that laptop (so I had the emails that were present at the time I stopped using Exchange), fired up Outlook which told me the server was AWOL (which didnt matter), all my email and folders were there! Phew.

I then Archived ALL the folders (File / Archive, etc which copies the data to a PST file – e.g. archive.pst). I then copied the archive.pst file back to my new laptop, started Outlook and voila, all the old email was available.

So, the moral is, if you are switching from Exchange and not migrating your old email to a new mail system, ARCHIVE all your old email BEFORE you disconnect the Exchange data file from Outlook!

 

Solved: Outlook 2007 – email stuck in Outbox after switching from Exchange Server to Gmail IMAP – error 0×80040201

This took a long time to work out. As usual, someone had walked the path before me but it took a while to find that solution amongst all the false leads (in my case).

Our company had recently switched it’s email from Exchange Server to Gmail. (Yes, they are aware of the security issues. Anyway …). Not liking the GMail interface etc I wanted to continue using Outlook for my mail client and using GMail’s IMAP to do that. After setting that up (lots of posts on the net on how to do that), I noticed the following problem.

Important note: See this post BEFORE you delete your old Outlook Exchange file. If you do it the wrong way you will lose all your email!

The problem: When I created a new email to some of my contacts, or replied to an email from one of those same contacts, the email stayed in the Outbox of my default PST file. Sometimes it threw the error 0×80040201. Nothing I did would cause Outlook to send the email. Other email addresses worked fine! Very weird. Eventually I discovered the post below that explained that the problem was due to the Outlook.nk2 file that contains the data for the auto-complete functionality of Outlook. That file remembers whether the address is an Exchange Server address or an SMTP address. And guess what? All the addresses I had problems with had Exchange settings.

So, see the LAST item on this post: http://www.pcreview.co.uk/forums/getting-error-0×80040201-t1872774.html which explains a couple of fixes.

Alternatively, download this: http://www.nirsoft.net/utils/outlook_nk2_edit.html and delete all the email items with an account type of EX (as opposed to SMTP) and follow the instructions. You will then need to type the full email address the next time you send to that person and it will then remember the correct settings. Some addresses had both EX and SMTP entries so deleting the EX entries allowed the SMTP entries to correctly auto-correct.

I hope this saves someone the hours it took for me to find the solution.

NB: there is still a problem with Outlook that appears to be a bug. To get the email to actually send, you must click Send/Receive / Send ALL. I haven’t found a way for it to send automatically but at least I can send email with a couple of extra button clicks!

Now, I wonder how well Thunderbird’s IMAP works?

Cheers,

Murray

Using AlivePDF to print from AIR Javascript via ActionScript3 – part 1

See also Part 2 of this article.

As has been blogged in many places, printing from AIR is very limited and problematic. It seemed to me that a way around the lack of printing support would be to have the ability to create PDF files client-side, as opposed to sending all the data to be printed to the server then getting a PDF back again. Knowing that it was possible to invoke ActionScript classes from HTML/Javascript AIR apps, eg this post by Ray Camden and using that post as a start, I began exploring the possibilities.

This post covers what I found along the way. In summary:

  1. It is possible to create PDF files completely client-side from Javascript AIR apps via ActionsScript. A “proof of concept” is at the end of this post.
  2. You can use the free Flex SDK to develop the SWF file you need to invoke the required ActionScript classes.
  3. You can set up Eclipse to do that (ie you dont need FlexBuilder or be restricted to command line compiling)
  4. There are lots of other AS libraries out there that can be used using the techniques discussed in this post.

Until I started this process I had never really looked at ActionScript so the following is very much from the perspective of a newbie!

Basic AS info

First, read Ray’s post as a starting point.

Download the Flex 4 SDK from here. Unzip it somewhere (in my case D:\flex_sdk_4.1).

The AS library you need in your AIR app is contained in a SWF file as you can see in Ray’s post.  There are 2 ways to compile your SWF file. As Ray says, the Adobe docs suggest using the acompc command line compiler, which outputs a SWC / Zip file that you can extract the SWF from. A simpler way is to use the amxmlc command line compiler instead which outputs directly to the SWF file. Both of these compilers are in the Flex SDK /bin folder.

Ray’s example assumes you are creating an AS package from scratch. What I wanted to do was to use an existing library and extend it. Before I discuss the command line compiler settings, I need to digress into talking about the libraries I found.

AS PDF options

I found two AS libraries that create PDF files client-side – AlivePDF and purePDF. The latter interested me particularly because it is a port of iText java library which I was already familiar with. However, as discussed in my forum post here, I was unable to get purePDF to work  so I switched to AlivePDF which was more successful. It is highly likely that my problems with purePDF we of my own making. However I was unable to get any help to work out what, if anything, I was doing wrong.

Extending an AS library

The basic method is that you create a new AS package that imports the classes that you need from the library. The AS class library is in a SWC file (ie is compiled) and the Flex / AS compiler imports the classes that you need from that file.

So, the easiest way I found to do this (before I found out how to use Eclipse) is as follows. I include this info here to help explain the process.

What I did was to take the AS code from this example and converted it into the following package.

package {
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.StageScaleMode;

    import org.alivepdf.pdf.PDF;
    import org.alivepdf.saving.Method;
    import org.alivepdf.fonts. * ;
    import org.alivepdf.pages.Page;
    import org.alivepdf.display.Display;
    import org.alivepdf.layout. * ;

    import mx.utils.UIDUtil;

    import flash.filesystem.FileStream;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;

    import flash.utils.ByteArray;

    // You need to extend the Flex class Sprite for AIR to be able to run the code
    public class aliveDemo extends Sprite {
        private
        var pdf: PDF;
        private
        var file: File;

        // Removed the image to simplify the testing
        //[Embed( source="/assets/o-png24.png", mimeType="application/octet-stream" )]
        //private var pngBytes:Class;
        public function aliveDemo() {}

        public function generate(): String {
            var pdf: PDF = new PDF(Orientation.PORTRAIT, Unit.MM, Size.A4);
            pdf.setDisplayMode(Display.FULL_PAGE, Layout.SINGLE_PAGE);

            var newPage: Page = new Page(Orientation.PORTRAIT, Unit.MM, Size.A4);
            pdf.addPage(newPage);

            // The following line turned out not to work as the API had changed since the original example was posted
            // pdf.setFont(FontFamily.ARIAL , Style.NORMAL, 12);
            // The correct way to do it now is:
            var myCoreFont: IFont = new CoreFont(FontFamily.HELVETICA);
            pdf.setFont(myCoreFont, 20);

            pdf.addText("This is a sample text", 5, 15);
            pdf.drawCircle(25, 35, 15);

            pdf.addPage();
            pdf.writeText(12, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n\nPraesent vel lectus lorem. Phasellus convallis, tortor a venenatis mattis, erat mi euismod tellus, in fermentum sapien nibh sit amet urna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent tellus libero, lacinia ac egestas eget, interdum quis purus. Donec ut nisl metus, sit amet viverra turpis. Mauris ultrices dapibus lacus non ultrices. Cras elementum luctus mauris, vitae eleifend diam accumsan ut. Aliquam erat volutpat. Suspendisse placerat nibh in libero tincidunt a elementum mi vehicula. Donec lobortis magna vel nibh mollis tempor. Maecenas et elit nunc. Nam non auctor orci. Aliquam vel velit vel mi adipiscing semper in ac orci. Vestibulum commodo sem eget tortor lobortis semper. Ut sit amet sapien non velit rutrum egestas sollicitudin in elit. Fusce laoreet leo a sem mattis iaculis");

            // Removed this image for testing
            // pdf.addImageStream( new pngBytes() as ByteArray );
            // Save to file
            var fs: FileStream = new FileStream();
            file = new File("C:/CFusionMX7/wwwroot/Sites/TestAS/aliveDemo.pdf"); // Set your own path here!

            fs.open(file, FileMode.WRITE);
            var bytes: ByteArray = pdf.save(Method.LOCAL);
            fs.writeBytes(bytes);
            fs.close();

            return "End of generate";
        }

    }
}

I saved this directly to the Flex SDK /bin folder as AliveDemo.as (remember I was in quick and dirty test mode at this stage).

Then, to compile it:

  1. Create a folder in the /bin folder called alivepdflib
  2. Download the AlivePDF package (AlivePDF 0.1.5 RC.zip) and extract it
  3. Copy the AlivePDF.swc file from \AlivePDF 0.1.5 RC\Sources\bin into the alivepdflib folder created in step 1
  4. From the command line in the Flex SDK /bin folder, execute amxmlc -library-path+=alivepdflib aliveDemo.as

What that does is to create a file called aliveDemo.swf in the \bin folder by linking whatever SWC files are found in the alivepdflib folder and importing those classes into my aliveDemo.as class.

Then, I created an AIR app in Ecplise and set the HTML as follows:

<html>
    
    <head>
        <title>
            Test alivePDF
        </title>
        <script type="text/javascript" src="lib/air/AIRAliases.js"></script>
        <!--- Drop the created SWF file in the /lib folder --->
        <script src="lib/aliveDemo.swf" type="application/x-shockwave-flash"></script>
        <script>
            // Instantiate the class
            var ASlib = new window.runtime.aliveDemo();
            // Call the generate method
            var result = ASlib.generate();
            // Display the message to show we completed OK
            air.trace(result)
            // The aliveDemo.pdf will be located where ever you saved it to in aliveDemo.as
        </script>
    </head>
    
    <body>
    </body>

</html>

I copied the aliveDemo.swf file into the /bin folder in my AIR app, then ran the app and hey presto! a pdf file!!

The next step was to make a javascript wrapper so I could actually create the PDF on demand. Before that though, I set up the Flex SDK in Eclipse.

Setting up Flex 4 SDK in Eclipse

Using this very useful post as a basis, I made the following adjustments for the AIR environment:

  1. I did not bother creating the application.mxml file because the amxmlc command line compiler is actually a batch file that appends the correct xml data for compiling for AIR.
  2. In the Eclipse builder configuration section, I used the following settings instead of the ones in the post:
    1. Location= D:\flex_sdk_4.1\bin\amxmlc.bat (ie use YOUR path to the Flex SDK)
    2. Working directory=${workspace_loc:/JSPDF} (browse to YOUR project folder, mine was called JSPDF)
    3. Arguments= -library-path+=libs src/alivePDFWrapper.as -output C:/CFusionMX7/wwwroot/Sites/TestAS/lib/alivePDFWrapper.swf (set the path of the -output parameter to YOUR AIR project so that the SWF file is saved there for you)
    4. I didnt set the suggested Build Options check boxes since I didnt want the compiler to run automatically. To build, you highlight the .as file you need to compile and use CTRL+B (in windows)
  3. Copy the AlivePDF.swc file into the /libs folder in your project
  4. Copy the alivePDFWrapper.as file from Part 2 of this post to the /src folder of your project

The javascript wrapper

While it is possible to call the ActionScript methods directly, class instatiation gets tricky because the AS classes are “data types” that Javascript cant know about. My solution is to create an AS class that acts as a wrapper exposing the required methods but using data types that Javascript can handle. Since this wrapper and it’s associated JS class is the “solution” (well, so far anyway) to my problem of creating PDF files from Javascript, I have posted this section separately for those who dont care about all the above background. See Part 2