Add this blog to Del.icio.us, Digg or Furl | Create Watchlist for this blog

ajax script tutorial - quick technology intro

June 20th, 2007

I love short stories to get started in a new technology. So here is one about ajax - the current hype on web platforms.

What is it for

Send requests asynchronous to your webserver and process the results within the current client-page-DOM without re-loading the whole page!

If you need special data in your webpage as response to a user action then use ajax. It is not meant for a whole Web GUI. If you use ajax for too much user navigation you will explore the two major drawbacks soon: The user can’t use the browser’s back button and search engines will ignore you (well, there are workarounds but those are bad browser dependent hacks).
The typical situation where ajax is useful is when you have two drop-down lists and the content of the second list depends on the selected entry of the first. I.e. “choose your cpu:” - first list contains manufacturers “Intel”, “AMD”, “IBM”, “Motorola”, second list contains processor model.

Technology, Syntax, Objects

On client side your users need a javascript enabled webbrowser of a “newer” generation. On server side you need nothing special, just use your favorite technique (there’s more importance on the selected protocol format - like just string or xml or json). On webdesigner’s side you need some DHTML and javascript.

A typical javascript function that initiates an ajax call with an url as parameter looks like this:

var request = false;  // you need this variable globally 

function initiateAjaxCall(url)
{
  request  = new XMLHttpRequest();
  request.open("get", url, true);
  request.onreadystatechange = async_event;
  request.send(NULL);
}

Where the XMLHttpRequest is the javascript-ajax object to focus on (for IE6 you need some workarounds well known in the web). ajax is “Asynchronous Javascript and XML” so it’s asynchronous and so you need a callback function (a function that gets called when an event occurs). Above “async_event” is declared to be your event handling function to handle the webserver’s asynchronous response.

There are four events your callback will be called with:

ajax state table:

0 = uninitialized
1 = loading
2 = loaded
3 = interactiv
4 = complete

For this quick intro, only state 4 is of interest. Maybe I’ll get back on this later in another post (can program nice progress bars with this infos).
Your event handler could look like this:

function async_event() {
  switch(request.readyState) {
  case 4:
    if (request.status != 200) {
      alert("HTTP Response not OK : Code:"+request.status);
    } else {
      myProcessing(request.responseText);
    }
  break;
  default:  break;
  }
}

In the “myProcessing” function the final response processing is done (usualy it’s any DHTML manipulation of the current DOM).

Full Code Example
It’s not that easy to invent a simple example that makes at least little sense, so don’t be to critical with this.

ajax script tutorial - example 1
Initial view of the example

To show up the technology in short code we build a website that displays the current client time (javascript) and a button to request the current server time. When the button is pressed, the current server time get’s fetched from the server by magical AJAX and is finally display via a DOM manipulation in - again - javascript.

We start with the server side (in php - to keep it simple)
File getTime.php

<?php echo date("H:i:s"); ?>

That was pretty simple, now we do the html page that uses ajax:
File getTime.html


<html>
<head><title>AJAX Test 1</title>
<script type="text/javascript">
   <!--
   // our global request variable
   var request = false; 

   // function to initiate the ajax call
   function initiateAjaxCall(url)
   {
     request  = new XMLHttpRequest();
     request.open("get", url, true);
     request.onreadystatechange = async_event;
     request.send(null);
   }

   // ajax callback function
   function async_event() {
     switch(request.readyState) {
     case 4:
       if (request.status != 200) {
         myProc("Error Response Code: "+request.status);
       } else {
         myProc(request.responseText);
       }
     break;
     default:  break;
     }
   }

   // function to print the ajax result
   function myProc(text) {
      var now = new Date();
      var ct = document.getElementById("CTIME");
      var st = document.getElementById("STIME");
      ct.innerHTML = ""+now.getHours()+":"+
                               now.getMinutes()+":"+
                               now.getSeconds();
      st.innerHTML = text;
   }
   //-->
</script>
</head>
<body onLoad="myProc('---');">
   <h1>Ajax Test 1</h1>
   Client Time: <span id="CTIME"></span><br>
   Server Time: <span id="STIME"></span>
   <br><br>
   <input type="submit" value="fetch server time via ajax now"
                          onClick="initiateAjaxCall('getTime.php');">
