2009
05.28

NXCOMPAT?

Recently, while developing a .NET Winforms desktop application, I needed to integrate a legacy .OCX that did terminal emulation for a serial device.  I had been using XP to develop and had run into no problems until I tried to deploy to a Vista machine.  When running the app on Vista, I was greeted with this exception:

Unable to get the window handle for the ‘myControl’ control. Windowless ActiveX controls are not supported.

Not much help here.  The “inner exception” was equally uninformative:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The location of the exception was at ((System.ComponentModel.ISupportInitialize)(this.myControl)).EndInit();

Pretty worthless information.  After googling around for awhile, I ran across Ed Maurer’s helpful blog (thanks Ed) and he discusses some breaking changes that .NET Framework 2.0 SP1 introduces (also applies to .NET 3.5 Framework).
Apparently in the header of a PE file, there is a flag called IMAGE_DLLCHARACTERISTICS_NX_COMPAT.  This flag tells Vista whether or not to enable something called DEP (Data Execution Prevention) in your process.  If this flag is set, and your legacy .OCX does not have the flag set (which it would not by default), Vista won’t allow your .OCX to load.
Ed’s blog says that Microsoft likes DEP so much that .NET Framework 2.0 SP1 emits binaries with the IMAGE_DLLCHARACTERISTICS_NX_COMPAT on by default (it was off before).  This is going to cause unexpected expenses and time commitments for developers that deploy new builds to customers only to find that suddenly their apps don’t run on Vista anymore.  In my opinion, it is very wrong-headed to release a service pack with these kind of breaking changes.  Bad judgment, Microsoft.

