programming language & alogirthm

Sunday, July 08, 2007

ld and WIN32 (cygwin/mingw)

mport libraries

The standard Windows linker creates and uses so-called import libraries, which contains information for linking to dll's. They are regular static archives and are handled as any other static archive. The cygwin and mingw ports of ld have specific support for creating such libraries provided with the -out-implib command line option.

exporting DLL symbols

The cygwin/mingw ld has several ways to export symbols for dll's.


http://www.redhat.com/docs/manuals/enterprise/RHEL-4-Manual/gnu-linker/win32.html

DLL Creation in MingW


I've always considered DLLs to be esoterically cool stuff - somehow the idea of one program running another makes my imagination run wild. I've now discovered that in many cases DLLs are a bad idea(TM), but for a fledgling programmer, learning how to create a DLL, especially in a free development environment such as MingW would mean an instant familiarity with a lot of development tools, and a lot of the seemingly hidden options of the incredible gcc compiler.

As usual, we're diving in. You should have a copy of mingw handy. Get the MingW installer from the Current branch in the Mingw download page, that sets you off easy. You should also be familiar with IDE-less coding, or should know enough to set up an IDE to work with Mingw, I'm not going to cover that here.

What are DLLs?

First off, what are DLLs? DLLs are dynamically linked libraries. How are they different from static libraries? In static libraries, the linking is done at compile time: all the library functions are combined with the main fragment of program code to create the executable. When the linking is done at runtime, it is called dynamic linking. Since the linking is done at runtime, it is obvious that the operating system will have something to do with it. That is why most DLL implementations are non-portable.

When a compiled executable that references a DLL is loaded, the OS looks into the file and sees that the executable references a set of "imports" from a DLL file. This is simply a situation equivalent to finding that "This program uses the following functions which are contained in this dll". The OS then looks into the particular DLL. The DLL has a corresponding and matching set of export functions that the OS then maps from the functions referenced in the main executable to the functions in the DLL. Thus, when the executable calls a referenced function, the code in the DLL is executed. Viola! Dynamic linking!

Hello DLL!

I'm now going to describe a standard "Hello world" implementation. The code is in three files: hello.c, dll.h and dll.c. The code is listed and explained below:

hello.c

#include  
#include "dll.h"

int main () {
hello();
return 0;
}

Hello.c is a standard hello world C program except that the hello() function is going to be dynamically linked. The only special thing here is the inclusion of dll.h.

dll.h

#ifdef BUILD_DLL
/* DLL export */
#define EXPORT __declspec(dllexport)
#else
/* EXE import */
#define EXPORT __declspec(dllimport)
#endif

EXPORT void hello(void);

DLL.h is where most of the magic happens. It begins with checking the BUILD_DLL macro. We manually set this macro when building so that the macro EXPORT is set to __declspec(dllexport), so that gcc can build the dll. When the OS calls up the dll from the executable, BUILD_DLL is not set and therefore EXPORT is set to __declspec(dllimport) which is a nice set of macro routines to expose our function to the calling scope.

Note that __declspec(dllexport) and __declspec(dllimport) are mingw macros to faciliate DLL creation. They are mapped to their equivalent WinAPI headers.

dll.c

#include 
#include "dll.h"

EXPORT void hello(void) {
printf ("Hello\n");
}

This is the actual code of the hello world routine. There should be nothing special here.

Compiling and Linking the files

DLL creation used to be a tiresome process. Recent advances in gcc and mingw engines have meant that it takes only four steps now to create a dll. They are:

  1. Creating the object code for hello.c
  2. gcc -c hello.c
  3. Creating the object code for the dll
  4. gcc -c -DBUILD_DLL dll.c

    Notice the use of the -D param by which we set the macro BUILD_DLL. It is used for setting export to __declspec(dllexport) so that compilation can take place.

  5. Creating the dll
  6. gcc -shared -o message.dll dll.o -Wl,--out-implib,libmessage.a

    The third step requires more explanation.
    The -shared parameter is used for creating a shared libaray; in Win platform it is a dll.
    -Wl means wait for next message to the linker.
    --out-implib is a param to the linker ld which tells it to create an import library which is used by programs which want to link to your dll.
    We are ignoring the definitions file which every well-behaved dll should export. If you follow the step above, GCC will automatically create the definition. For most cases, it will work, but if you want to optimize stuff this is the place to look.

  7. Creating the executable
  8. gcc -o hello.exe hello.o message.dll

    The fourth step is actually a bit of gcc magick. The actual step is something like this:

    gcc -o hello.exe hello.o -L./ -lmessage

    The -L param means that the linker checks the ./ path for imports
    -lmessage (or -l message) means to search for the message linker name. It extracts this from message.dll

