Monday, April 13, 2009

Making File Uploads Work in IE6 and 7

So, I'm developing a web application at home with Linux OS and Firefox web browser. Then I deploy it on a Windows OS and a IE Web Browser.

...

Yeah I know how dumb and risky it sounds, problem is I can't afford a new computer right now, so I use Ubuntu 8.10 for developing, and the target server for my developed web app is Windows.

You know cross-browser compatibility is always a headache, and this it's all true for File Uploads.

I use PHP, and for some reason, the file upload feature wouldn't work in IE Browser. WHYYYY!!

I spent almost 3 hours on forums and finally found the reason: ENCTYPE. All file upload features warn you: You have to change your form enctype attribute to "multipart/form-data" in order that the file input contents can travel through the request.

Well... I DO! SO WHAT'S WROONG?!!

As I use an admin page with header, left navigation pane and content areas, I use the same form for several different features. And I have a feature which uploads files.

Hence, I dynamically change the ENCTYPE attribute through javascript. And after hours of trying to explain myself "why in the world is this not working if I'm doing everything right", and just before I start blaming the elves or believing I was coursed, I found this page: http://www.talkphp.com/javascript-ajax-e4x/1176-form-enctype-internet-explorer.html

It turns to be that for Internet Explorer, the W3C STANDARD enctype attribute is NOT ENOUGH. I have to set this particular ENCODING attribute as well, so my code ended up like this:

form.enctype = "multipart/form-data";
form.encoding = "multipart/form-data";
form.submit();

Yeah, I addded the form.encoding=... line and it worked perfectly.

Thanks Wildhoney @ talkphp forum!

Now I am compelled to spread the words of wisdom to all you programmers that have lost hope. No, you're not cursed, you just didn't know.

PS. Yes, my writing style today is a little bit crazy, that's what's left of an stressed mind after 3 hours of trying to find a logical reason to an error that shouldn't be there in the first time. Now I'll take some rest and no more coffee for me.

GREETINGS!

Saturday, April 4, 2009

Overcoming AJaX UTF-8 Encoding Limitation (in PHP)

I've been learning a lot about PHP, MySQL programming through a project I've been working on for 2 months.

I didn't know AJaX, actually. And when I find any challenge that takes time and a lot of headaches to overcome, I share the solution for the sake of saving people some time and bad moments.

My web application is in Spanish (latin american characters), and I use AJaX to show search results paginated, in order to make it simpler and faster to go through the results, sort them, etc...

And the results include words in Spanish, containing characters not supported in UTF-8, AJaX won't show those characters correctly.

And no, there's no way, so far I've researched, to change the UTF-8 character set for the XMLHttpRequest object; setRequestHeader("Content-Type", "...; charset=ISO...") won't work.

Some pages say you may encode the URI you are sending, and decode the responseText and you're all set. I assume encoding the URI applies when using GET method, or when using non-UTF-8 characters in the parameter values, but not to make the responseText UTF-8 compliant. I can't decode a responseText that was never encoded. And I wasn't able to decode the responseText when assigning it to the containing element.

So I finally found the solution on a web page, much simpler than what I would imagine: encode the string representing the HTML string at the server-side to UTF-8 before returning it.

In PHP, it's like this:

$html = "... all my html response text here ...";
echo(utf8_encode($html));

or whatever way you decide to do it, the fact is, encode the response text with ut8_encode() before printing it or returning it.

Also, very important, make sure the HTML page receiving the responseText has the appropriate character encoding.

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

I assume it'll work pretty much the same way on other programming languages; simply encode the response text server side before responding, and make sure the receiving page character set is utf-8.

Hope it is helpful for anyone.

Greetings!

Tuesday, February 17, 2009

Correct Installation Steps for XAMPP 1.7 on Ubuntu Linux

So, for my freelance projects, I have to learn PHP, and use MySQL as database.

I have an Ubuntu 8.10 Linux distribution, and the best tool available for developing web apps with PHP and MySQL is XAMPP (formerly LAMPP: Linux, Apache web server, MySQL database engine, PHP programming language, PERL scripting language)