Solutions?
-Disable DEP on the affected machines (run this line at a command prompt:  bcdedit.exe /set {current} nx AlwaysOff ). This is not a very good option for app developers for obvious reasons.
-Update the .OCX to build with a newer compiler (newer than ATL 7.1 and set the /NXCOMPAT linker flag – http://msdn.microsoft.com/en-us/library/ms235442(VS.80).aspx).  This is not an option with 3d party .OCXes, however.
-Run a post-build script in the .NET app that sets NXCOMPAT to NO and redeploy your app.  This script worked for me:

call "$(DevEnvDir)..\..\VC\bin\vcvars32.bat"
call "$(DevEnvDir)..\..\VC\bin\editbin.exe" /NXCOMPAT:NO "$(TargetPath)"

This will let the app run and load the OCX without a problem, but if you are trying to debug, it still has the same exception thrown.

TODOs for Microsoft:
-Don’t introduce this kind of breaking change in a “mandatory” service pack release.
-Provide better error info for the exception thrown.
-Document this somewhere easier to find than the back pages of an msdn blog.

Midniteblogger

2009
03.23

Visual Studio is incredibly slow to load and that makes it almost prohibitively hard to use.

Some examples:
-I am typing this post while waiting for Visual Studio to get done with whatever it is doing.  I merely opened an .aspx file and that was 11 minutes ago.  The application window is “Whited out” (in Vista) and the title bar says “Microsoft Visual Studio (Not Responding).”  The site has quite a few files, but is not incredibly large.  Hasn’t Microsoft ever heard of multithreading UIs?

-After the site finally loads, whenever I edit a page, there is a constant annoying delay that locks the UI for a couple of seconds after doing the simplest of things (like pasting some text).  The status bar continues to inform me that it is “Getting file ‘Web.config’ from the Web.”    How often does it need to do this?  Once would seem sufficient, but not for Visual Studio.

-Loading an .XML file.  OMG.  This can also take on the order of MINUTES to load a 20K file.  Meanwhile, Visual Studio is locked solid and “Whited out.”   What is it doing to these files, anyway?

I have really wanted to develop a new book site with Visual Studio, but am seriously considering switching to php because of the slowness of using Visual Studio.

Anyone else had this problem?  (Yes I have tried it on different machines, yes I have a fast connection, and yes, this machine is well-powered with a quad-core and 7 GB of memory).

At Tech-Ed 2007 I sat with a guy from the VS dev team on the bus and bent his ear for a few minutes about this problem (it was the same in Visual Studio 2005).  He sounded pretty clueless, but said he would look into it.   Didn’t look hard enough, I would say.  At least it sure didn’t get fixed.

Well, I can get back to my project now.  Total time to load one small aspx page: 13 minutes.

midniteblogger

2008
12.12

Recently I wanted to show a splash screen form in an application, loading the image file from the disk at run time instead of binding it into the executable. It’s easy enough to load the image with Image.FromFile, but if the file is not there, I wanted to fail gracefully and just close the form.
When I called Close() from the FormLoad event, however, the following exception greeted me: Value Close() cannot be called while doing CreateHandle().
What does that mean?
A little searching around coupled with my experience in traditional Windows programming led me to conclude that the .NET runtime doesn’t like to have it’s forms closed while they are being created. In the C++ days, we would just PostMessage with WM_CLOSE to the hWnd, and all would be well. Hmmm… What to do in C#?
In searching, I ran across the BeginInvoke method, which “Executes a delegate asynchronously on the thread that the control’s underlying handle was created on.” Sounds interesting.
What delegate to use, however, was the next question. MethodInvoker is the answer. According to the Microsoft docs, MethodInvoker “represents a delegate that can execute any method in managed code that is declared void and takes no parameters.” The intended use is for “when you need a simple delegate but do not want to define one yourself.” Exactly what I was looking for.
So I defined a simple function in my form class that would be used by the delegate:

private void CloseMe()
{
  Close();
}

In the CloseMe method, I simply do what I wanted to do in the first place – call Close() on the form.  Close() is now safe to call because we are no longer in the FormLoad event.

From the FormLoad event, if the image file was not found, simply call the asynchronous BeginInvoke method:

void FormLoad(object sender, EventArgs e)
{
  if(imageNotFound)
  {
    BeginInvoke(new MethodInvoker(CloseMe));
  }
}

It works great and no more exception!
midniteblogger

2008
09.23

Getting data across process boundaries can be tricky sometimes, especially when one of the processes is running managed code (.NET) and one is running a native executable.  It gets even more complicated if you want to do it on Windows CE.

In Win32, if I want to call from COM to .NET, it is pretty straightforward because the CLR will create a managed object and a COM Callable Wrapper (or CCW) that acts as a proxy for the COM object to talk to the managed object.  It’s a little clunky, but it works and is well documented on MSDN.

On Windows CE or Windows Mobile, however, (as best as I can determine), the CCW option does not exist.  The CE runtime won’t allow an unmanaged process to “host” the CLR so the CCW proxy can be created.  So how do you get data from unmanaged to managed code on Windows CE, then?

Good question.  I found the answer in the WM_COPYDATA message.  This cool little message lets you send data between processes, and even seems to work between managed and unmanaged code.

How to use it?

Let’s say that on the unmanaged side I want to send a string of data, “Hello”, to a managed .exe written in C#.  The unmanaged code is not COM, just regular old C++.
To set up the unmanaged code, declare a COPYDATASTRUCT, and fill out the members:

COPYDATASTRUCT cds;
cds.dwData = 0;
//Unicode chars. Don't need room for NULL on end
cds.cbData = 5 * sizeof(WCHAR);
cds.lpData = L"Hello";

Then just do a SendMessage with the address of cds:

::SendMessage(hManagedWnd, WM_COPYDATA, (WPARAM)myHwnd, (LPARAM)&cds);

Whoops, what is hManagedWnd? It is the HWND of the managed window where you are sending the data. How did I get that handle? With a call to FindWindow, of course. Just fill in the name of the window you are looking for and you get the handle back.

HWND hManagedWnd= FindWindow(NULL, L"NameOfManagedWindow");

Awesome.
So how do I catch this on the managed side? Good question.
Just to make this a little more interesting, I create a little managed window that just sits and waits for a WM_COPYDATA message. .NET has a handy class called MessageWindow that “Provides the ability to send and receive Windows-based messages.” Just what I am looking for.
Declare the COPYDATASTRUCT type:

[StructLayout(LayoutKind.Sequential)]
struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}

Derive a class from MessageWindow:

public class MsgWindow : MessageWindow

Define WM_COPYDATA:

public const int WM_COPYDATA = 0x004A;

Set the text of the window in the constructor:

public MsgWindow(Form1 msgform)
{
this.Text = "NameOfManagedWindow";
}

Override the WndProc (Yes, you can get to the WndProc in .NET):

protected override void WndProc(ref Message msg)
{
  switch (msg.Msg)
  {
    case WM_COPYDATA:
    {
      COPYDATASTRUCT cds = new COPYDATASTRUCT();
      cds = (COPYDATASTRUCT)Marshal.PtrToStructure
              (msg.LParam, typeof(COPYDATASTRUCT));
      if (cds.cbData > 0)
      {
         byte[] data = new byte[cds.cbData];
         Marshal.Copy(cds.lpData, data, 0, cds.cbData);
         UnicodeEncoding ue = new UnicodeEncoding();
         String str = ue.GetString(data, 0, data.Length);
         //At this point, str will contain "Hello"
      }
    }
  }
  base.WndProc(ref msg);
}

Create an instance of MsgWindow in your form’s constructor:

public partial class Form1 : Form
{
  MsgWindow MsgWin;
  public Form1()
  {
    MsgWin = new MsgWindow(this);
  }
}

In this way, even though it is a bit awkward, you can get data across from unmanaged to managed code. Working with binary data would be a bit trickier, but will still work. Underneath it all, Windows creates a memory-mapped file to handle the actual data transfer, which saves you the trouble of doing it yourself.
midniteblogger

2008
08.21

Malware everywhere

So, regarding my last post, perhaps I owe an apology to YouTube regarding malware distribution.  I have been chasing the problem for about a month now, and have finally narrowed it down to a virus known as “MPack” from Russia.  This is a really nasty one and appears to have several “ports of entry” into a web site.

 From what I can tell, the attacks came in through the following php that I innocently installed on my site (not this site), but have since removed:

  •  php Hamweather installation (nice app that gives weather in various locations).  Hacked through appending .include to the URL with a perl script reference on the end.  I notified them of the attack.  Hopefully they have corrected it by now.
  • php Mortgage calculator.  Supposed to give mortgage estimations at various rates.  Looks like it was malicious from the start (especially in some caching stuff with names like ’smartie’).
  • WordPress blog – could be the ‘free’ template I downloaded.  Still not sure how they hacked this one.

