Wednesday, 21 March 2007

ODBC Escape sequences!

In other words: those curly bracket things in SQL. What? curly brackets in SQL? Yes! Imagine that :)

The idea is that most database systems adhere to the ODBC standard, at least ODBC 1.0. That means that, when you communicated with a database, you can send so called ODBC escape sequences that are translated into the SQL engine native objects.

Quick example: SELECT {d '2007-03-15'} will work in all ODBC 1.0 compliant DBMSs, including Microsoft SQL Server, MySql, PostgreSQL, Oracle, etc. and select a date object from 15 of March 2007, no matter the server configured country or language.

Interested yet? You can read the ODBC Programmer's Reference for more details. Short story shorter, here are the working and interesting parts (to me) of the ODBC escape sequences:
select {d '2007-02-13' }
select {t '22:20:30' }
select {ts '2007-02-13 22:20:30' }
select {fn curdate()}
select {fn curtime()}
select {fn User()}
select {fn Database()}
select {fn week(getdate())}
select {fn quarter(getdate())}
select {fn monthname(getdate())}
select {fn dayname(getdate())}
select {fn curdate()}
select {fn dayofweek(getdate())}
select {fn dayofyear(getdate())}
select {guid '12345678-1234-1234-1234-123456789012'}

Tuesday, 20 March 2007

Ajax enabling your controls

Ok, so you have the greatest control library ever made and Microsoft releases Asp.Net Ajax and none of them work anymore. What is one to do?

Eilon Lipton to the rescue! He writes a very good article about Ajax enabling your controls without linking to the System.Web.Extensions dll.

However, the article is a bit outdated. Here is a piece of code that solves the problems (at least for the latest version of Asp.Net Ajax):
Type scriptManagerType = Type.GetType("System.Web.UI.ScriptManager, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", false);
 if (scriptManagerType != null)
 {
 RegisterClientScriptResourceMethod = scriptManagerType.GetMethod("RegisterClientScriptResource", new Type[] { typeof(Control), typeof(Type),typeof(string) });
 RegisterStartupScriptMethod = scriptManagerType.GetMethod("RegisterStartupScript", new Type[] { typeof(Control), typeof(Type), typeof(string), typeof(string), typeof(bool) });
 }


This is because the namespace has changed since the writing of Elion's article from Microsoft.Web.UI to System.Web.UI and there are two methods named RegisterClientScriptResource and two named RegisterStartupScript so you have to get the right one. Else you get the "Ambiguous match found" error.

There you have it!

Creating a Web User Control in NET 2.0 that can be validated

The .NET validation framework has two parts, the client Javascript validation and the server validation. That means that the Javascript code needs a value to validate and the server validation needs a property to validate.

So, first step, you create your web user control by putting some controls in it. Then, you want to add a validator to the page to reference the newly created user control. And you get the error "Control '{0}' referenced by the ControlToValidate property of '{1}' cannot be validated.". Why? because every control to be validated needs to be decorated with the ValidationProperty attribute:
[ValidationProperty("Text")]
public partial class ucDate : System.Web.UI.UserControl

Adding the first line to the control tells the validation framework to use the Text property of the UserControl.

Next step, you run the page and you notice the javascript doesn't work. The client validation works on html controls, by looking (recursively) for a 'value' attribute. When one looks at the source code, though, there is no html control that has the id of the user control. It doesn't use a span or a div to encapsulate its controls. All the controls have the id to show they are children to the user control, but the actual user control does not appear in the html source. So what is there to do?

<div id='<%=ClientID %>'></div>

You put all the controls in the ascx file of the User Control into this div. There you go! The validation works!

There is one more quirk regarding web user controls that have more children that render an html object with a 'value' attribute. In that case, remember that the validation starts from the very top, in our case the div. One could build simple javascript functions on the onchange or onsubmit javascript events, for example, to add a value attribute to the div. Best way would be using the onsubmit event, but be careful that the validation sequence also runs on the onsubmit event.

TextBox2.Attributes["onchange"]="document.getElementById('"+ClientID+"').value=this.value";


On popular demand, here is a complete example codeThis is a control that holds two TextBox controls. The control will be validated both on server and client by the value of the second Textbox, the first will be ignored.


using System;
using System.Web.UI;

[ValidationProperty("SecondTextboxValue")]
public partial class vuc : UserControl
{
public string SecondTextboxValue
{
get { return tbValidated.Text; }
}

protected void Page_Load(object sender, EventArgs e)
{
string script =
string.Format(
@"var vuc=document.getElementById('{0}');
var tb=document.getElementById('{1}');
if (vuc&&tb) {{
tb.vuc=vuc;
tb.onchange=function() {{ this.vuc.value=this.value; }}
}}"
,
ClientID, tbValidated.ClientID);

ScriptManager.RegisterStartupScript(Page, Page.GetType(), UniqueID + "_submit", script, true);
}
}