</body>
</html>

ajax script tutorial - example 2
After pressing the button, server’s time is displayed

New bugfix release V 2.1.2 of MIMEMailxPHP4_V2

June 13th, 2007

A new bugfix release concerning compatibility. There was an issue, that inline html images (CID images) were not shown correctly in the thunderbird email client. This was caused by a wrong (but accepted by MS Outlook) MIME type in the MIME mixed-boundary.

Changed the multipart/mixed to multipart/related - now it works in all mail clients.
The BUG and FIX was reported by H. Borns. Thanks a lot!

The projects info page is here

Eine deutsche Version ist hier

Multithreaded programming in D

June 8th, 2007

While in C++ there was no build-in threading support, D comes with a JAVA-like class “Thread”. So while in C/C++ you had to mingle around with threading libs like pthread or solaris-threads, in D you can leave that problem to phobos.

A simple example shows all the simplicity:

import std.c.time;
import std.stdio;
import std.thread;

int runThread(void *ptr)
{
  printf("Thread %d startedn", cast(int)ptr);
  sleep(10);
  printf("Thread %d endedn", cast(int)ptr);
  return 0;
}

int main()
{
  Thread t1 = new Thread(&runThread, cast(void *)1);
  t1.start();
  sleep(2);
  Thread t2 = new Thread(&runThread, cast(void *)2);
  t2.start();

  while ((t1.getState() == std.thread.Thread.TS.RUNNING)
            || (t2.getState() == std.thread.Thread.TS.RUNNING))
    Thread.yield ();   

  printf("program readyn");
  return 0;
}

That’s it. Save the code as ThreadTest.d, than compile with “gdc ThreadTest.d” and run a.out (or a.exe). What you get as output should be very similar to:

rainer@ThinkTop ~
$ ./a.exe
Thread 1 started
Thread 2 started
Thread 1 ended
Thread 2 ended
program ready

freebase - let the community build a global ontology

June 8th, 2007

With the help of Thomas I got invited to the freebase alpha program. In a short sentence I would say, that freebase is the semantic extension of wikipedia. That means, that freebase does not only have “objects” like wikipedia, it additionally has a hierarchy for these objects, relations between the objects, and common object attributes.

I.e. freebase “knows”: Austria is a country, Vienna is a city. A city is contained in a country - for Vienna, Vienna is contained in Austria. In Austria the main language is german. Goes what lanuage is spoken in Vienna…
freebase knows it! Got the point?

So, setting up the “Ontology” on freebase is a little bit like object oriented analysis. And it is a huge job to do for all the world’s knowledge!

Like Tim O’Reilly wrote:

But hopefully, this narrative will give you a sense of what Metaweb is reaching for: a wikipedia like system for building the semantic web. But unlike the W3C approach to the semantic web, which starts with controlled ontologies, Metaweb adopts a folksonomy approach, in which people can add new categories (much like tags), in a messy sprawl of potentially overlapping assertions.

It is possibly the advantage of freebase to have this messy sprawl of assertions - and with this sprawl the support of all the editors of the “collective intelligence“. The other (MIT) approach is very academic (surprise, surprise) and hard to follow (RDF, GRDDL, SPARQL, ITL, Microformats…). They spend a lot of work in the representation of an ontology - but it seems to be time just to start, to define some interweavings. Who is actually using DublinCore now?

When the collection of data is done, all the relations are set, how can we use the freebase?

freebase offers an open and free-of-charge API (MQL (like JSON) via HTTP) to use the data under common creative license where ever you want.

Questions:

  • freebase is driven by the company Metaweb, what happens to the data when something happens to Metaweb, i.e. getting bought by Google?
  • when lot’s of pages rely on the freebase service, how will they pay the traffic costs?

Yahoo! at a loose end

June 7th, 2007

About the new Yahoo! Panama API.

When I read the interview with Yahoo!’s Dan Broberg, Managing Director of Sales Technology on Alan’s Blog, I got a feeling that yahoo!’s running after Google.

