Categories
Flex How to

How to dynamically add attributes and child nodes to an XML element in Flex

This is how I copied all the attributes of an XML node (srcXMLNode) to another XML node (dstXMLNode) in Flex, without knowing the names of those attributes:

for each(var attr:XML in srcXMLNode.attributes())
{
dstXMLNode.@[attr.name()] = attr;
}

And this is the way I added child nodes of an XML element to another:

for each(var elem:XML in srcXMLNode.elements())
{
dstXMLNode[elem.name()] = elem;
}

If you know a better way to do this, feel free to write a comment.

Categories
PHP

The attachment of an email sent via PHP has 0 bytes

I wanted to send an email that only contained an attachment as follows:

$headers  = "MIME-Version: 1.0\r\n";
$headers .= "To: <".$to_email.">\r\n";
$headers .= "From: ".$from_name." <".$from_email.">";
$random_hash = md5(date('r', time()));
// add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
// read the atachment file contents from a string previously formed,
// encode it with MIME base64,
// and split it into smaller chunks
$attachment = chunk_split(base64_encode($content));
// construct the body of the message
$message = "--PHP-mixed-".$random_hash;
// my attachment was an html file
$message .= "\r\nContent-Type: text/html; name=\"".$filename."\"";
$message .= "\r\nContent-Transfer-Encoding: base64";
$message .= "\r\nContent-Disposition: attachment\r\n".$attachment."\r\n";
$message .= "\r\n--PHP-mixed-".$random_hash."--";
// Windows
ini_set('sendmail_from', $return_email);
mail($to_email, addslashes($subject), $message, $headers);
ini_restore('sendmail_from');
// Linux
// mail($to_email, addslashes($subject), $message, $headers, "-r ".$return_email);

I received an email with an attachment, but the problem was that the attached file had 0 bytes.
To my surprise, after comparing the source of the email with the source of an email with a complete attachment, I found out the problem: before the actual content of the attachment ($attachment) there should be an empty line.
I replaced the line of code:

$message .= "\r\nContent-Disposition: attachment\r\n".$attachment."\r\n";

with:

$message .= "\r\nContent-Disposition: attachment\r\n\r\n".$attachment."\r\n"; // notice the double \r\n

and it worked! This way I received the email with the correct attachment.

Categories
MySQL

#1005 – Can’t create table

Full error message: #1005 – Can’t create table ‘.\my_db\#sql-7c4_444.frm’.

Using MySQL version 4.1.22-community-nt, I created two tables (`table1` and `table2`) in a database (let’s call it `my_db`) as follows:

CREATE TABLE `table1` (
`idtable1` int(10) unsigned NOT NULL auto_increment,
`table1_str` varchar(50) NOT NULL default '',
PRIMARY KEY  (`idtable1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `table2` (
`idtable2` int(10) unsigned NOT NULL auto_increment,
`idtable1_fk` int(10) NOT NULL,
`table2_str` varchar(50) NOT NULL default '',
PRIMARY KEY  (`idtable2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Then I tried to add a foreign key constraint like this:

ALTER TABLE `table2`
ADD CONSTRAINT `table2_ibfk_1` FOREIGN KEY (`idtable1_fk`) REFERENCES `table1` (`idtable1`) ON DELETE CASCADE ON UPDATE CASCADE;

And then I got the error.

The solution in my case was adding the unsigned attribute to the `idtable1_fk` field in `table2` for having the same type as the field `idtable1` it references in `table1`:

ALTER TABLE `table2` CHANGE `idtable1_fk` `idtable1_fk` int(10) unsigned NOT NULL;

After that I ran the foreign key constraint query:

ALTER TABLE `table2`
ADD CONSTRAINT `table2_ibfk_1` FOREIGN KEY (`idtable1_fk`) REFERENCES `table1` (`idtable1`) ON DELETE CASCADE ON UPDATE CASCADE;

And then it worked. But if you don’t have the same problem but you get the same error message you might already have a foreign key constraint with the given name. For example, if I run again the foreign key constraint query I will get the same error. Be careful if you use phpMyAdmin as a visual interface for MySQL, because it seems to me that it does not show us all the foreign key constraints we added to a table. If you want to see which foreign key constraints a table has, you could export the structure of that table and analyze the foreign key constraints queri(es).

Hope this works for you, too.

Conclusion: We should make sure that the possible values of the foreign key field are in the same range as the possible values of the field referenced by that foreign key and that there is no foreign key constraint with the same name as the constraint we are trying to add.

Categories
How to

How to uninstall Google Toolbar for Firefox

Problem: Because I did not use Google Toolbar (it was automatically installed when I installed Firefox), I decided to uninstall it. I selected the Uninstall option in Tools -> Add-ons -> Google Toolbar in Firefox (Disable option being grayed) and it said that the toolbar will be uninstalled the next time Firefox will restart. So I closed and started Firefox again and I got a popop window that said something like thanks for installing Google Toolbar and if I want to see the page rank for every site I visit etc. This window kept appearing until I agreed installing Google Toolbar. I also tried uninstalling the toolbar using its uninstall setting, but I kept getting the same (reversed) result.
Everytime I closed the Firefox browser window I got sure that the procees was closed (no instances of FF remained opened).
My operating system is Windows XP Professional.

The solution that worked for me consists of two simple steps:
1. I uninstalled Google Toolbar for Internet Explorer using Control Panel -> Add/Remove programs.
2. I pressed Disable (not grayed anymore) and then Uninstall buttons for Google Toolbar in Firefox Tools -> Add-ons and restarted Firefox.

And it worked! No annoying popop window anymore.

Categories
HTML

Problem: When submitting a form, seems like another form gets submitted

Actually, I had two forms on the same page, one with the GET method (let’s call it get_form), the other with the POST method (we’ll call it post_form). When I pressed the submit button of get_form it seemed that the post_form got submitted. In fact, all the variables in get_form and post_form were passed with the POST method.

So the natural thing that came into my mind was that the two forms were intersecting. But how? I knew for sure they were separate forms because get_form was in a file that I was including in the file that contained post_form, after post_form.

After verifying the HTML source over and over again I finally solved the mistery. There was a stupid mistake I made: I did not close post_form properly. Instead of using the form closing tag </form> at the end of post_form, i put the form opening tag <form> and every time I checked for the problem, I missed an important detail: the lack of the slash sign.

Conclusion: When opening a HTML element, make sure to close it accordingly.

Categories
Apache Web Server How to PHP Tutorial

How to receive a failure notice when the recipient cannot be reached after sending an email using the PHP mail() function

I could not receive a failure notice when sending email to an email address that does not exist ($to_address), using this code:

$subject = "Email subject";
$message = "line1\r\nline2\r\nline3";
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "To: <$to_email>\r\n";
$headers .= "From: Me <$my_email_address>\r\n";
$headers .= "Return-Path: <$my_return_email_address>r\n";
mail($to_email, $subject, $message, $headers);

The problem was that the email address I wanted to receive the failure notices to ($my_return_email_address) was not the same as the value of the configuration option sendmail_from in the php.ini file (Apache web server installed on a machine with the Windows Professional operating system). So the failure notices were sent to the sendmail_from email address if this was an existing address, instead of the email address specified in the Return-path header of the email.

The solution is replacing the lines:

$headers .= "Return-Path: <$my_return_email_address>r\n";
mail($to_email, $subject, $message, $headers);

with:

// when the PHP server runs on Windows
ini_set(sendmail_from, $my_return_email_address);
mail($to_email, $subject, $message, $headers);
ini_restore(sendmail_from);
// when the PHP server runs on UNIX
mail($to_email, addslashes($subject), $message, $headers, "-r $my_return_email_address");

This means that, before sending the email, we set the value of the sendmail_from configuration option to $my_return_email_address and we restore the default value of the configuration option after the email is sent.

Categories
How to HTML JavaScript Tutorial

How to check/uncheck a bunch of checkboxes without using ids for the checkbox inputs

My solution of checking/unchecking a group of HTML checkboxes using Javascript implies using an array of checkboxes, which means naming all the inputs of type ‘checkbox’ like array_name[]. Example:

<form name="cb_form">
<input type="checkbox" name="cb[]" value="0" />Zero
<input type="checkbox" name="cb[]" value="1" />One
<input type="checkbox" name="cb[]" value="2" />Two
<input type="checkbox" name="cb[]" value="3" />Three
</form>

In this example, the name of the checkboxes array is cb.

Next, we place two links for checking/unchecking all checkboxes in our array. If someone clicks one of these links, the checkAll() JavaScript function is called:

<a href="" onclick="checkAll('cb_form', 'cb[]', true); return false;">Check all<a>
<a href="" onclick="checkAll('cb_form', 'cb[]', false); return false;">Uncheck all<a>

The checking/unchecking all checkboxes function in JavaScipt looks like this:

function checkAll(form_name, cb_name, value)
{
var cb_arr = document.forms[form_name].elements[cb_name];
// if the checkboxes exist
if(cb_arr)
{
// if the number of checkboxes is at least 2
if(cb_arr.length > 1)
{
// for each checkbox
for(i = 0; i < cb_arr.length; i++)
{
// check (value == true) or uncheck (value == false) it
cb_arr[i].checked = value;
}
}
else // cb_arr.length is undefined which means there is a single checkbox element that is not considered an array of one element
{
cb_arr.checked = value;
}
}
}

Note that if we only have one checkbox, the variable cb it is not considered an array, but a normal variable. This is useful in the situation of dinamically generated HTML pages (using PHP, for example) and the number of checkboxes varies from page to page.

You can test the example here:

Zero One Two Three

Check all Uncheck all

Categories
PHP

Warning: mail(): SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in path_to_php_file on line #

Full error message: Warning: mail(): SMTP server response: 451 See http://pobox.com/~djb/docs/smtplf.html. in path_to_php_file on line #

This is an error message that I got lots of times and it was always the same problem. So I decided to write here the solution for the next time I encounter it and I thought it might also help other people.

So I tried to send an email in plain text using the PHP function mail() :

// consider this being an existing email address
$to_address = "abc@def.com";
$subject = "Email subject";
$message = "line1
line2
line3";
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "To: <".$to_email.">\r\n";
$headers .= "From: Me <".$my_email_address.">\r\n";
mail($to_email, $subject, $message, $headers);

It worked fine with Apache server running on Linux operating system, but I got the error message mentioned before with the server running on Windows.
It looks like while Unix-based systems recognize \n character (the equivalent in PHP of LF – line feed) as a newline even when sending emails, Windows systems are stricter in comunicating using some textual Internet Protocols (such as SMTP) that mandate the line terminator to be the ASCII CR+LF (carriage return + line feed) sequence, which is abstracted in PHP to \r\n character sequence.

So the problem was the $message variable. The correct way to assign the multiple lines value to it is:

$message = "line1\r\nline2\r\nline3";  // separate the lines with \r\n
// or,  elegantly:
$message = "line1\r\n";
$message .= "line2\r\n";
$message .= "line3";

And now it works on Windows, too.

Categories
Hibernate Java MySQL

org.hibernate.HibernateException: identifier of an instance of members.Appointment was altered from 8 to 8

Full error message:

Exception occurred during event dispatching:
org.hibernate.HibernateException: identifier of an instance of members.Appointment was altered from 8 to 8
at org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:58)
at org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:157)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:113)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:196)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at members.AppointmentDialog.jButtonSaveActionPerformed(AppointmentDialog.java:279)
at members.AppointmentDialog.access$000(AppointmentDialog.java:21)
at members.AppointmentDialog$1.actionPerformed(AppointmentDialog.java:101)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:5517)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:153)
at java.awt.Dialog$1.run(Dialog.java:535)
at java.awt.Dialog$2.run(Dialog.java:563)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Dialog.show(Dialog.java:561)
at java.awt.Component.show(Component.java:1302)
at java.awt.Component.setVisible(Component.java:1255)
at admin.AdminOptionsForm.jButtonSetAppointmentActionPerformed(AdminOptionsForm.java:238)
at admin.AdminOptionsForm.access$800(AdminOptionsForm.java:24)
at admin.AdminOptionsForm$9.actionPerformed(AdminOptionsForm.java:145)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:5517)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

