Flex DateFormatter bug, missing January 1970 month name

June 18th, 2009

Today, while working on a small piece of code I discovered something that appears to be a DateFormatter bug. I was using following DateFormatter:

private var formatter:DateFormatter = new DateFormatter();
...
 formatter.formatString = "MMMM";

to display just the month names. I didn’t really care about the year when constructing new Date so I thought I would pick 1970. It appears that for January 1970 the DateFormatter returns an empty string while for 1969, 1971 and any other dates it works fine. Here is the demo.

This movie requires Flash Player 9

And the source code below.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

 <mx:Script>
  <![CDATA[
   import mx.formatters.DateFormatter;

   [Bindable] private var names:String = "";
   private var formatter:DateFormatter = new DateFormatter();

   private function listMonths(year:Number):void {
    // get just the month name:
    formatter.formatString = "MMMM";
    // create dates and get formatted values:
    var values:Array = [];
    for ( var i:Number=0; i<12; i++ ) {
     values.push( formatter.format( new Date(year, i, 1) ) );
    }
    names = values.join(String.fromCharCode(13));
   }

  ]]>
 </mx:Script>

 <mx:HBox>
  <mx:Button label="1969" click="listMonths(1969);" />
  <mx:Button label="1970" click="listMonths(1970);" />
  <mx:Button label="1971" click="listMonths(1971);" />
 </mx:HBox>

 <mx:TextArea width="300" height="200" text="{names}" />

</mx:Application>

It appears that the bug was logged quite a few times, just one of the tickets I’ve found: https://bugs.adobe.com/jira/browse/SDK-14528. It also appears that it won’t be fixed. According to the comments under the linked story DateFormatter class is not an Adobe code. Interesting…

Flex DataGridColumn width set to the longest value of that column

June 16th, 2009

There was an interesting question on stackoverflow.com today. Some unnamed user asked:

Can we change the width of the datagrid column dynamically by clicking on the border of the column in order to display the complete string which is too long to be displayed and needs to be scrolled ? If so, How ?

Also, how can we ensure that the column width changes dynamically based on the number of characters / length of string; since many a times the data is too long to be displayed. Can we set the column width to take the length of data into consideration before displaying onto the datagrid ?

It looked like a cool practice so I thought I would give it a go. This is what I came up, it doesn’t resize columns on double click but rather automatically when data provider is set/updated.

 <?xml version="1.0" encoding="utf-8"?>
 <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
  creationComplete="onComplete();">

  <mx:Script>
   <![CDATA[
    // imports:
    import mx.events.FlexEvent;
    import mx.core.UIComponent;
    import mx.controls.dataGridClasses.DataGridColumn;
    import mx.controls.Text;
    import mx.utils.ObjectUtil;
    import mx.controls.Label;
    import mx.collections.ArrayCollection;
    // data provider:
    [Bindable] private var dp:ArrayCollection = new ArrayCollection();

    private function onComplete():void {
     // populate data provider here
     // to avoid calcMaxLengths execution when the app is created:
     dp = new ArrayCollection(
      [
       { col1: "Short", col2: "Other column 1" },
       { col1: "Some long string", col2: "Other column 2" },
       { col1: "Short", col2: "Other column 3" },
       { col1: "Short", col2: "Other column 4" },
       { col1: "The longest value in this column", col2: "Other column 5" },
       { col1: "Short", col2: "Other column 6" },
       { col1: "Short", col2: "Other column 7" }
      ]
     );
    }

    // this is going to be executed whenever the data provider changes:
    [Bindable("dataChange")]
    private function calcMaxLengths(input:ArrayCollection):ArrayCollection {
     // if there are items in the DP:
     if ( input.length > 0 ) {
      // and no SPECIAL child exists:
      if ( getChildByName("$someTempUICToRemoveAfterFinished") == null ) {
       // create new SPECIAL child
       // this is required to call measureText
       // if you use custom data grid item renderer
       // then create instance of it instead of UIComponent:
       var uic:UIComponent = new UIComponent();
       // do not show and do not mess with the sizes:
       uic.includeInLayout = false;
       uic.visible = false;
       // name it to leverage get getChildByName method:
       uic.name = "$someTempUICToRemoveAfterFinished";
       // add event listener:
       uic.addEventListener(FlexEvent.CREATION_COMPLETE, onTempUICCreated);
       // add to parent:
       addChild(uic);
      }
     }
     // return an input:
     return input;
    }

    // called when SPECIAL child is created:
    private function onTempUICCreated(event:FlexEvent):void {
     // keep the ref to the SPECIAL child:
     var renderer:UIComponent = UIComponent(event.target);
     // output - this will contain max size for each column:
     var maxLengths:Object = {};
     // temp variables:
     var key:String = "";
     var i:int=0;
     // for each item in the DP:
     for ( i=0; i<dp.length; i++ ) {
      var o:Object = dp.getItemAt(i);
      // for each key in the DP row:
      for ( key in o ) {
       // if the output doesn't have current key yet create it and set to 0:
       if ( !maxLengths.hasOwnProperty(key) ) {
        maxLengths[key] = 0;
       }
       // check if it's simple object (may cause unexpected issues for Boolean):
       if ( ObjectUtil.isSimple(o[key]) ) {
        // measure the text:
        var cellMetrics:TextLineMetrics = renderer.measureText(o[key]+"");
        // and if the width is greater than longest found up to now:
        if ( cellMetrics.width > maxLengths[key] ) {
         // set it as the longest one:
         maxLengths[key] = cellMetrics.width;
        }
       }
      }
     }

     // apply column sizes:
     for ( key in maxLengths ) {
      for ( i=0; i<dg.columnCount; i++ ) {
       // if the column actually exists:
       if ( DataGridColumn(dg.columns[i]).dataField == key ) {
        // set size + some constant margin
        DataGridColumn(dg.columns[i]).width = Number(maxLengths[key]) + 12;
       }
      }
     }
     // cleanup:
     removeChild(getChildByName("$someTempUICToRemoveAfterFinished"));
    }

   ]]>
  </mx:Script>

  <mx:DataGrid id="dg" horizontalScrollPolicy="on" dataProvider="{calcMaxLengths(dp)}" width="400">
   <mx:columns>
    <mx:DataGridColumn dataField="col1" width="40" />
    <mx:DataGridColumn dataField="col2" width="100" />
   </mx:columns>
  </mx:DataGrid>

 </mx:WindowedApplication>