For “advanced” support, we are not charging all that much, $2000 per month. This level provides our partners with more support, more dedicated Yahoo engineering resources should they need support. At the advanced and elite levels, we’ll make specific commitments regarding uptime, and provide our partners with in our product roadmap process.

They sell support for using their API - that’s not a 2.0 approach! That’s old IT business. A 2.0 approach would be to have a FAQ + a forum + a wiki + a developer blog - and all of that for free.

APRK: Google has taken a different approach. They don’t charge for support, but rather charge a nominal fee for each API action, 25c per thousand API tokens.

DB: We’re interested in best serving our advertisers, and we differentiate from our competition when it makes sense.

Is this eloquent marketing speech? Well, sure it makes sense for the selling company to charge a monthly fee instead of charging per action.
But to be fair, the free of support use is free of charge :-)

What does this change next few months? Can’t see any effects now, specially cause Google bought YouTube, DoubleClick and FeedBurner lately, there is more effort necessary to change the commercial search market than a “free API” (may be as stable as a rock). Is it a step in the AdWords direction? But AdWords is for free also, and I am not quite sure to earn more from Yahoo! adclicks than I do from Google’s.

Do I?
Is Yahoo! on the loose?

By the way, what do they do to their directory?

Programming in D - getting startet

June 3rd, 2007

I am programming in C/C++ for more then 15 years now. I took a look at JAVA, programmed some applications for 5 years now. But I am not so enthusiastic with JAVA, I find it kind of childish - it never stepped out of that web application area (in my opinion). No question, JAVA is bad for system programming - and no question too, there are some better choices today for business legacy system than JAVA.
I think the programming world is moving to the component side (away from the one-for-all approach, but independent from the infrastructure system for now). So what I looked for is a modern language to program fast, system-near components. And I found D.

If you search for information D is a terrible name
Try “D” in google and you will get some billions of results. Too bad, we need a web-catalog for this topic, but start with wikipedia for a first try. You will find that …

D is imperative, object-oriented, and metaprogramming
In short, that means that D knows objects and templates.

Continue with “Hello World”
The usual hello world is pretty simple and pretty close to C:

import std.stdio; // writefln() needs this module
int main(char[][] args)
{
writefln("Hello World!");
}

As you see, the include “stdio.h” has been replaced by a import std.stdio (looks like we have a package-like concept here now). And the printf() is writefln() today.

But you need a D compiler now
So start with the dgcc project. They deliver for all major (and some minor) plattforms. Install the compiler, save the code from above as test.d then compile like “gdc test.d”. As result you get the well known a.out executable (or a.exe under windows).
Run a.out and you will get:

Hello World!
Error: AssertError Failure test.d(5)

That’s because you didn’t return from your main function, so D is more severe than C. Insert a return 0; after the writefln() line and you’re done.

Next post will start with a serious application: A TCP/IP server in D.

New release V 2.1.1 of MIMEMailxPHP4_V2

June 2nd, 2007

Minor bugs made a new release necessary. It’s basically kind of service release to make the usage of the package more easy.
I fixed the linefeeds in the example programs to be all DOS (”\r\n”) linefeeds. So the problems with some FTP transfers should be solved now. And I fixed the PHP Warning (”Invalid argument supplied for foreach in line 364″) for empty attachment arrays.

The new version is absolutely compatible to all prior version. If you didn’t experience any problems, there is no need to upgrade!

Download of the software is possible here.

Google Gears makes me wonder

May 31st, 2007

Today I read a lot about the new “Google Gears” project. And it makes me wonder what google is doing here. Google Gears is a mix of a runtime-environment and an API to develop applications that run online as well as offline.

At a first impression it reminds me for old battles like with “Lotus Notes” where one could synchronize online and offline data. Simple for EMails but horrible for i.e. documents and complicated database content.

So why is google joining this business? My only explanation is, that they want to support their online application market (like their google-docs and picassa) by adding strong offline and synchronization capabilities. Making web applications run offline in a browser is one more step away from a single-user desktop PC - and from the OS needed here.