Once you've finished these steps, run the program!

C:\>hello
Hello!

Wait, that's not dynamic!

You're right, that's not *really* dynamic. Of course, you're loading the function at run-time, but what is the purpose of that if you need to reference the dll at compile-time? One of the reasons why a dll is used is to enable a plugin architecture for your program. Other people can write code that your program can use, and you can't really anticipate other people's dlls, and if you are going to recompile your program every time a new dll comes along, then why use dynamic linking at all?

Solve this by using two functions from the Windows API: LoadLibrary() and GetProcAddress(). We modify the codes for the main module like this:

hello.c

#include 
#include

int main () {

/*Typedef the hello function*/
typedef void (*pfunc)();

/*Windows handle*/
HANDLE hdll;

/*A pointer to a function*/
pfunc hello;

/*LoadLibrary*/
hdll = LoadLibrary("message.dll");

/*GetProcAddress*/
hello = (pfunc)GetProcAddress(hdll, "hello");

/*Call the function*/
hello();
return 0;
}

The code should be self explanatory, there are just some things that you should remember:

  1. Don't forget to include windows.h
  2. The syntax for LoadLibrary is:
  3. handle = LoadLibrary("path to dll file");

    handle is <= HINSTANCE_ERROR if there is an error loading the dll.

  4. The syntax for GetProcAddress is:
  5. pointer_to_function = (pointer_to_function_type)GetProcAddress(dll_handle, "resource_name");

    We can also use global variables inside the dll that are prefixed with export as a valid resource name, it needn't be a function. That is,

    variable = (type)GetProcAddress(dll_handle, "global_variable_name_inside_dll");

    is also valid.

  6. For further error info at any step in the process, call GetLastError()

To compile it, don't change a thing for the dlls. For compiling hello.c, a simple...

gcc -o hello.exe hello.c
...would do.

More information

This doesn't solve the problem of implementing a plugin arch, but we can work towards it. One of the ways in which this is done is to reference a function with a unique name from every dll called. For example, a program searches for all dll files beginning with a particular header in the file name and loads it via LoadLibrary. For example, a music program called foobar might look at all dll files which begin with foo. Thus foo_looks.dll will be loaded, while gym.dll won't be. Then inside the dll, it searches for a particular resource say "play", and loads and runs it.


An implementation of the above method, branched off from sortalg, can be found here.
http://sig9.com/node/35

MinGW + DirectX
I should first point out to beginner game developers that it is entirely possible to avoid using DirectX at all by using SDL (Simple DirectMedia Layer) for all your graphics, sound, input, timing, etc., and it integrates well with OpenGL for 3D graphics (it actually uses DirectX for 2D graphics, sounds, and so on) -- with the added benefit of being cross-platform. So unless you need or want to work with the DirectX API directly for some specific reason, this is a good solution that offers portability to a number of other platforms and a rabid following of both pro and amateur game developers. If you're just starting out and not sure, I would recommend looking into it before getting into DirectX. You can have a look at my MinGW + SDL page for MinGW/SDL-related setup tips.

Now, for those of you remaining, I assume you do know how to use MinGW, and I assume you are interested in getting it to compile DirectX apps. We'll need the DirectX headers and libraries for the version of DirectX we want to use. These are typically included in the DirectX SDK available from Microsoft. Whichever way you do this, you will at least need the header files, so get the SDK you want to use. The latest version can be found at www.microsoft.com/directx/. You can, at the time of this writing, still get the DirectX7 SDK from Microsoft. With DirectX8, Microsoft has combined DirectDraw into Direct3D. Some people wishing to use DirectDraw, or older interfaces may opt to use this download. (If you do want to use an older version, this version 7 SDK is a much leaner download and install.)


The Easy Way