The ascx looks like this:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="vuc.ascx.cs" Inherits="vuc" %>
<div id="<%=ClientID %>"> value="<%=tbValidated.Text%>"
<asp:TextBox ID="tbIgnored" runat="server"></asp:TextBox>
<asp:TextBox ID="tbValidated" runat="server"></asp:TextBox>
</div>


How it works:
  • The javascript validator will look for an html element with the same id as the user control. If it has a value attribute, it will be validated, else it will go to the next control in the hierarchy. If the containing div would not have a value attribute, then the validation would have occured on the first textbox value, as the first element that has a value attribute. That's why the value attribute will be set on textbox change and when first loading the page.
  • The server validation will work because of the user control property that exposes the Text value of the second textbox and the ValidationProperty attribute that decorates the code.


Monday, 19 March 2007

Geological history of Earth

I am just linking this small page about the evolution of Earth. You may see when the planet formed, how the moon appeared, the different geological eras, major meteor impacts and extinctions, the evolution of species and some information about the impact humans have on the environment lately.

Sunday, 18 March 2007

Audio Spotlight - the narrow beam of sound

I've told a lot of people about this, but forgot to blog about it. Shame on me, because this revolutionary concept can change the way we think of sound.

Audio Spotlight enters the category of directional sound systems, more precisely it creates sound from ultrasound. The result is that you can direct a single speaker towards a certain area, and only people in the area can hear the sound.

There are drawbacks, as obstacles getting in the way of the sound beam block the sound from reaching further on. There are limitations to the frequency response and the dispersion pattern. I also don't know if the system can create loud sounds as this would probably need high power ultrasound and I don't know how healthy that would be.

But, even so, the idea is marvelous. As you can see from the animation from the Audio Spotlight site, you can attach a sound to a picture in a gallery, and the sound will only be heard by the people in from of the picture. Imagine that in a museum. Or think about having a restaurant with audio spotlight above the tables, playing whatever music they want and not bothering the other people. Combine it with some form of sound barrier between tables and you get a classy private place with no walls and a lot of people. Or think of a disco where you can separate the sound of each instrument and play it in a slightly offset area so people can dance to the music equalized however they like it. Or even a club where people can hear the music loud on the dance floor and really weak at tables, so they can talk.

This invention comes (of course) from MIT, more precisely from Dr. Joseph Pompei while he was a student at the MIT Media Lab, himself son of another distinguished doctor, Dr. Francesco Pompei.

Update:
However, with great power comes... ah, forget Spiderman! Anyway, there are voices expressing concern on the evil use of such technology. Like this link here, expressing the opinions of Barry Blesser, one of the most respected names in digital audio.

Now, I guess that the best invention ever would be directional earplugs! :)

Friday, 16 March 2007

Ray Tracing, a graphics model for realistic lightning using low resources

I found this article on BBC News that told of a series of new algorithms for 3D image rendering using the tracing of light rays rather than polygonal rendering. They also use less resources than traditional algorithms. Interesting enough, so I searched the Internet. I think this will usher a new era of computer games, not to mention a boom of cheap 3D movies. See how the reflections generate secondary and tertiary reflections in the image?

Check out the site of the OpenRT project for videos on how this works.

Update 2011: Apparently the site is pretty much dead except the front page. It's an old post anyway.

Other Links:
Ray Tracing basics at Wikipedia
A free open source (GPL) OpenRT implementation

svchost 100% CPU utilisation

For a while now, whenever I start my computer at work, I get to wait about 5 minutes with my CPU up to 100% due to svchost.exe. Of course, this being an important component of Windows, I cannot delete or disable it, neither can I see what subprocess is causing this utilisation with the normal Task Manager. However, one can download Process Explorer and see a lot more information. I highly recommend it.

Anyway, back to the original problem. I noticed that the problem was the ntdll.dll (ntdll.dll!RtlAllocateHeap+0x18c to be exact) which is, again, a Windows important file.

Only googling to the extreme did I find that the issue is caused by Windows Update, scanning your computer each time you start it. If you disable Windows Update, you don't get the updates, but you get rid of the wait.

Here is a discussion with Microsoft MVPs about possible solutions.
Also, try this link.

And if you do have Process Explorer, you can set the priority of the offending task to Bellow Normal, which will allow you to run any program normally while the Windows Update process runs only on spare CPU. Normal Task Manager does not allow you to change the priority of the process.