Sample:

This movie requires Flash Player 9

This code works just fine however it may be not efficient enough when applied to large data providers.

Source code is also available on stackoverflow.com under the original entry.

XMLSocket.send / Socket.writeUTFBytes doesn’t work?

June 11th, 2009

Disclamer
In first words – no, of course it is not broken, it is working fine. But there is a specific issue with these two methods when the socket server is implemented incorrectly. I noticed I’ve been looking for the solution using these phrases and that’s why the post it titled like that.

I just finished writing an ActionScript 3 SWC library which is going to be used with Flex and Flash applications. The library uses Socket connection to provide some statistical information to the Java socket server. As part of the project I had to create simple socket server which simply writes what it gets to the standard output.

The code was working fine when running in Flex Builder debugger. However, as soon as I started the test application in the Flash IDE I found following problem:

  • SWF was requesting policy file
  • my Java socket server was serving policy file
  • SWF was showing that it was connected
  • any other messages sent to the socket were not coming through

Exactly the same problem appeared when I deployed Flex version on the external server. It worked while running in the debugger but not from the browser. So it was clearly something wrong with the socket server. Once the policy file was served any other communication wasn’t working. My socket server looked like this:

package uk.co.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketTest {
 public static void main(String[] args) throws Exception {
  System.out.println("Starting...");
  start();
 }
 public static void start() throws Exception {
  // create socket server
  ServerSocket ss = new ServerSocket(1234);
  for (;;) {

   System.out.println("Waiting for the client.");
   Socket cs = ss.accept();
   System.out.println("Connection...");

   InputStream in = cs.getInputStream();
   OutputStream out = cs.getOutputStream();
   boolean isConnected = true;
   StringBuffer soFar = new StringBuffer();
   byte b;

   while (isConnected) {
    // let it rest a bit:
    Thread.sleep(10);
    // read everything what's coming in:
    while ( (b = (byte)in.read()) > -1 ) {
     if ( b == 0 ) {
      // zero byte, process:
      String value = soFar.toString();
      // get the value
      if ( value.equals("<policy-file-request/>") ) {
       // policy file requested, sent the policy back:
       System.out.println("Policy file request.");
       String crossdomain = "<?xml version=\"1.0\"?>";
       crossdomain += "<cross-domain-policy>";
       crossdomain += "<allow-access-from domain=\"*\" to-ports=\"*\" secure=\"false\" />";
       crossdomain += "</cross-domain-policy>";
       out.write(crossdomain.getBytes());
       out.write((byte)0);
       out.flush();
       System.out.println("Policy file sent.");

      } else {

       if ( value.equals("exit") ) {
        // if exit command received, finish:
        isConnected = false;
       } else {
        // just output the message:
        System.out.println(value);
       }

      }
      soFar.setLength(0);
     } else {
      // append the character to the buffer:
      byte[] buf = new byte[1];
      buf[0] = b;
      soFar.append( new String(buf) );
     }
    }
   }
  }
 }
}