The most straightforward way to go about building a DirectX app is simply to use Microsoft's DirectX SDK. You can link to Microsoft's .lib files to your application by specifying the .lib name explicitly to the compiler. Adding the headers location to the include path would also be a good idea. Example:

g++ main.cpp -o test.exe -I../dxsdk/include ../dxsdk/lib/dxguid.lib

Note that by using this method, you need to write the full path for each .lib file you wish to link to. Users of MinIDE can simply drag and drop .lib files directly into the target(s) requiring them.


Other Ways

  • There also exist MinGW-compatible libs (typically named lib*.a, where * is the name of the library). The advantage to using MinGW-compatible libraries using this naming convention is that you can put them into a location on your library search path (specified by the -L flag). The version of the DirectX static libs shipping with MinGW is probably out of date, but if they do support the functions you need then you can use those simply by adding, for example -ldsound to your linker command.

    The implication of this library search naming convention gives us one more way to link to Microsoft's DirectX SDK libraries: simply change the names of the MS libraries to lib*.a (e.g. rename ddraw.lib to libddraw.a, and then don't forget to add the library search path with the -L option.)

  • You can also get a ready-to-go Cygwin/MinGW-compatible DirectX6 SDK from John Fortin's site (you only need the directx6_1-cyg.tar.gz file). This includes everything you need to build DirectX 6 (or earlier) apps with either Cygwin or MinGW, however keep in mind that this download is the version 6 API. If you want later versions, I suggest getting them from Peter Puck's excellent site which also contains more detail regarding DirectX and MinGW and import library issues. The reason I'm using the version 6 SDK is because I only need version 5 for what I'm working on. If there are features missing from these older versions that you require, you'll need to get a later version. Note that DirectX8 has removed the DirectDraw API; now all 2D and 3D graphics is accomplished via the Direct3D8 API. The last version of DirectX to support DirectDraw API was version 7. You can still use the latest headers to compile and build for older versions of DirectX, however the v7 & v8 headers were causing some annoying compiler warnings so I stuck with version 6. I get the feeling Microsoft doesn't like you using 3rd party compilers to build DirectX apps.

More Tips

  • When using an ad-hoc DirectX SDK, I create Microsoft-like directory for it called, eg. dx6sdk, and in that I create an include and lib directory. I leave this in a convenient spot so that I can link to the lib and include files from multiple projects.

  • Another trick I use in order to avoid a lot of hassle is to use Windows' LoadLibrary()/FreeLibrary() calls to load the DDRAW.DLL, DSOUND.DLL, etc. libraries explicitly. This minimizes your static link requirements down to just the dxguid library. (I was unsuccessful getting the #define INITGUID trick to work, which would eliminate the need to link to any DirectX static libraries. For some reason, the IID_IDirect3D2 symbol remained undefined. Perhaps there is another way around it, but as far as my experiments showed, you need to at least be able to link to libdxguid.a.)

Backwards Compatibility, Version Decisions

