There are several products that implement your idea. The most famous one is the Adxstudio, you can find a community edition (also for CRM 4.0) at this address:
http://community.adxstudio.com/products/adxstudio-portals/
After you can check the source code, but they use C#