XAMPP is basically a set of tools well-packed to run altogether. It is called now XAMPP and not LAMPP because it is available to all operating systems, not only Linux.

Usually the best way to install a software in Linux is to get the debian package installation, (.deb file, this is because Ubuntu is built over Debian distribution) but for XAMPP there's nota debian package; there's a self-contained .tar.gz file (like a .zip file for windows users) with a folder called lampp that includes all tools embedded.

There's a comprehensive installation manual on the XAMPP pages for installing and setting it up, however, it doesn't include some minor changes that are required in order for some included XAMPP tools (such as MySQL) to work well.

After installing XAMPP do the following:

1.- For XAMPP web page to run: give proper read/write permissions to 'others' on the lang.tmp file at /opt/lampp/htdocs/xampp folder; go to the folder and execute the following command as root user:

#chmod 666 lang.tmp

2.- For MySQL correct execution: provide read/write/execute permissions over the var folder and all its contents. As I hadn't identified the right user, I assigned it to everyone. Go to the /opt/lampp/ folder and type:

#chmod -R 777 var

I've spent HOURS figuring out in error logs and forums for the right answers. I don't even want to list all of the errors I've faced. This should solve any of your installation problems on Ubuntu 8.10 and basically any Linux distribution.

Greetings!

Tuesday, January 13, 2009

Basic Java Thread Exercises

Was this helpful for you? Please take a little time to comment on the exercises and solutions after you've used them, I'd like feedback from you. Thanks! =)

UPDATE 12/03/20011: Fixed broken download links


Thread Race
Thread Relay Race

Assassin Thread Slayer

BASIC JAVA THREAD EXERCISES

This brief, simple tutorial assumes you already know the basic use of OOP in Java language.

Basic Theory Background - What is a thread?

I like to take the approach form the Operating Systems perspective, where a thread defines a single execution unit in a process, being a process an instance of a program in a multitasking environment.

Meaning, for example, when I run my internet browser, it is a process, and each separate browsing window tab inside that browser is a thread.

Threads, ideally, are independent execution units; they don't depend on others to execute, and a process can go on separately from the thread.

However, this would work fine in a multi-processing environment, like in a server with several CPU's. Most operating systems are multi-tasking, meaning they emulate this multi-processing by reserving time slots and resources alternately for each process, and as the CPU clock speed is high, it is transparent for the user.

Think about your computer now: you probably have this browser window open and also maybe your personal messenger, and maybe playing some music. Well they are executing alternately in the background, but for you as a user it's seamless.

And even in a multi-processing environment, threads may be having access to a resource another thread may be using, and this can cause what is called a deadlock; when neither thread can have access to a resource.