In Java, I had a class Appointment mapped to a MySQL table `appointment` using Hibernate as follows:

<hibernate-mapping>
<class name="members.Appointment" table="appointment">
<id name="idAppointment" column="idappointment" type="short">
<generator class="native"/>
</id>
<many-to-one name="member" column="idmember" not-null="true" foreign-key="fk_idmember"/>
<property name="startDate" type="timestamp" column="start_date"/>
<property name="duration" type="short" column="duration" length="3"/>
<property name="cancelled" type="boolean"/>
</class>
</hibernate-mapping>

I was getting the error when inserting a new appointment into the database.

The problem was that the idAppointment member variable in the Java class and the idappointment field in the MySQL database table were of the type int. So why the hell did I have the type short in the mapping? The answer is simple: because of the copy paste. So the correct code is:

<id name="idAppointment" column="idappointment">
<generator class="native"/>
</id>

Conclusion: copy paste is sometimes evil.

Categories
Hibernate Java MySQL

java.sql.SQLException: Cannot convert value ‘0000-00-00 00:00:00’ from column 9 to TIMESTAMP

Full error message:

Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute query
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2223)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
at org.hibernate.loader.Loader.list(Loader.java:2099)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at admin.MembersTableModel.<init>(MembersTableModel.java:43)
at admin.AdminOptionsForm.initComponents(AdminOptionsForm.java:98)
at admin.AdminOptionsForm.<init>(AdminOptionsForm.java:32)
at managemembers.Main.main(Main.java:45)
Caused by: java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 9 to TIMESTAMP.
at com.mysql.jdbc.ResultSet.getTimestampFromBytes(ResultSet.java:6864)
at com.mysql.jdbc.ResultSet.getTimestampInternal(ResultSet.java:6899)
at com.mysql.jdbc.ResultSet.getTimestamp(ResultSet.java:6218)
at com.mysql.jdbc.ResultSet.getTimestamp(ResultSet.java:6256)
at com.mchange.v2.c3p0.impl.NewProxyResultSet.getTimestamp(NewProxyResultSet.java:3394)
at org.hibernate.type.TimestampType.get(TimestampType.java:30)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:154)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:81)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2096)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1380)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1308)
at org.hibernate.loader.Loader.getRow(Loader.java:1206)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:580)
at org.hibernate.loader.Loader.doQuery(Loader.java:701)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)
... 11 more

My example:

// the Java class

public class Member  {
// some private member attributes
private Date addedDate;
// proper getter and setter methods
}

<!– the Hibernate mapping–>

<hibernate-mapping>
<class name="managemembers.Member" table="member">
<!-- some mappings here-->
<property name="addedDate" type="timestamp" column="added_date"/>
</class>
</hibernate-mapping>

# The MySQL table

CREATE TABLE `member` (
# some fields here
`added_date` DATETIME,
) ;

So I was mapping a java.util.Date field in the POJO to a MySQL DATETIME field.

The error occured while I was trying to retrieve the data from the member database table.

The problem was that I had DATETIME values in the database with all-zero components (0000-00-00 …), so the solution was to set all the added_date field values with all-zero components to NULL and to be careful to set a valid DATETIME value or NULL into the added_date field each time I inserted a new row.

Conclusion: You have 2 choices: either set the date field in the table to a NULL value either set it to a valid date.