With their runtime-environment, google adds like an apache, and a mySQL Server to your PC. To synchronize the data on your local PC with your host system, google suggest a online synchronization via ajax technics (see here).

I will examine this in detail later because it is interesting. But for this time, I can not see how google will handle the more complicated problems of synchronization (like missed merges, concurrency problems, huge amounts of data …).

What a systems analyst is doing

May 28th, 2007

I call myself a freelance IT consultant, in a brighter light I offer my service as “systems analyst”. But what exactly is the job of a systems analyst? I try to describe the tasks from a practical point of view:

The core challenges are

  • Listen to the customer
  • Translate for the technicans
  • Design and pre-document the system on different detail levels

Do not mix up the analyst with the architect or the technical designer! Imagine there is an interface to a stock exchange involved: The analyst says what data the application needs from the interface, the architect says how the data is retrieved (i.e. MQ, http, triarch…) and the technical designer says how the data is stored in classes (or what ever data model you use).

The core qualifications for this are

  • Communication skills: Ability to ask and listen, and to read between the lines
  • Business knowledge: Deep knowledge about the business field of the application and the business processes of your customer
  • Methodological skills: Have a good command of formal documentation methods like SA, OOA, UML
  • IT skills: Good knowledge of IT possibilities, specially about the customers legacy systems
  • Soft skills: Be friendly, courteously and of course have an analytical mind

The most difficult task in systems analysis is understanding what the customer expects. In practice I found, that the average customer has no in deep imagination of what the resulting system should do. It’s more of a general spec like “the system should support the purchase department”. Your task is it now to define the systems requirements exactly, you can not be fuzzy like the customer.
This is why you have to understand the business field of the application.

When you start examining the current business process of your customer you will have to talk to a lot of employees. Employees usually don’t like changes but your task is it to define a computer system to streamline their job. If the stuff that’s working on your business process is rejecting you, you can never design a useful system.
That is one aspect why you need good communication skills.

When you have your plan at least and start to write it down you have to adhere to the rules of the selected method. You can not invent your own kind of specification language, because if you do, you’d need a lot of your budget to explain your language. From my practice I can tell that computer staff usually doesn’t like business staff, that means you won’t find mercy here. When you draw application data models you are not free in your syntax, you have to use your customer’s standards. And if your customer is not a tiny company, he will use industry-standards like i.e. UML.
That is why you need excellent methodological skills

The job of a systems analyst is it to define the capabilities and behavior of an IT system, considering environmental constraints, considering business processes, considering methodological guidelines, considering the users capabilities. Design the system and communicate it on different detail levels to the customer’s executives, to customer’s staff and to the staff thats doing the implementation.

So far?

Anger about my new Lenovo Z61m

May 23rd, 2007

I had my Samsung T10 now for three years, I was at all satisfied with the machine (put 1.5GB in it) but I wanted a Intel Duo CPU now - specially for eclipse development.

So I bought the new IBM Lenovo Z61m with a Core2Duo T7200, 2×2GHz and 2 GB memory. And I am not really glad about that. Other than expected, the laptop is terrible slow. The identification with the fingerprint reader is close to be useless. Lot’s of annoying “free software” that’s pre-installed is pulling on my nerves - at all, I don’t know what the system is doing all the time (looking at the Task Manager tells that it’s idle). Another point that’s bad done is the WLAN installation with lot’s of tiers in the TCP/IP setup that do who ever knows what - but don’t establish stable network connections.
The WLAN requests “hang” very often. I.e. when browsing nothing happens until I load another page on another tab or in another browser. Now I am browsing with a permanent ping in a DOS shell -> the “hang” is gone - well done!

Next bad point is the Think-Software, meaning the software that pops up when you press the “ThinkVantage” button. For example the “Travel Manager”. That piece of software thinks it nows what you want to do when you change from pure to docking station. But it does not. It kills your suspended session when you put the Lenovo in the docking station. Please, what is this for? Not talking about the Display Manager when changing between external monitors…

I am really not amused!
And on and on. Currently I am loading a bios update that was suggested by the “ThinkVantage” …