Imagine for example me and my brother want to wash our cars, and there's only one bucket and one sponge. Let's say I got the sponge and my brother the bucket: I won't be able to start washing my car because I'm waiting for the bucket, but my brother won't give it away because he's waiting for the sponge, so we're both just standing there looking at each other to see who releases his item first, but no one does, and I'm late for my date =(

If we were an harmonious family, we'd agree to share both alternately; he'll be using the bucket and sponge while I'm removing the soap from the part of the car I've washed and dry it, and then ask him for the bucket and sponge when done and he'll dry his part of the car and then ask me for the bucket when done and so on... and I'll be on time for my date with a shining car =D

What I mean is that when we program threads, we must consider these possibilities and provide our classes with a mechanism to manage shared resources. Java itself includes several synchronization methods for that purpose.

EXERCISES SECTION

The purpose of this post is to provide exercises that will help practice a basic implementation of threads. Here we'll present the problem and guide through the solution from a design approach, the implementation is up to you, and that's what these exercises are about: use what you've learned about threads implementation in Java for coding the solution. Good luck with your self-assessment exams! :-)

Exercise 1 - Thread Subclassing Vs Runnable Implementation - The Thread Race.

I wanted to make an interesting experiment: is it true that threads run independently, and that in multi-tasking environments each execution unit is given a time slot based on certain algorithms? What will happen if I made a thread race, let's say 10 threads... will the first one being run will finish first, or are they completely asynchronous and independent?

Let's make a thread race program, where a ThreadRace class will create an instance of 10 ThreadRaceCompetitor's. Then it'll run them all. There will be a results class called ThreadRaceContext, which will keep the scorecard of who finished in which place.

When a ThreadCompetitor finishes the race, it will have to inform the ThreadRaceContext his race number, and that it's done, so the ThreadRaceContext will inform about its arrival. Who'll arrive first? Make your bets!


Design challenges: The ThreadRaceContext object is a common resource for all ThreadCompetitor's. How can I make sure it keeps an accurate record of each of their positions at the race?

How should I implement the solution of I extended from Thread rather than implementing the Runnable() interface? What will the difference be? How would the ThreadRace class control each of the threads execution?

Reference for solving this exercise.

Exercise 2 - Synchronizing the Threads Through the join() Method - The ThreadRelayRace

Now let's make the Thread Race even more interesting: let's make it a ThreadRelayRace, in which the competition will occur between 10 ThreadRelayRaceTeam's, each of them composed of 4 ThreadCompetitor's.

Now the ThreadCompetitors will have a thread number and a team number, and the ThreadRaceContext will inform when a ThreadRaceCompetitor from a team finished, and then the whole team finishes, informing the results of the team's positions.



Design challenges: Did you make the previous classes reusable? How would I redesign the ThreadRaceCompetitor and the ThreadRaceContext to comply with these changes?

Now the ThreadRace will start running the ThreadRelayRaceTeam, and the ThreadRelayRaceTeam will start running its ThreadRaceCompetitor #1. How can I ensure the ThreadRaceCompetitor #1 starts and then follows #2 using the join() method?

Reference for solving this exercise.

Exercise 3 - Reserving a Shared Resource Using the interrupt() Method - The Assassin Threads Slayer.

So I decided to make an experiment in which I want to see that will happen if I place 10 AssasinThread's in a ThreadSlayerRoom, where there's only one ThreadKillerGun? Who'll take the gun first and kill all others?

The AssasinThreadSlayer class will make sure the AssasinThreads are placed on the ThreadSlayerRoom where the fun will start when their run() method is invoked. They'll all try to get the ThreadKillerGun first, and if it's already taken, they'll say it: "Assassin 1: Oh No! Gun's Taken!"

You should be informed who takes the gun and how all AssasinThread's are being killed one by one.



Design Challenges: Who will call the interrupt for the AssasinThread's when one takes the gun? It has to be the gun.

Reference for solving this exercise.

A Reference Code Example.

A useful code example implementing all the methods included in this exercise.

Was this helpful for you? Please take a little time to comment on the exercises and solutions after you've used them, I'd like feedback from you. Thanks! =)

Regards!

Monday, December 8, 2008

Something Very Terrible Will Happen to This Town.

I received this story by e-mail, and decided to translate it and share it with you.

In times of uncertainty like this one, where economical crisis is hitting all companies, sometimes fear takes us over and we create our own doom.

Speculation is a dangerous demon, that makes all come to a vicious circle: companies started selling their shares and assets looking for money foreseeing they won't be able to pay their debts, then people noticed and they started taking out their money from them, making company's value to go down and them needing to sell more and so on until bankruptcy.

Let it no happen to ourselves.

Hope this story gives you an idea about how ridiculous is human nature sometimes, and makes you reflect:

Are we the people causing something terrible to happen to this town?


Imagine yourself a very small town where there's an old lady who has two siblings: one boy, 17, and a daughter, 14. She's serving them breakfast and has a worried expression on her face. Her sons ask her what's wrong and she answers:

- I don't know, but I have woke up with the feeling that something very terrible will happen to this town.

They laugh at their mother. They say those are old people feelings, it happens. The son goes to play to the billiards, and at the moment he's about to strike a simple cannon, the other player says to him:

- I bet you a dollar that you won't do it.

Everyone laughs, he laughs, he shoots and misses, pays his dollar due and everyone asks him what happened, if it was a simple shot. He replies:

- It's true, but I'm concerned about something my mother told me this morning, about something terrible happening to this town.

All laugh at him, and the dollar winner goes back home, where he's with his mother or a granddaughter or anything, any sibling. Happy about his dollar he says:

- I won this dollar to Dámaso on the simplest way because he's such a fool.

- And why is him such a fool?

- Well, because he couldn't strike a very simple cannon, worried about the idea that her mother woke up with a feeling that something terrible will happen to this town.

Then his mother tells him:

- Don't make fun out of old people feelings because sometimes they come true.

She listens to him and then goes to buy food. She says to the shopkeeper:

- I want a pound of food - and at the moment she's being served, she adds-: No, better them be two, because they're saying something terrible will happen to this town and it's best to be prepared.

The grocer dispatches her food and when another lady comes to buy a pound of food he tells her:

- Take two, because people is coming here saying something very terrible will happen, and they're preparing and buying things.

Then the old lady replies:

- I have several sons, look, better give me four pounds.

She takes the four pounds, and to make the long story short, I'll say that the grocer in half an hour runs out of food, go gets more from the warehouse, he sells all of it and the rumor spreads. The moment comes when everyone in the town is waiting for something to happen. All activities are stopped and suddenly, at two o'clock, weather's hot as usual. Someone says:

- Have you noticed how hot it is?

- But this town has always been hot!

(So hot that it's a town where musicians had their instruments mended with tar, and always played under a shade beacause if they played under the sun, their instruments will tear down in pieces.)

- However -someone says-, it's never been that hot at this time.

- But it's at two o'clock is when it's hotter.

- Yes, but not so hot as now.

To the desert town, to the desert town square, suddenly a little bird comes down and rumor spreads:

- There's a bird in the town square.

And everyone comes, frightened, to look at the little bird.

- But people, there have always been little birds who come down here.

- Yes, but never at this time.

It comes to a moment of such tension for the town residents, that everyone is desperate for leaving and are not brave enough to do it.

- I am a real man. -someone yells- I'm leaving.

He takes his goods, his children, his animals, place them on a cart and passes through the central street, where all the poor town is looking at him, until the time they all say:

- If he dares, then we are leaving too.

And they literally start to desert the town. They take their goods, animals, everything.

And one of the last to abandon the town says:

- Let no disgrace come to what is left from our house -and then he burns it and others start to burn their houses too.

They run away in tremendous and true panic, like in a war exodus, and in the middle of everyone is the woman who had the premonition crying out:

- I said something very terrible will happen, and they told me I was crazy.

by Gabriel García Márquez - told on a writer's congress.
Translation and adaptation by Juan Manuel Trejo Sánchez

Wednesday, December 3, 2008

How to Keep your Job in Crisis Times

I receive a bi-weekly news digest from the ACM, called CareerNews, which focuses on news related to IT Carreer Development.

Economical crisis is hitting everyone, menacing our jobs or our growth opportunities. In times like this (and on any other time) is good to be well-informed. I'll be sharing with you the articles digest with what I consider the most relevant news.

Today I'll focus on the articles related to how to keep my job, how to ensure I get the best opportunities.

*I highly encourage you to keep in touch with this news digest, it has helped me keep up-to-date and well prepared: http://www.acm.org/membership/careernews/current

How to Ensure IT Job Security Despite an Economic Meltdown
Tech Careers, November 2008

Despite the steady growth that the technology sector has experienced over the past few years, the declining economy could lead to slower growth in this key industry. The current economic meltdown has caused many companies to re-evaluate their technology budgets and hiring plans, which could potentially lead to layoffs or increased outsourcing of technology jobs to other countries to save money. As a result, IT professionals will need to adjust their skills to align with changing business demands, learn how to demonstrate their value to employers and find ways to impact the bottom line.

First and most importantly, employers are looking for workers who can provide meaningful results. This is the perfect opportunity for IT staff members to demonstrate their value to the organization by identifying new ways to save money or increase revenue. Workers can also expand beyond their traditional role to take on more responsibilities. Although this inevitably means an increased workload, it is important to make the most out of this opportunity to gain more experience and demonstrate value to the employer. Additionally, IT workers can diversify their skill set and express a willingness to help out wherever needed.

The current period may be the right time for IT professionals to assess their current skill set and determine if they could benefit from additional certifications or training. In an industry that is constantly evolving and changing, it is important for IT professionals to anticipate emerging technology trends and continue to learn new skills to stay competitive in the job market. It is also important for professionals to proactively maintain their skills and continue networking at all times. It helps to be aware of what is going on in the job market, so as to avoid being unprepared in the case of a layoff.

Ten Steps Techies Should Take to Keep Their Jobs in a Financial Meltdown
eWeek, October 10

Against the backdrop of a slowing economy, there are a number of steps that corporate IT professionals can take to increase their job security. With belt-tightening now a common theme -- even in Silicon Valley, IT workers need to focus on practical ways that they can help their company reduce costs. They also need to learn how IT can drive business value throughout the organization and develop the type of peer network that will help them build consensus about important projects. Finally, they need to think about ways that they can position themselves as a generalist rather than a specialist in order to increase their perceived value to an employer.

In order to maximize your value to the organization, you really need to understand not just a specific part of the IT world, but all the technology tools that keep your company running. This is especially true as companies look for utility players rather than specialists in an era of tighter budgets. If possible, try to learn as much about the business and the types of technology projects that can really create value. Also, try to build some personal contacts within the company who can give you an early warning of organizational changes afoot.

How to Re-Skill Yourself for a Higher-Paying IT Job
CIO.com (via Computerworld), November 11

While IT professionals face challenges in switching to a different technical discipline to take advantage of increased demand for a hot skill, there are several ways to make the transition as easy as possible. The easiest path is to convince an employer to pay for online or classroom courses to hone or develop certain skills. However, given current cost constraints, most employers have fewer resources available than they once did to retrain IT workers in different technical fields. With that in mind, the article provides an overview of different opportunities that could lead to higher-paying roles.

While employers may be more willing to provide reimbursement for certain technical certifications, they may not be as willing to support more advanced training opportunities. From the perspective of employers, providing IT staffers with training opportunities can have mixed results. On one hand, a well-rounded technical staff with enhanced knowledge in various disciplines can provide better IT support. On the other hand, as IT workers become more knowledgeable, they also become more marketable, increasing the risk that they will leave for another employer or ask for higher compensation.

To underscore this point, the article profiles an application support supervisor in Michigan, who took advantage of his company’s training program to bolster his supervisory, project management and VMWare skills. In addition, he enrolled in MBA classes at a nearby college. However, after only receiving a 3% raise and being passed over for a promotion, this IT worker took advantage of social networking connections to explore senior systems analyst jobs. After interviewing for a position at a Detroit-area law firm, he received an offer and decided to take the job, since it included a 20% salary increase and better benefits.

Thursday, November 20, 2008

The Hottest IT Skills

I read an article from Computer World called "The Hottest IT skills to Survive a Cool Economy" which comes as a result of their Computerworld 2008 Salary Survey, and it states the trends on which will be the most demanded/best paid IT Skills in the next 5 years.

It identifies Web Developers, Network Administrators and Information Security Managers at the top of demand.

SECURITY is the top skill among organizations, according to a CompTIA survey of 3,500 IT Managers from 9 countries, --Australia, Canada, France, Germany, Italy, Japan, the Netherlands, the U.K. and the U.S.-- 73% of the respondents identified security, firewalls and data privacy as the IT skills that are most important to their organizations today. But just 57% of the same group said their IT employees are proficient in security. This leaves a 16% GAP to be covered yet.

Something that called my attention in the article is the recognition of the increasing pervasiveness of remote access for mobile employees and the implementation of wireless networks, particularly on high demand from Health Care and Education industries. This increase challenges IT sector tu secure communications, data and networks.

Hence, wireless technologies is included as a top too, at least for the next 5 years.

I know in the end, it's not about going with the trend, but about doing a quality job.

But it's also about being a "value worker": that who provides real value through the contribution of his/her work rather that the amount of extra-hours applied.

So, preparing our skills on these areas will ensure we can provide high-value where we will be more needed. And in these downstream times, where we struggle to keep our jobs, this is important to consider.

I just changed from company, and my new work is in the Telecommunications area, particularly on wireless technology. I leaked in through a Java project, but I'm preparing myself to hop-in to this wireless train.

And you, what are you doing to be a value worker?