While looking for the solution I found the following article: Setting up a socket policy file server. Peleus Uhley from Adobe describes how to use policy files effectively. In What data is sent in the request and response? section of the article there is a solution..

Once Flash Player receives the socket policy file, it closes the connection and opens a new connection if the policy file approves the request.

Looking at the above socket server code I could now clearly see what’s wrong. Once the connection is accepted no other connections are coming in until the first client sends exit message. So I modified my socket server, here it is:

SocketTest.java

package uk.co.test;

import java.net.ServerSocket;
import java.net.Socket;

public class SocketTest {

 public static void main(String[] args) throws Exception {
  System.out.println("Starting...");
  start();
 }

 public static void start() throws Exception {
  // create socket:
  ServerSocket ss = new ServerSocket(1234);
  for (;;) {
   System.out.println("Waiting for the client.");
   Socket cs = ss.accept();
   System.out.println("Connection...");
   // create socket connection handler and run it in separate thread:
   new SocketHandler(cs);
  }
 }
}

SocketHandler.java

package uk.co.test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketHandler
implements Runnable {

 private Socket _client;

 public SocketHandler(Socket s) {
  _client = s;
  // create new thread from this instance and start it:
  Thread t = new Thread(this);
  t.start();
 }

 public void run() {
  try {
   // get client in/out:
   InputStream in = _client.getInputStream();
   OutputStream out = _client.getOutputStream();
   boolean isConnected = true;
   StringBuffer soFar = new StringBuffer();
   byte b;

   while (isConnected) {
    // let it rest a bit:
    Thread.sleep(10);
    // read everything coming in:
    while ( (b = (byte)in.read()) > -1 ) {
     if ( b == 0 ) {
      // zero byte, process what already came in:
      String value = soFar.toString();
      if ( value.equals("<policy-file-request/>") ) {
       // policy file requested, send it to the client:
       System.out.println("Policy file request.");
       String crossdomain = "<?xml version=\"1.0\"?>";
       crossdomain += "<cross-domain-policy>";
       crossdomain += "<allow-access-from domain=\"*\" to-ports=\"*\" secure=\"false\" />";
       crossdomain += "</cross-domain-policy>";
       out.write(crossdomain.getBytes());
       out.write((byte)0);
       out.flush();
       System.out.println("Policy file sent.");

      } else {

       if ( value.equals("exit") ) {
        // exit command received, exit then...
        isConnected = false;
       } else {
        // just print the message to the stdout:
        System.out.println(value);
       }

      }
      soFar.setLength(0);
     } else {
      // append the char to the buffer:
      byte[] buf = new byte[1];
      buf[0] = b;
      soFar.append( new String(buf) );
     }
    }
   }
  } catch (Exception e) {
   // ignore
  }
 }
}

The second socket server fixed the problem. It is working for connections with and without policy requests, from Flash IDE, Flex Builder and the browser.

It took me 5 hours to figure out the solution (process client connections in separate threads) so if you’re in the same situation as I was I hope this post helps you.

Google Wave – Microsoft OneNote anyone?

June 1st, 2009

Right… just before SotR09 London I can’t get sleep. I just watched the Google Wave recording from Google I/O. After 5 minutes I had this feeling I’ve seen it somewhere already…, think, think! And BING ;) It was Microsoft OneNote.

All that real-time typing capabilities, dropping images, commenting is already in OneNote. Until I see and "touch" Wave I claim – Wave is OneNote on steroids. Is it going to be successful? I really don’t know, probably yes. I’m just not sure if I really want Google to know everything about me, where I go, what do I do in my spare time, what do I work on.

Why crossdomain.xml is even more than a good thing

May 22nd, 2009

For a long time I couldn’t really understand what crossdomain.xml is for. Today, after finishing one the Flex projects I finally figured it out. At least one of two reasons. About 4 years ago Martijn de Visser described one of them – defending your internal network from the attacks. But there is another way reason why crossdomain.xml is good.

Let’s say I’m developing some smart module and I let people download and load it from their domains but there are some specific sites that I want to prohibit. I’m going to use this very simple module to demonstrate how this can be achieved.

<?xml version="1.0"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%">
 <mx:Label text="I'm the protected module" />
</mx:Module>

Suppose that I let http://www.friend1.com and http://www.friend2.com use it but http://www.pron.com shouldn’t be allowed. When I modify the code a bit I will use Flash Player sandboxing to do so.