If you are looking to support relic Windows PCs that have never been patched since, like, 1996, you can just go with the version one interfaces of DirectDraw and DirectSound, and use the Win32 calls GetJoyPosEx()/GetKeyState() for input and Windows sockets for networking. In fact, there really is no reason not to use the old interfaces if you're not using Direct3D or the higher-level media APIs -- with a few caveats:
  • DirectSound version 1 has a bug that the streaming sound buffer read/write position to be off by 50ms or somesuch. If you are not doing any software sound filtering or realtime computation relying on accurate feedback from the API (i.e., if you just want to play/loop/stop/volume/pan stuff), DSound1 handles the basics just fine, otherwise you should look at using a later versions in which this bug was fixed.


  • DirectDraw version 1 does pretty much all you need a blitter/flipper to do, unless you're doing some strange video things. Most of the extra features later interfaces of DirectDraw provided were not implemented on all (or even hardly any) hardware, so unless you've got a specialized application/hardware, consumer hardware support for things like hardware alpha-blitting with DirectDraw never came to be. (Most features were implemented for Direct3D instead.)


  • Direct3D version 1 (DirectX3) -- this API was pretty much unusable until Direct3D2 (DirectX5) which added DrawPrimitive (OpenGL-style) calls. DirectX5 by the way was also on the Win95OSR2 release, and by that time people had really started to buy Windows machines, so I believe DX5 is quite widespread as well as being the first release to really start working like it was supposed to (this is all very scientific, you know). With the newer releases, now up to DirectX8, the interface has become much more flexible and has stripped alot of the butt-ugly setup code overhead that used to be necessary and you've got all the latest vertex shader & multi-texture features at your disposal -- at the expense of a smaller pre-installed user-base. Also keep in mind that the later the more recent the feature is, the more likely it is to be emulated in software on older hardware. Just be sure not to cut out the low-end, especially if you're not working on a AAA retail game with a multi-million dollar budget :) In any case, if you must use DirectX8 and all the latest flashy gadgets, you can always provide the DX setup utility with your game, or tell the user where to get it. DirectX 6 or DirectX 7 may be a good compromise for you as well.

    One final comment I might make about using Direct3D: this is probably the most compelling reason to use DirectX at all instead of using pure SDL/OpenGL. Direct3D (at least in my experience) tends to behave itself better on some cards (provided your app handles that cards capabilities properly) than OpenGL. In addition, a few things like swapping between fullscreen and the desktop, and synchronized page flipping are just better-handled with DirectDraw/Direct3D than OpenGL (which is partly due to the way Microsoft handles OpenGL, and partly due to some of the limits of a more hardware-abstracted 3D API). DirectDraw also provides access to the frame buffer, which is not accessible via SDL while OpenGL is running, should that be an issue. D3D also allows your app to load textures in their native format, theoretically allowing faster mixed-mode rendering. Of course, depending on your app/hardware, you may find OpenGL preferrable (it's certainly less work to port!). Many Windows games these days provide both OpenGL and Direct3D support.


  • Old Documentation can be hard to find. I have some on my resources page, however Microsoft seems to do a pretty good job of obfuscating it on their website. To constrain your usage of an interface to a certain version, use

    #define DIRECTDRAW_VERSION 0x0500
    #define DIRECT3D_VERSION 0x0500

    ... for each DirectX component you're using, before including any DirectX headers. Note that the number refers to the version of DirectX for that API rather than the numbered version of the API. (Microsoft now synchronizes all version numbering for all DirectX interfaces.)
Roughing it

When you use static-link libraries for DirectX, they do not contain the actual DirectX functions; they only allow the linker to resolve dependencies at compile time, and Windows then searches for and loads the DLL is loaded at runtime. Keep in mind that any of the static functions that you link to, like DirectDrawCreate() need to be resolved at runtime when the dll is loaded. If the dll is missing, or is missing the function you called, your app will bail before it can start.

If, for whatever reason, you want to control this behaviour from your app, I would instead recommend using the Win32 functions LoadLibrary() and GetProcAddr() on the DLLs directly. This reduces your link requirements down to only dxguid.lib (or libdxguid.a), which does not require run-time binding. This allows you to test, for example, the presence of Direct3D2, and if it fails, resort to, say, OpenGL, or starts the DirectX installer, etc. This is a fair amount of work however. Most people can simply warn that the user "must install the latest DirectX runtimes, yadda yadda".

Final Notes

You will quickly discover that if you're attempting to use anything COM (like DirectX), you will need to add the -fvtable-thunks option to your compile commands. Using the MinIDE, you can set this from the Options->Target Switches dialog box. On the General tab, add -fvtable-thunks to the 'Other GCC options' text field. Important Gotcha: if you use the -fvtable-thunks flag to compile a static library, be sure to use that same compile option for anything you want to link to it! Otherwise the virtual function tables will get messed up, the linker won't warn you of this and all of your virtual function calls will make your computer puke. This wasted a good 2 days of my life! Don't be like me!!

http://www.spacejack.org/games/mingw/mingw-dx.html

MinGW Starter Guide

http://www.spacejack.org/games/mingw/
This article is targeted towards C and C++ programmers, particularly Windows programmers familiar with other Windows compilers, who would like to use MinGW (Minimalist Gnu Compiler for Windows), the port of GCC, for application development on a Windows PC. I also make few related tool recommendations, keeping in mind that everyone has different tastes or needs. If you don't know what MinGW or GCC is, then you should probably visit the above links first. Most of the resources I describe are listed or linked to on the mingw.org page, but I have narrowed down the scope considerably to the tools I have found to work best for me.


What we want:

  • A modern C++ compliant compiler with solid Standard Library support.


  • A code editor and makefile tools or an IDE.


  • The ability to build console, Windowed, SDL and DirectX and OpenGL apps.

What to get:

  • Download the latest MinGW release from the MinGW home page. If you download a zip file, be sure to check that there is a root MinGW folder in the zip file before extracting; if there is not you should specify one for extraction (eg: C:\mingw). You can freely rename or move this top-level directory, provided you update your system's path environment variable (on Windows 2000, right-click My Computer --> Properties --> Advanced --> Environment Variables). For our example, we'd insert: C:\mingw\bin, preferrably at the beginning of the path. See the install instructions with MinGW for more.

    Before continuing, you may wish to experiment a little with your MinGW installation. I found Colin Peters introduction invaluable. It shows you a simple HelloWindows.exe and explains how to build various types of binaries. Highly recommended first steps.


  • You will also want a good Text Editor/IDE (unless you're an emacs fiend, in which case you've probably made up your mind already :). An extensive list of free editors and IDEs can be found on devzoo.com. Some are definitely better than others. Of note, Dev C++ is an ambitious effort to provide a full development suite for MinGW. There is also a make utility called Jam which greatly simplifies the task of creating makefiles and managing dependencies. It is not an IDE, but it does allow you to create makefiles for large/complex projects with very simple, concise commands. This may appeal to some people better than a GUI tool. Cygwin, which provides a Unix environment on Windows can also be rigged up as an IDE/development environment in a number of ways (Unix is, after all, a developer's platform). See the Cygwin section below for more.

    My favourite editor is TextPad, a fully-functional shareware text editor for Windows, but it is very reasonably priced and is an excellent editor for C, C++, HTML, Perl, Java, etc. One of the better free text editors I've come across is the Programmers File Editor.

    If you don't want to write makefiles by hand, Rainer Schnitker has a simple IDE to work in conjunction with MinGW.

    There's also the general-purpose IDE Eclipse. I actually haven't used Eclipse with MinGW yet, but there is an article on IBM's site with more information.


  • You should also be aware of STLport. (Pure C coders can skip this, as can those who do not wish to use the STL or would rather use the default headers provided with MinGW.) STLport boasts some very efficient statistics and is ported to many different platforms/compilers, so if it's relevant, or if you just like to tinker, give it a shot. If you do, or if you plan to try compiling other 3rd party libraries or applications from source, be sure to read the following section. Some makefiles may require a "posix shell" in order to build with mingw.


  • MSYS is a lightweight posix shell for Win32, also available at the mingw.org site. This will likely allow you to use makefiles and/or run configuration scripts in order to compile projects ported from Unix (or Unix variants) and allows the posix style path separator character '/' to work with Win32 apps run from the MSYS command line. MSYS's installer will easily allow you to configure it to work with your MinGW installation. Or you can try...
CygWin
  • If you are primarily a Windows coder and are not very familiar with Unix or Linux but are interested in learning more, I would recommend installing CygWin. CygWin is kind of like a Unix emulator for your Windows machine but it is also capable of running Windows applications (like MinGW) from the command-line. CygWin is often necessary to use in conjunction with MinGW when you are attempting to build libraries from makefiles, typically programs that have been ported from *nix. make is capable of starting other executables, and *nix developers often include *nix-specific calls to programs that don't exist on Windows. Installing CygWin usually makes the required apps available; you simply run 'make' from CygWin's command line.

    In order to get MinGW to work properly with CygWin, you need to make one change to CygWin's own $PATH variable. CygWin's path is prepended your Windows path so CygWin will find its own native executables before Windows (generally, Unix and Windows programs on the path are named differently, but not always). If you installed CygWin into C:\cygwin, open the file C:\cygwin\etc\profile in a text editor. If you installed mingw into c:\mingw, then insert: /cygdrive/c/mingw/bin: at the beginning of the path string (look for the line $PATH="...). 'cygdrive' refers to the root level of your Windows system, outside of the Unix environment. Save this file after making the change. If you have any CygWin windows open, close them. From now on, CygWin will find mingw's binaries before its own. You can test this by starting up a new CygWin command-line window and typing gcc -print-libgcc-file-name. This will output c:/mingw/bin/../lib/gcc-lib/mingw32/2.95.3-6/libgcc.a (assuming you installed mingw to c:/mingw).

    Note: I believe that Cygwin now includes MinGW as an optional install component. You may wish to check to see that it includes the version of MinGW that you want before using it. If you do install Cygwin's MinGW, then take care to distinguish between the Cygwin version of MinGW, Cygwin's GCC and the Win32 standalone MinGW in your $PATH variables, by placing the one you want to use first (and/or omitting the others).

    Cygwin it is a heck of a lot more than just a tool to get GCC makefiles to compile with mingw. It is an entire Unix environment that brings with it editors like emacs and vi which have extensive programming syntax files, as well as various shells like ksh which are designed for coders. Basically, you can tailor your development environment with a myriad of tools.

Linkage Issues:
  • Another point to clear up: .a files are understood as library (actually archive) files by MinGW. This is all explained in the documentation, however it is worth noting that ld, the linker (called implicitly by g++) can link just about any type of file to build a target. However, the naming convention "lib*.a" for static libraries allows you to specify a search path for static link libraries. That is; if your library is named "libfoo.a" for example, then it can exist anywhere in the path specified by the -L flag, and should then be specified as -lfoo. If you are linking to a library named "foo.lib" however, you will need to type the full path and filename for this, and every other .lib (i.e., not .a) file.

Other Notes:
  • Exception handling is enabled by default, which will make your resulting binaries larger. You can turn off exception handling with the -fno-exceptions flag (unless of course you want to use exceptions). You can further reduce the size of your exe (but not by much) by disabling RTTI. Use -fno-rtti, however this prohibits the use of exception handling as well as run-time type identification features like dynamic_cast. With MinIDE, you can add these settings to the Options->Target Switches->General tab->Other GCC options text field. There is a lot of other trickery one can do with template instantiation flags as to avoid redundant code generation, however I haven't gotten much into that yet.


  • Finally, remember to use the -s flag to strip symbols from your final exe (MinIDE will add this to makefiles automatically when building an exe).

Wednesday, April 18, 2007

JSF is too sensitive to JavaBean naming

In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.

The required conventions are:

  • It has to have a no-argument constructor
  • Its properties must be accessible using get, set and other methods (so called accessor methods) following a standard naming convention
  • The class should be serializable (able to persistently save and restore its state)
  • It should not contain any required event-handling methods

public class PersonBean implements java.io.Serializable {

private String name;
private boolean deceased;

// No-arg constructor (takes no arguments).
public PersonBean() {
}

public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}

// Different semantics for a boolean field (is vs. get)
public boolean isDeceased() {
return this.deceased;
}
public void setDeceased(boolean deceased) {
this.deceased = deceased;
}
}

Wednesday, March 21, 2007

AJAX in the Enterprise

Is AJAX ready for the Enterprise? The answer to this question may lie in its relationship to open standards, vendor lock-in, conformity to popular skill sets, and web services and service-oriented architectures.

  1. Open standards are preferred by corporations who do not want to be tied to a specific vendor or plugin for their mission-critical systems. The building blocks of AJAX, (X)HTML, CSS, JavaScript, and XML, are all open standards supported widely across different browsers and platforms. Some alternatives to AJAX do not enjoy the same level of ubiquity. For example, XUL and XAML are both browser dependent, while Java, Flash, and SVG all require proprietary plugins.
  2. Vendor lock-in has always been an issue for IT investment, and continues to be on the web. By avoiding proprietary technologies on which to build large-scale enterprise applications, firms are mitigating some long-term financial risk. AJAX is a set of technologies that are based on open standards and partially avoids the issue of vendor lock-in.
  3. Another big selling point for AJAX is the way web developers who are familiar with the underlying technologies can begin developing with AJAX relatively quickly, while the learning curve for alternative technologies is comparatively steep. By leveraging the synergies of skill transference, firms do not have to invest in significant retraining of their developers.
  4. Service-oriented architectures (SOA) have been gaining popularity in major enterprises around the world for several years now. SOA is an approach to building large distributed systems on a composite set of loosely coupled business services. Just about every major enterprise software vendor has an SOA strategy and product suite match. In many SOA models, business services are exposed through XML web services, and AJAX clients are ideal consumers of these services.

The question then becomes, is the AJAX platform powerful enough to build enterprise-quality Rich Internet Applications (RIA). This issue is highly debated in the web development community (http://blogs.ebusiness-apps.com/dave/?p=32). Here are some of the arguments against AJAX for RIA:

  1. There is a stigma attached to using JavaScript to accomplish any intensive processing tasks since JavaScript is an interpreted scripting language, and quite inefficient. That said, the average desktop computer is becoming more powerful. In the past, most JavaScript applications only performed very simple tasks where efficiency is not a concern, and so techniques for writing efficient JavaScript are not widely known. As AJAX matures, coding standards will improve and push the language to its limit. As this happens, the efficiency argument against using AJAX for Smart Client implementations will weaken.
  2. As an interpreted language, JavaScript must be sent up to the client as source code. This causes problems for protecting intellectual property, since the source code must be distributed to anyone using the application. There are techniques for obfuscating the JavaScript, but like all copy protection they just make it a bit harder to steal, not impossible. This argument fails for a number of reasons, though.

First of all, Java suffers from a similar problem, with source code weakly protected in its distributed form. This, however, has not stopped businesses from deploying large Java-based applications. Another reason this argument fails in an SOA environment is that the AJAX application doesn't need to possess all the business secrets required for the program; they just need to orchestrate the business services that perform these activities.

This broad argument against using AJAX in the RIA realm may be somewhat short sighted. Within an enterprise, the need for interoperability may outweigh more fine-grained standards centering around performance, IP, and code inefficiencies. Consequently, looking into the future, approaches like AJAX which focus on platform independence and RIA will become important in the realm of enterprise applications.

Conclusion

The trend in web application development is towards open standards and vendor neutrality. Current HTML web applications don't provide the user experience users have come to expect, so the development community has long needed a viable technology suite to develop rich internet applications. AJAX fits all of these requirements and has experienced significant uptake by developers and enterprises over the last year. It's always challenging to predict technology trends, but if we look back at Java's evolution we can see that there are a number of similarities.

A decade ago, Java was going to revolutionize the way that developers built applications. Instead of building different versions of an application in order for them to run on different operating systems, developers could target the Java Virtual Machine, and then their software would run on Macs, Windows, and Unix-based platforms without any further customization. Huge corporate information systems are being built on the Java platform, and a number of large client applications are also built using Java. Java also suffered from performance and usability issues related to poor user-interface libraries, but overall it was quite successful.

As internet applications became more prevalent, we ran into the same problems of being forced to either write software to target a specific environment, or be very limited in the quality of the user experience. Technologies like HTML, CSS, and JavaScript gradually evolved with the promise of providing a platform on which very powerful applications could be based, but that promise was unfulfilled until now. Now that all the major web browsers have relatively consistent support for the technologies AJAX requires, AJAX will become a crucial piece in the RIA puzzle and will offer the potential for dramatically more powerful and user-friendly web applications.

Monday, March 19, 2007

Process Affinity

Processor affinity is a modification of the native central queue scheduling algorithm. Each task (be it process or thread) in the queue has a tag indicating its preferred / kin processor. At allocation time, each task is allocated to its kin processor in preference to others.

Processor affinity takes advantage of the fact that some remnants of a process may remain in one processor's state (in particular, in its cache) from the last time the process ran, and so scheduling it to run on the same processor the next time could result in the process running more efficiently than if it were to run on another processor.

win32process.SetProcessAffinityMask

SetProcessAffinityMask(handle, mask)

Sets a processor affinity mask for a specified process.

Parameters


win32process.SetThreadAffinityMask

int = SetThreadAffinityMask(handle, mask )

Sets a processor affinity mask for a specified thread.


def SetProcessorAffinity(self):
try:
import win32api, win32process

# get number of processors
systemInfo = win32api.GetSystemInfo()
numprocs = systemInfo[5]

# if multiple procs, set processor affinity to the first
# this sets proc affinity for children also, so vic will get this
# (vic is ill-behaved on multiproc machines)
if numprocs > 1:
log.info("Found %d processors; setting affinity",numprocs)
cp = win32api.GetCurrentProcess()
win32process.SetProcessAffinityMask(cp, 1)

except Exception,e:
log.exception("Exception setting processor affinity")

Saturday, March 03, 2007

Python, Php Web programming

-- collection of comments from others
http://blog.ianbicking.org/why-web-programming-matters-most.html

"Trying to explain to people how to do Web programming in Python, or even trying to convince them to let me do Web programming in Python (instead of say PHP) has been an embarrassment. (This despite my opinion that PHP is an embarrassment to the term "programming language".)

I have long believed that Web scripting is the domain with the biggest bang-for-buck you can get out of a high-level language, mainly because the Web is the universal user interface. Once a program is placed on the Web, its functionality becomes instantly accessible to millions of people. Tiny, simple programs can become useful groupware tools.

Not all is lost, though. PHP succeeded at displacing Perl as a widespread Web programming language, so maybe it can happen again. Python can still do many things that other languages can't -- for example, cgitb exploits Python's unique strengths to provide a huge win for Web developers. "

" The vitrol that Python programmer's have for PHP has always baffeled me. Frankly, part of the reason I've avoided learning Python is because every Python programmer I've ever met has been a prick about my current choice in programming language. PHP works, I enjoy programming in it, I like the way it feels and reads, and the user community is incredibly supportive. More importantly, I've built some seriously effective web applications using it. If you want me to bother learning Python, loose the 'tude, dude.

Seriously, every language has its problems and it's quirks. PHP is far from perfect (e.g. no namespaces), but many of Python's language design features, such as the meaningful whitespace concept, I find unpleasant to work with. (A little too much like FORTRAN for my taste.) That doesn't mean that I don't think its a good language, or that Python programmers are bad people. (Just pooly socialized.) Obviously people have done a lot of great work in Python, and its a very useful tool. But its also a language that has a very different syntax from PHP, PERL, JavaScript, Java - languages that web people are familiar and comfortable with. If you want to get us to part with our semicolons, curly braces, and crazy bohemian whitespace, you're going to have to be nicer to us, and more polite about the tools we love. "


"I'm a PHP/Java/Ruby/Python programmer. I tried once to talk (but it's amazing how some people does not know how to talk) with a influent Python local dude about this. I told him that mod_python will spread more easily if it could show all it's power running on Apache 1.x, since there's is a LOT of websites still running Apache 1.x.

That was worst than insult his mother. He became mad, angry, asked me if we need to use old tools, that is a stupid idea blah blah blah.

He did not see the point there. I was thinking in a way that could help to, for example, THOUSANDS of PHP coders try mod_python (easy), without upgrade their webservers (harder) while PHP still marked Apache 2.x as experimental. But he was not able to talk about that. I told his so beloved tool could not work perfectly (and I was able to help if there was a way, on that moment) on a older enviroment, and he became mad, offended. Stupid. Idiot.

While this kind of behaviour still exists on the Python community (and believe me, there is a lot of situations like this), the tool will not even go closer where PHP is. While PHP is not a half of the language Python is (and I think Python is very better than PHP), some Python dudes are really hard to deal."

" You've clearly articulated a deep frustration that I have felt for several years now. I would love to do web programming in Python but I know that pragmatically PHP is a better choice despite its inadequacies as a language. Finding affordable Python hosting is not easy ; choosing a framework is not easy. Even when frameworks are well documented - like modpython - I would like more than just the bare documentation i.e. books.

For commodity hosting to emerge and books to be written the community has to agree on one framework, develop it further and make it easy for new programmers to get started. I worry that by failing to recognise the importance of the web and adding further complexities to the language Python will actually begin to lose users.



Tuesday, January 03, 2006

c++ constant reference
C++ Memory Manament: What is the purpose of a constant reference?
Q: What is the purpose of a constant reference?

A: Passing by a constant reference avoids creating a temporary object (thus copying) and thus can vastly improve performance.

However passing constant references to the standard data types (char, int, long, double, ...) does not result in any performance gain. Usually, these types are passed by value instead.

Sunday, December 25, 2005

java interview questions

http://www.allapplabs.com/interview_questions/java_interview_questions.htm