What happened then, was that bad files got copied all over the site through the above-mentioned holes:

  • modsoap.php – This one periodically injected really evil Java Script into the <head> section of the index.php page.  The script looks like the following:   <script language=JavaScript>function dc(x){var l=x.length,b=1024,i,j,r,p=0,s=0,w=0,t=Array(lots of numbers and more code here…);  Once executing, this script tries to download ActiveX controls and run .exes, exploiting IE weaknesses.  These guys did a good job of summarizing the details of the attack.
  • news.php – Looks like a bunch of random characters wrapped in a php base64_decode, unzip and eval calls.  I think it places modsoap.php elsewhere. 

Hopefully its gone now, but it will never be forgotten!

This is definitely a lesson learned in not trusting php script written by others even if they are reputable folks.

 midniteblogger.

2008
08.05

Publishing and managing web sites is always an interesting challenge and it helps to be able to generate extra income from them from programs like AdSense.  Recently, Google has allowed its publishers to monetize YouTube views/clicks by putting some script on their sites.

That is great, or so I thought, until the other morning I got a couple of emails from Google saying my site was distributing “malware.”  Quite a surprise to me since I strive to keep my sites as clean as possible.  Sure enough, upon going to the site, my anti-virus protector went crazy, complaining about JS/Psyme.J virus, Bugnraw!generic virus (Bugnraw!generic was detected in …\UIIL.EXE), and Hopee!generic virus.  It kept trying to download something from golnanosat.com/in (213.155.0.242) and wanting me to approve an exe to run that was signed by HiPoint Ltd, S.A.

What is going on here??  After a couple of days of digging, I believe the source was the YouTube video strip that I was embedding in my pages.  I took it off the page, and the virus warnings stopped.

It’s nearly impossible to get Google to take the “malware” warning off your site, but how ironic that it might be caused by a company that they own.  I hope they will at least take a look at this problem and determine if someone is hacking their YouTube publisher scripts.

Anyone else experiencing the same problem?

midniteblogger

2008
06.11

More Fun with Interop

Now let’s say we have a “C” exported function that looks something like this:

void MyFunction(void* myData);

This, of course, is inherently unsafe, because the void* could represent anything. In the wonderful world of “C”, however, such a construct is frequently used.
We must assume that the caller knows exactly what the called function is expecting the void* to point to. Knowing that, then, how would we call this function from C#? Good question.
I puzzled over it a bit before realizing that a void* is allowed in C#. No way, you say. That’s what I thought.

Using P/Invoke for this example, in your DllImport declaration, just put the “unsafe” keyword like so:

        [DllImport("MyDLL.dll")]
        public static unsafe extern void MyFunction(void* myData);

Using “unsafe” allows the code to compile and the compiler to be happy with a void* in C#. Cool. So how do you call it from C#?
This is one of those instances where you need to create a “pinned” address so the garbage collector doesn’t move the memory around during the call. For the sake of simplicity in this example we are just going to use an array of bytes for the void*. Put everything in an “unsafe” block so the C# compiler is happy with a void* :

public void AMethod()
{
  unsafe
  {
    void* vaddr = null;
    Array arr = Array.CreateInstance(typeof(byte), 10);
    GCHandle handle = GCHandle.Alloc(arr, GCHandleType.Pinned);
    vaddr = (void*)handle.AddrOfPinnedObject();
    //Call the DllImport function
    MyFunction(vaddr);

    if (handle.IsAllocated)
      handle.Free();
  }
}

Assuming that MyFunction “knows” that it is going to get an array of 10 bytes (in this case), the call will work and both the C++ and C# sides will be happy. Of course, you probably should put something interesting in the array before sending it across. I’ll leave that to you.

midniteblogger

2008
05.29

Fun with Interop

Coding with C# is fun (most of the time) and really takes a lot of the work out of stuff, like memory allocation/deallocation, that was pretty grungy in C++. Unfortunately, sometimes a new .NET component has to talk to a legacy C++ API and that’s where things can get interesting.
I want to look at a hypothetical example where we are creating a managed wrapper around an old-style extern “C” exported interface.
This example will use the method known as P/Invoke (or Platform Invoke) to call from C# to the C++ interface. Passing primitive types is easy, since there is a pretty straightforward correlation between the managed and unmanaged types. But what about if we want to pass a wchar_t* (pointer to 16-bit UNICODE character) to an Extern “C” exported function as an embedded structure member? How could we do that from C#?

Assume the C structure looks like this:

typedef struct
{
  const wchar_t *Address;
  //other stuff
}MyStruct;

and the exported C function looks like this:

void foo(MyStruct* mystruct);

Assume that the C++ implementation is just going to examine the contents of the Address wchar_t* in the structure; it is not going to change it in any way.
Calling that from C++ is easy since it knows about pointers. C#, however does not know about pointers — just references to objects. It turns out to be a bit of a pain to call from C#.
What I did was define a C# structure that mimics the “C” one:

[StructLayout(LayoutKind.Sequential)]
internal unsafe struct _MyStruct
{
  //IntPtr acts as placeholder for char*
  public IntPtr Address;

  //Managed memory handle
  private GCHandle hAddress;
}

What we doing here is creating a wrapper around a raw GCHandle memory handle and managing the address of the bytes ourselves in the IntPtr. Yuck. Keep reading, it gets better.

Let’s add to the struct:

[StructLayout(LayoutKind.Sequential)]
internal unsafe struct _MyStruct
{
  //IntPtr acts as placeholder for char*
  public IntPtr Address;

  //Managed memory handle
  private GCHandle hAddress;

  internal _MyStruct(string str)  //c'tor
  {
    UnicodeEncoding ue = new UnicodeEncoding();
    byte[] arr = ue.GetBytes(str);

    //extra 2 for null terminator char on end that "C" expects
    Array arr0 = Array.CreateInstance(typeof(byte), arr.Length + 2);
    Array.Copy(arr, arr0, arr.Length);

    hAddress = GCHandle.Alloc(arr0, GCHandleType.Pinned);
    Address = hAddress.AddrOfPinnedObject();
  }
}

We get the raw bytes of the incoming string, create a byte array of that size (+ 2 extra for the null char that “C” expects), then GCHandle.Alloc a “Pinned” address that we remember. Since “C” expects an address of a “string” that is not going to move around, we have to “Pin” the memory and get its address with GCHandle.AddrOfPinnedObject and remember that too.
Yuck. Keep reading, it gets better.

Let’s add to the struct again:

[StructLayout(LayoutKind.Sequential)]
public unsafe struct _MyStruct : IDisposable
{
  //IntPtr acts as placeholder for char*
  public IntPtr Address;

  //Managed memory handle
  private GCHandle hAddress;

  internal _MyStruct(string str)  //c'tor
  {
    UnicodeEncoding ue = new UnicodeEncoding();
    byte[] arr = ue.GetBytes(str);

    //extra 2 for null terminator char on end that "C" expects
    Array arr0 = Array.CreateInstance(typeof(byte), arr.Length + 2);
    Array.Copy(arr, arr0, arr.Length);

    hAddress = GCHandle.Alloc(arr0, GCHandleType.Pinned);
    Address = hAddress.AddrOfPinnedObject();
  }

  public void Dispose()
  {
    if (hAddress.IsAllocated)
      hAddress.Free();
  }

}

Here, we are deriving from IDisposable so we can free the memory handle manually in our Dispose method. Isn’t managed code supposed to free us from this kind of grunge? Guess not.

So, to call this puppy, we could do something like this:

[DllImport("MyDLL.dll")]
public static extern void foo(ref _MyStruct mystruct);
...

string strHello = "hello";
_MyStruct mystruct = new _MyStruct(strHello);
try
{
  //The "C" function gets "hello" in the struct Address member
  foo(ref mystruct);
}
finally
{
  mystruct.Dispose();
}

Sadly, we CANNOT do the following elegant call:

//Won't compile ***
using(_MyStruct mystruct = new _MyStruct(strHello))
{
  foo(ref mystruct);
}

Why won’t it compile? Because, as the compiler complains, you “Cannot pass ‘mystruct’ as a ref or out argument because it is a ‘using variable’”. Hmmm… Oh well. Another thing we live with.

One caveat here, the _MyStruct structure has to mirror the “C” struct, so if the “C” struct has “const wchar_t *Address” as its first member, _MyStruct has to have “public IntPtr Address” as its first also. If there were a second wchar_t* in the “C” struct, _MyStruct would have to have its second “public IntPtr” come immediately after the first and BEFORE any of the GCHandles. The reason here is that the memory layouts have to be the same if you are going to pass a _MyStruct with IntPtr members to an unmanaged function that expects a struct* with wchar_t* members. Make sense?
Oh, and don’t try to make _MyStruct a class. Bad things will happen.

Got a better solution? Lemme hear it.

midniteblogger

2008
04.05

Sometimes working with a managed language like C# can make you lazy. Having cut my programmers teeth on C++, I learned very early that if you “new” something you must also “delete” it. Forget and you get a memory leak.

After moving to C#, however, I occasionally become complacent and begin to think that the garbage collector (GC) will solve all wrongs with my coding style. I re-learned that lesson the hard way with database connections recently, and almost had a site shut down because of it. Perhaps that experience will save you some pain.

Managed code is awesome. You can “new” and allocate all kinds of resources however you want and the GC will just clean up for you. Right? Well, not exactly. It is true that the GC will free “new”ed memory once all references to it are released. The problem (especially with a web app on a busy site) is that by the time the finalizer queue runs, the server box could be out of a scarce resource like database connections and further requests will fail often causing the site to block for extended periods of time.

Let me give you an example. Let’s take a class derived from DbConnection like SqlConnection (for SQL Server databases) or OdbcConnection (for generic connections to databases like MySQL). We’ll use it by creating our own derived class and holding an instance of the connection as a class member. Just to be safe, we’ll let the finalizer close the DB connection for us (since database connections don’t tend to close themselves) so we don’t leak any resources.
Good idea? Let’s see:

public class DBUtilities
{
  private SqlConnection m_dbSqlConn;

  ~DBUtilities()
  {
     // Our safety net?
      if (m_dbSqlConn != null)
          m_dbSqlConn.Close();
  }

    public SqlConnection GetSqlConnection()
    {
        try
        {
            m_dbSqlConn = new SqlConnection();
            m_dbSqlConn.ConnectionString = "MyConnectionString";
            m_dbSqlConn.Open();
            if (m_dbSqlConn.State != ConnectionState.Open)
                return null;
        }
        catch (Exception e) {}

        return m_dbSqlConn;
    }

}

//Use the class:

void UseDatabase()
{
    DBUtilities dbu = new DBUtilities();
    SqlConnection sqlConn = dbu.GetSqlConnection();
    SqlCommand cmd = new SqlCommand("Select * from aTable", sqlConn);
    SqlDataReader dr = cmd.ExecuteReader();
    dr.Read();
    //Do something with the data
    .....
    dr.Close();
}

Cool. The finalizer for DBUtilities will close the database connection for us, won’t it?
Well, sure, but the important question is “when?”. The answer is “whenever the GC gets around to it.” That could be several seconds later, or longer. In my case, the games web site (The best online games) where I was using the code above would simply start blocking after a few database requests. Bad news. It gets worse.

The hosting company (CrystalTech) I was using at the time called me with a problem and an ultimatum. The problem was that my site was hogging resources (I had to figure out that it was database resources) and the ultimatum was that they were shutting off my site until I could prove to them that it was well-behaved again.

Scramble. Scramble.

Fortunately it didn’t take too long to dawn on me that the scarce resource was the database connections, and doing something as simple as calling

sqlConn.Close();

when done with the SqlDataReader reads and taking the Close() call out of the class finalizer solved the entire problem. Hard to believe? It was for me, and it was a hard lesson in non-deterministic finalization.
I think calling Dispose on the connection would have the same effect, but have not proven that yet.

In the end, I switched the site to Godaddy because of CrystalTech’s non-helpful attitude and now everything is humming along smoothly for the happy games players.

midniteblogger

2007
11.18

Continuation of Part 1

AJAX sample code – calling from a .NET page with C#

Now the good stuff.  How do we implement AJAX in our .NET pages?  The answer is surprisingly and pleasantly simple, as it turns out, and is not actually particular to any one scripting language, be it C#, php, perl or whatever.

The secret to AJAX is the XMLHttpRequest object.  Unfortunately, it has not been implemented in a totally consistent manner across browsers (what else is new?), but as it turns out, the code branching logic needed to overcome this problem is not bad at all.  All we have to do is test for the existence of the appropriate object with an “if” statement and we are ready to roll.

For the purposes of this simple AJAX tutorial, when my .aspx page loads, I am going to request data from a mythical web service (could be Amazon, Ebay, or any number of others), and present it in an asynchronous manner to the user when it comes in.  If the service is slow or if I am querying many web services in this page, the user will not be left waiting for them all to come back with a response.  The data will show up as it comes in.

Pieces to the puzzle

The first thing we need is a JavaScript function to call on some kind of event.  I have chosen an “onload” event for the page, but it could be on a button click, edit box “blur,” image load or whatever.  For the example here, all we need to do is put the following in our HTML page body tag:

<body onload=”AsyncDataRequest(1)”>

When the page loads, the browser will make sure that AsyncDataRequest gets called with a parameter of 1.  For the following functions, make sure all the code is in a <script language=”JavaScript”> </script> tag in the <head> section of your .aspx page.  Also, put a <span id=”ProductInfo1″>  </span> in your page where you want the response data to go.

The data request function simply looks at the page parameter passed in (optional), formats a request url and calls the function that actually makes the Http Request:

function AsyncDataRequest (page)
{
    var varProduct;
    var prodSpan;
    if (1 == page)
    {
        prodSpan = 'ProductInfo1';
        varProduct = 'Product1';
    }
    url = 'http://www.mysite.com/DataRequest.aspx?Query=' + varProduct;
    loadXMLDoc (url, processRequest, prodSpan);
}

We pass in a “page” parameter so we can more easily branch our logic based on what object is making the request.  Here, for page “1″ we specify the name of a <span> tag (”ProductInfo1″) that will be filled in with our data later on and a product tag (”Product1″) that lets us return more specific information from our query.

We simply formulate the URL with the desired parameters and call another JavaScript function “loadXMLDoc.”  That function looks like this:

function loadXMLDoc (url, rsFunc, prodSpan)
{
    var reqHTTP;
    if (window.XMLHttpRequest)
    {
        reqHTTP = new XMLHttpRequest();
        reqHTTP.onreadystatechange = function()
        {
            rsFunc(reqHTTP, prodSpan);
        };

    reqHTTP.open("GET", url, true);
    reqHTTP.send(null);
    }
   else if (window.ActiveXObject)
   {
        reqHTTP = new ActiveXObject("Microsoft.XMLHTTP");
        if (reqHTTP)
        {
            reqHTTP.onreadystatechange = function()
            {
                rsFunc(reqHTTP, prodSpan);
            };

        reqHTTP.Open("GET", url, true);
        reqHTTP.send();
        }
    }
}

This function tests for the existence of the XMLHttpRequest object and makes our asynchronous request for data.
Notice how we have to branch our XMLHttpRequest creation with the if/else if so both IE and Firefox are happy.  With Firefox, XMLHttpRequest is a built-in object, but with IE, it is an ActiveXObject.  Such is life;  just accept it and go on.

The interesting thing here is the assigning of the “onreadystatechange” event of the request object to the function we want to be called when the event fires.  In case you haven’t seen it before, the onreadystatechange = function () syntax allows us to define what is known in JavaScript as an “anonymous function.”   The cool thing is that we can pass parameters to our callback function, and the script code will take care of preserving those parameters for the callback, even though it occurs later.

Note that “rsFunc” is the parameter we passed in to loadXMLDoc, which we called “processRequest.”  That is the function that will be called when the onreadystatechange event of the request fires (basically just when the request gets more data or an error condition).  More on that in a second.

The only things left to do here are call “Open” with the URL and “send.”

What does “processRequest” look like? I was hoping you would ask:

function processRequest(reqHTTP, prodSpan)
{
    if (reqHTTP.readyState == 4)
    {
        if (reqHTTP.status == 200)
        {
            response = reqHTTP.responseText;
            document.getElementById(prodSpan).innerHTML = response;
        }
    }
}

This is simple, boiler-plate code that looks for hardcoded numbers in the response. The readyState of the request has to
be 4 and the status has to be 200. Don’t worry about it, just accept it. Only under those conditions will the request give you good data.
Notice that we passed the request object that we created in loadXMLDoc to this function along with the <span> id originally specified in AsyncDataRequest.
Here, we get the response text from the request object, get the element of the document specified by id (prodSpan) and set its innerHTML to the response text. Voila. The text magically appears in the browser in the place where the <span> tag is.  Very cool.

Last piece to the puzzle — data!

So what does the code in DataRequest.aspx look like?  That’s mostly up to you.  That file does the dirty work of retrieving data from a database, 3rd party web service, validating user input against business rules, etc., etc.  Here’s a sample of what it might look like:

      String strQueryString = Request.QueryString["Query"];
      switch (strQueryString)
      {
        case "Product1":
            Response.Write(MyObject.GetAmazonData("Books");
            break;

        //Other product feeds responses here

        default:
            break;
      }

Here we are just branching our logic based on the Request string sent in the URL we formatted in the AsyncDataRequest function. Feel free to substitute whatever Request QueryStrings suit your needs.
In the GetAmazonData function you would request your data from the appropriate web service, format it (HTML would be desired here) and write it to the Response stream. Every thing else is automatic. Awesome.  You have to supply the logic in MyObject, however. :)

It’s OK for the GetAmazonData function to block for as long as it needs to, because the user is no longer waiting for the page to load.  This is the sweet part.   Here you could also do secret calculations or password validation, etc.

If you have done everything correctly, whatever HTML you put in Response.Write will show up in the ProductInfo1 <span> tag.

This should be a complete example that you can slice and dice to fit your own needs. If not, please post and let me know. Also, if you have found this helpful, please post your experience for others to read.
As you can see, this could easily be adapted to use in a php environment. The only thing that would be different is the trivial differences in syntax for the DataRequest page.

As an example, this link leads to a games site that has implemented Amazon Web Services as a monetizing tool to present games for sale:
Time Killing Games

Enjoy

midniteblogger