<?xml version="1.0"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" width="100%" height="100%"
 creationComplete="onCreated();">
 <mx:Script>
  <![CDATA[

   import flash.net.URLRequest;
   import flash.net.URLLoader;
   import flash.events.SecurityErrorEvent;
   import flash.events.Event;
   import flash.events.IOErrorEvent;
   import flash.external.ExternalInterface;

   private function onCreated():void {
    var url:URLRequest = new URLRequest();
    url.url = "http://www.mymodulesfactory.com/check.cfm"
    var loader:URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, onComplete);
    loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
    // this one really doesn't matter
    // I'm catching it so the error is not visible
    // in the debug player if the user uses it and check.cfm doesn't exist
    // check.cfm does not have to exist
    loader.addEventListener(IOErrorEvent.IO_ERROR, onComplete);
    loader.load(url);
   }
   private function onComplete(event:Event):void {
    // everything is fine, I am allowed to access the domain, ignore
   }
   private function onSecurityError(event:SecurityErrorEvent):void {
    ExternalInterface.call(
     "f = function() { alert('you are not allowed to use this extension');"
     + "top.location.href='http://www.mymodulesfactory.com/license.cfm'; }"
    );
   }
  ]]>
 </mx:Script>
 <mx:Label text="I'm the protected module" />
</mx:Module>

Next, I have to create following crossdomain.xml file:

<cross-domain-policy
 xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFile.xsd">
 <allow-access-from domain="friend1.com"/>
 <allow-access-from domain="friend2.com"/>
 <!-- any other friends I like to add in the future go here -->
</cross-domain-policy>

The extended example in the conjunction with the above policy file protects this module from being used by the http://www.pron.com. When the module is created it simply calls home, policy file is returned and the module checks if the domain from which it is being used is allowed. Because http://www.pron.com is not on the list SecurityErrorEvent is fired and browser’s alert message pops up. Once the user clicks OK button he will be redirected to the module’s license. This is just a prototype but it should be quite solid.

I’ve created this code outside the IDE so it may have some bugs.

This approach should be very easy to apply in Silverlight as well.

Adobe and feeds.adobe.com team, please accept my apology

May 17th, 2009

It’s been a long time since I last blogged, I’ve been on holiday and following week was kind of busy. It turned out that in my last post, Thank you Adobe for removing me from feeds.adobe.com, I accused Adobe/feeds.adobe.com team of doing something that never happened. As johnb and Big Mad Kev pointed out the situation was caused by a failure in feeds.adobe.com system.

Previous post is totally my fault, I should have ask what happened before writing my post. It is a lesson for the future. I’m leaving that unfortunate post on my blog but I updated it with the explanation and link to this post.

Thank you Adobe for removing me from feeds.adobe.com

May 1st, 2009

Update: it turned out that removal of my blog from feeds.adobe.com was caused by a failure of the site’s database. I have published a blog post Adobe and feeds.adobe.com team, please accept my apology explaining what exactly happened.

I have to say I am really disappointed with this move. I really did not expected that. About a week ago my blog was approved for feeds.adobe.com. I just checked, when I try to ping my blog from here I see:

Adobe Feeds is not currently aggregating this site. If you would like your site to be added, use the Adobe Feeds Feed Submission Form to submit it for approval.

Now the question is, is this because of this post? I expected to be a persona non-grata in the ColdFusion community because of what I have been saying in the past. But that?! After Ben Forta answered my question with the statement that is now quoted all over the internet I asked:

Is this an official statement?

The answer was short: Yes. So what happened to the don’t kill the messenger rule?

Windows 7 Release Candidate – first look

May 1st, 2009

Today I got my hands on fresh Windows 7 RC so I decided to give it a shot. I installed it on VirtualBox 2.2, VM with 1GB of RAM and I have to admit, I am impressed.

There is no visible changes in the UI, the only thing that’s changed is the installer, it is really nice, much nicer than any previous installer. But here is the thing, I couldn’t really enjoy it too long. Installation took only 22 minutes. I wanted to see how quick it is on the boot time. Fresh start, with login screen, 47 seconds… The interface is responsive straight away. That is very good result for Windows running on only 1GB of RAM. I would love to see it on a physical machine.

First impression – I like it. It feels like it is ready to rock. If I just wasn’t in love with Ubuntu… :)

Vote for Flex Builder for Linux

April 28th, 2009

Tom Chiverton has logged a support request in Adobe JIRA for Flex Builder for Linux. Quick recap – a week ago Ben Forta being asked what is the status of Flex Builder for Linux answered: the project is currently on hold. There is not enough requisition for the product to continue its development.

Developers want Flex Builder for Linux! Show your support, vote for it: http://bugs.adobe.com/jira/browse/FB-19053!

More information:

Configuring postfix as a relay for GMail

April 27th, 2009

For the domain this blog is running on I have a separate GMail account, I wanted my server to relay all email there. I was searching quite a lot for detailed info on how to set up postfix correctly but could not find any. All information was scattered across different blogs, websites, forums. I just achieved the target and I thought I will share what I just learned.

All command below were executed under the root account. If an account used is not root use sudo and make sure it is a sudoer.

Confirm that the openssl is installed and if not, install it (on my Ubuntu 8.10 I had it installed by default). If CA certificate was not generated before it is time to do it. On Ubuntu it is nothing else than running following command from the terminal:

/usr/share/ssl/misc/CA.sh -newca

If an error is returned it may suggest that the CA.sh script is somewhere else. To find it simply execute following:

find / -name 'CA.sh'

and run the first command again with correct CA.sh path. While generating CA certificate the script will ask some questions, just follow the instructions, it is really short and painless process.

The next step is to install postfix.

apt-get install postfix

Answer the questions using default options, it appears that in most cases they are fine. Just make sure first question is answered with Satellite system option.

To make sure this process is going to work postfix must be configured with SASL and TLS support and on Ubuntu it was by default, indeed. It can be verified with following command:

ldd /usr/lib/postfix/smtp

Look for the line starting with the libssl. I bet it will be there. BUT if not, postfix must be reconfigured with SASL and TLS. Here is just one of the articles of many I found showing how to do it: Setup Email Services on Ubuntu Using Postfix (TLS+SASL).

Once postfix is running:

cd /etc/postfix
mkdir certs
cd certs
openssl genrsa -out itchy.key 1024
openssl req -new -key itchy.key -out itchy.csr
openssl ca -out itchy.pem -infiles itchy.csr
nano main.cf

To search for the string in nano use CTRL+W. Look for myhostname key. I have a mx.gruchalski.com value but gruchalski.com would work just fine. Next important bit is mydestination key. I have changed it to smtp.gmail.com and I will explain why in a second. Last key to change is the relayhost. Set it to [smtp.gmail.com]:587. At the end of the file add following lines:

# auth
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps=hash:/etc/postfix/sasl_passwd

# tls
smtp_use_tls=yes
smtp_sasl_security_options=noanonymous
smtp_sasl_tls_security_options=noanonymous
smtp_tls_note_starttls_offer=yes
tls_random_source=dev:/dev/urandom
smtp_tls_scert_verifydepth=5
smtp_tls_key_file=/etc/postfix/certs/itchy.key
smtp_tls_cert_file=/etc/postfix/certs/itchy.pem
smtpd_tls_ask_ccert=yes
smtpd_tls_req_ccert=no
smtp_tls_enforce_peername=no

CTRL+O to save and CTRL+X to exit.

At this point /etc/postfix/sasl_passwd file does not exist yet, so:

nano /etc/postfix/sasl_passwd

Add these two files:

gmail-smtp.l.google.com user@gmail.com:password
smtp.gmail.com user@gmail.com:password

Make sure that the correct credentials are set. Save, exit the file and execute:

[source lang-'bash']
postmap /etc/postfix/sasl_passwd
/etc/init.d/postfix reload
apt-get install mailutils
[/source]

It is time to test postfix, that is why I installed mailutils.

echo "Testing relay from terminal" | mail -s "Test relay" to@email -f from@email

Well, the -f option is not going to work here anyway but it does not brake anything either :) If an email did not arrived please check /var/log/mail.log for details.

And now an explanation why mydestination key was changed. Let’s say my server name is funkyserver.com and from the terminal or Apache web server I am sending an email to d’oh@funkyserver.com. But I have a d’oh user on the server as well. Postfix is going to think oh, hang on mate, my name is funkyserver.com and you are sending an email to the user who BELONGS TO ME! I am so smart, I am not going to send it via GMail, I will just drop it to the /var/mail/d’oh mailbox!. That email will not appear in GMail. By changing mydestination I am telling postfix do not try to be smart dude, just send it to the outside world and let the others make the decision what to do with it.

The last thing to make sure is that the correct real name for the www-data account (used by Apache) is set. When a sent email is received it will have www-data-real-name <gmail@email> in the from field. By Changing it to Wordpress for example, recipients will see it as Wordpress <gmail@email> and not www-data <gmail@email>.

What about iptables and security? To make sure no one is going to use postfix as an open relay if it is incorrectly configured, just execute:

iptables -I INPUT -p tcp --dport 110 -i eth0 -j DROP

and save iptables rules.