2005 2006 2007 2008 2009 2010 2011 2015 2016 2017 2018 aspnet azure csharp debugging docker elasticsearch exceptions firefox javascriptajax linux llblgen mongodb powershell projects python security services silverlight training videos wcf wpf xag xhtmlcss

"Common Language Runtime detected an invalid program"

If you've ever gotten this error you've probably been one of the most confused people in the world. In your debugging you may have seen that this message came from an InvalidProgramException.

Well, while this problem should be rare, here's an example harness of where you may see it.

// ThrowerHarness.cs
namespace ThrowerExample
{
  class ThrowerHarness
  {
    static void Main(string[] args)
    {
        try
        {
            Thrower.Start( );
        }
        catch (System.Exception ex)
        {
            System.Console.Write("Error: " + ex.Message);
        }
      }
    }
}

Alright, so where's it coming from?

In this case, it's actually coming from the IL.

// Thrower.il
.assembly ThrowerLib { }


.class public Thrower {
  .method static public void Start( ) {
    stloc.0
    throw
    ret
  }
}

This actually comes from invalid IL. In this case I'm putting 0 on the stack and then throwing...well, nothing really. This is not something a good compiler would create. If you see this it's probably a bug in the compiler or manually written IL.

Anyhow, to test the above do this...

ilasm /dll ThrowerLib.il
csc /r:ThrowerLib ThrowerHarness.cs

Atlas October 2005

If you are anything like me, you consider a technology is new as long as it's marked as experimental. Atlas still qualifies for being new...or even, pre-new. In any case, the October 2005 version of Atlas has been released and can be downloaded at the link below.

http://atlas.asp.net/

You can find a list of changes here: http://weblogs.asp.net/atlas/

Note that unlike WCF and WPF, which in my mind are stable for production, Atlas is still experimental and is only in the technical preview stages. Not that it will explode into pieces, but there is little to no documentation on almost all of Atlas and given the early nature of the product, things are almost guaranteed to change.

Cool SMS/VS2005 Integration Feature

Today I discovered a very wierd feature regarding SQL Management Studio 2005 ("SMS") and Visual Studio 2005 (of course I'm using the FREE standards editions from the MSDN/Technet seminars)

OK so here it is...

  • Open SMS
  • Navigate to a table and modify it.
  • Copy the text of one of the columns
  • Go to an ASPX page in Visual Studio 2005 and paste.

If you did it right you will see the weirdest thing in the world: it pastes a GridView linked to a SqlDataSource, which it also pastes.

<asp:GridView ID="GridView1" runat="server"
     DataSourceID="SqlDataSource2"
     EmptyDataText="There are no data records to display."
     AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="ContactID"
            SortExpression="ContactID"
            HeaderText="ContactID">
        </asp:BoundField>
    </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    SelectCommand="SELECT [ContactID] FROM [Employee]"
    ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString1 %>"
    ProviderName="<%$ConnectionStrings:AdventureWorksConnectionString1.ProviderName %>">
</asp:SqlDataSource>

You will also find that it pastes the appropriate connection string directly into your web.config.

<add
 name="AdventureWorksConnectionString1"
 connectionString="[string omitted;  it was LONG"
/>

Cool, huh?

p.s. If you want to paste that particular name, as I wanted to do, you can always do the old school paste-into-notepad-copy-out-of-notepad trick that is a tried and true way to strip off Web Browser formatting.

Firefox 1.5 released!

The last 32 days rocked! The release of .NET 2.0 and now Firefox 1.5. Both are absolutely revolutionary in their technology.

So, go get it! Woohoo!!! The link is in the list below.

Also, I remind everybody about my "What's new in Firefox 1.5" video, which is also in the list of links below.

...and yes, Chris Pederick's Web Developer Toolbar works great with Firefox 1.5. His page link is also below...

Learn WCF via MSDN Nuggets

Want to learn WCF (a.k.a. Indigo)? If so, you should head on over to MSDN UK to see Mike Taulty's latest MSDN Nuggets.

http://www.microsoft.com/uk/msdn/events/nuggets.aspx

Currently there are three videos:

  • Hello World
  • Type Serialization
  • Bindings

You will find that WCF looks much like old-school COM, but has the power of MSMQ, COM+, remoting, Web Services and the simplicity of .NET. Awesome!

For more information on WCF check out this great MSDN article: http://msdn.microsoft.com/library/en-us/dnlong/html/introtowcf.asp.

.NET Wikipedia Entry Edit

OK so I got SICK of the horrible midunderstandings written about .NET on Wikipedia...so much so that I rewrote much of it.

As of right now, 95% .NET 2.0 material written at http://en.wikipedia.org/wiki/Microsoft_.NET was written by me. The only parts I didn't write were the top two 'changes in 2.0' bullets. I added all other .NET 2.0 content.

Here are some snippets I added regarding .NET 2.0

".NET 2.0 is a severe redesign of not only the technology, but also the model of Microsoft's .NET agenda. While .NET v1.x was considered more of a Rapid Application Development (RAD) model and was often compared with Sun's Java. C# 2.0, part of the .NET 2.0 model, is now compared more closely with C++, so much so infact, that large portions of Microsoft's Windows Vista are written in C# and the .NET framework."

I also added information about how .NET was NOT the competition for Java, but was infact originally intended to be COM+ 2.5 by one team and "Next-Generation Web Services" by another. In addition, I removed anything about .NET 2.0 betas and updated the information about the express editions to be more proper.

New Blog

In addition to my WinFX blog I'm also going to be working on this new dynamics blog, called Dynamic Bliss. This blog will cover client-side topics such as XML based, out-of-band procedure calling ("Ajax" though I don't approve of that name), ECMAScript dynamics, dynamic graphics, widget creation, other topics from my book and a few other browser-related topics.

This blog is the replacement of a book I was working on regarding the same topic. I'm a strong believer that blogging is the new book (for technology at the moment). Parts of the blog will include video chapters from the my video book as well as my Firefox Web Development Suite videos.

You can get to the blog here, Dynamic Bliss.

WSE3 MTOM

OK, so this week I found out that that there currently is no support the the Jet database provider on the x64 platform. That didn't change the fact that I was determined to do it (or create the illusion of it). I had to create a user-approachable report generator which exported the data into Excel and sent it on to the user all via a web interface. I also didn't want to use the XML version of Excel spreadsheets (it surprises me how many times people think I'm talking about Excel 12 when I say that. You can do XML-based sheets in old Excel versions too!) So I wanted this done via ADO.NET and the Jet provider creating a "real" xls file. Obviously what I wanted to do isn't even work with the framework, but…doing it on x64 is.

The solution? Simple, WSE3 provides you with the ability to use SOAP Message Transmission Optimization Mechanism (MTOM) very seamlessly. MTOM is a new W3C recommendation used to optimize messaging scenarios that involve transmitting binary data. Technical gibberish aside, MTOM is just AWESOME. Using WSE3/MTOM, all I had to do was create a WSE3 service on a different server which created the XLS binary data and returned to back to the caller which then sent it on to the client.

Want specifics? MSDN has a document which provides you with the hands-on training you sufficient to propel you into WSE3 services: WSE3 Hands-on Lab: Messaging. MTOM is the third lab, but basically all you do is enable WSE3 (and MTOM) on the client and server, set the server up to return a byte array to the caller, call the server, and stream that byte array into a file. In my case I then sent it out to the user...

Here's my code for sending the Excel worksheet out to the user...

Response.Buffer = true;
Response.Clear( );
Response.ClearContent( );
Response.ClearHeaders( );


Response.AddHeader("Content-Disposition", "attachment; filename=" +
 "AutoGeneratedReport.xls");
Response.AddHeader("Content-Length", file.Length.ToString( ));
Response.ContentType = "application/vnd.ms-excel";
Response.WriteFile(fullpath);
Response.Flush( );

I'll have to beef up on WSE3 a bit for a future SOA lecture in my WinFX/.NET course.

.NET Course I'm teaching

So, for a while now I've been teaching a .NET 2.0/C# 2.0/Object-oriented desing class and decided to come up with a simple class website.

I'm covering not only the basics, but also many advanced topics that you would only find in footnotes. Mainly I'm going to be covering stuff that I wish someone would explain to me in plain english!! So, I'm going to be spending time explaining the differences between ref and out, const and readonly, and try{}catch{} and try{}catch(Exception ex){} among other topics. You can bet that I'll be spending A LOT of time just on delegation!!

There are actually a few series going on at once: C# Language (Intro, Intermediate, Advanced), .NET Framework and Design, Object Orientation and Design Patterns, SOA and Enterprise Development, ASP.NET 2.0 (web-standards "tableless"/CSS!!!), and WinFX concepts are the series all going on in parallel.

As far as the intro ASP.NET stuff is concerned, there are great ASP.NET books out for that kind of stuff. I'm mainly focusing on the middle layer and more advanced concepts. I'm actually planning a lecture for Microsoft Atlas. Given my love for Firefox, .NET, and remote scripting (err, Ajax), that should be fun! Also in the course of things I plan on having a lecture to discuss .NET design guidelines and another lecture on the architecture and mechanics of the CLR! .NET assembly language (yeah, yeah, the IL) rules!

Now what is my supplemental book recommendation? Basically anything that Troelsen has written. His latest book "Pro C# 2005 and the .NET 2.0 Platform" is written incredibly eloquently.

I absolutely love .NET... and this should show! maybe I can get an MVP out of this :D hint hint!!

Anyhow, here's the page I threw togther for it. I'll be posting more information, links, and samples as time goes along.http://www.davidbetz.net/dotnetcourse/

A few .NET 2.0 life simplifiers...

I'm starting to realize that not everyone knows everything or watches every blog in the cosmos, so I'll start including blog entires which will help people very efficiently master .NET 2.0 and WinFX.

One thing that will help people who currently fight with .NET 1.x is the following video I saw earlier this month. It's an explanation of some of the life simplifiers in .NET 2.0.

One of my favorites they talk about is is the addition of a Contains( ) method for things. Now instead of typeing "string".IndexOf("str") > -1, we can use Contains( ). My next favorite thing...well, about a tie, would be the additions of the String.IsNullOrEmpty(string) method to replace if(myString == null || myString.Length < 1). Nice...

OK, so here's the video...

"Favorite v2.0 Features in the Base Class Libraries"

C# 2.0 Self-Test



In the .NET course I'm teaching (".NET Complete") I gave a little project to the class, of which all of them are new to OO design, C#, .NET, and all the related items. The project requirement was for them to study the example and see what it does. The point of the project was to allow them to test their knowledge of C# syntax, collections, generics, and nullable types

It's almost as useless as "Hello World". Or,rather, hello world is almost as useless as this.

You simply type in string and it tokenized it into characters…but they didn't know that.  Anyhow here you go…

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace CodeExamples { class Program { class Storage<T> where T : ICollection<Char>, new( ) { private Dictionary<String, T> list = new Dictionary<String, T>( );

        <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> ShowLines( ){
            <span style="color: rgb(43,145,175)">Int32</span>? i;
            <span style="color: rgb(0,0,255)">foreach</span>(<span style="color: rgb(43,145,175)">KeyValuePair</span>&lt;<span style="color: rgb(43,145,175)">String</span>, T&gt; collection <span style="color: rgb(0,0,255)">in</span> list) {
                i = <span style="color: rgb(0,0,255)">null</span>;
                <span style="color: rgb(0,0,255)">if</span>(collection.Key.Length &gt; 2) {
                    i = collection.Key.Length;
                }


                <span style="color: rgb(43,145,175)">Console</span>.Write((i ?? -1) + <span style="color: rgb(163,21,21)">" : "</span> + collection.Key + <span style="color: rgb(163,21,21)">" : "</span>);
                <span style="color: rgb(0,0,255)">foreach</span>(<span style="color: rgb(43,145,175)">Char</span> thing <span style="color: rgb(0,0,255)">in</span> collection.Value) {
                    <span style="color: rgb(43,145,175)">Console</span>.Write(thing);
                }




                <span style="color: rgb(43,145,175)">Console</span>.WriteLine();
            }
        }


        <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> Save(<span style="color: rgb(43,145,175)">String</span> text) {
            T parts = <span style="color: rgb(0,0,255)">new</span> T( );
            <span style="color: rgb(0,0,255)">foreach</span>(<span style="color: rgb(43,145,175)">Char</span> c <span style="color: rgb(0,0,255)">in</span> text.ToCharArray( )) {
                parts.Add(c);
            }


            <span style="color: rgb(0,0,255)">if</span>(!list.ContainsKey(text)) {
                list.Add(text, parts);
            }
        }
    }


    <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">void</span> Main(<span style="color: rgb(43,145,175)">String</span>[] args) {
        <span style="color: rgb(43,145,175)">Storage</span>&lt;<span style="color: rgb(43,145,175)">Collection</span>&lt;<span style="color: rgb(43,145,175)">Char</span>&gt;&gt; storage = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">Storage</span>&lt;<span style="color: rgb(43,145,175)">Collection</span>&lt;<span style="color: rgb(43,145,175)">Char</span>&gt;&gt;( );


        <span style="color: rgb(43,145,175)">Boolean</span> done = <span style="color: rgb(0,0,255)">false</span>;


        <span style="color: rgb(0,0,255)">while</span>(!done) {
            <span style="color: rgb(43,145,175)">String</span> text = <span style="color: rgb(43,145,175)">Console</span>.ReadLine( );


            <span style="color: rgb(0,0,255)">if</span>(text == <span style="color: rgb(163,21,21)">"end"</span>) {
                done = <span style="color: rgb(0,0,255)">true</span>;
                <span style="color: rgb(0,0,255)">continue</span>;
            }


            storage.Save(text);
        }


        storage.ShowLines( );
        <span style="color: rgb(43,145,175)">Console</span>.ReadLine( );
    }
}

}

Firefox for ASP.NET 2.0 Developers Video Series



In September I recorded a video series I entitled the Firefox Web Developer Series. I've since renamed it to the Firefox for ASP.NET 2.0 Developers Video Series (clearly because the original title wasn't long enough). I put the project on hold because of the .NET 2.0 course I was teaching, which took almost all my time, but now I'm ready to take the time to get back into videos.

This series is for ASP.NET 2.0 developers who want to enhance their ECMAScript (JavaScript) skills and see how the powerful web development suite known as Firefox as simplify their lives as much as .NET 2.0 Framework does. In the series I use Beta 2 of Visual Web Developer 2005 and Firefox 1.0, but everything should be good for the final version of VWD2005 and for Firefox 1.5.

I will be releasing videos from this series over the next few weeks. For now, here is my introduction.

You can download the first video from the video below. You can download Visual Web Developer 2005 Express and Firefox 1.5 below as well.

Gosh I hate SPs/SQL (a.k.a. LLBLGen Rocks!)



…well at least in my C# code. That stuff belongs in the world of reporting, integration services, and other places which are NOT IN CODE. You couldn't get me to use ADO.NET anymore; it's such a pain for large projects. I love it for mass importing and when I do extremely dynamics such as report generation and a few other things, but for a static data access teir it's PATHETIC.

Not only is everything you type not strongly typed and therefore prone to error and has no color syntax; SQL (including SP calls) is just abrupt. You are doing this beautiful array of C# 2.0 greatness. Generic collections all over and BAM you see "select * from Person where..." Yuck!

Long live LLBLGen! If you don't know what LLBLGen is, you are completely missing out. I've been using it for months on all my projects and it's just downright awesome. It's basically LINQ...NOW. It allows you to use strongly typed .NET code to access your data WITHOUT writing any data tier code yourself. Not only that, the full blown enterprise edition is only $300. There is NO reason to ever write any data access layer yourself. It will pay for itself in about a DAY. I recommending getting a copy of LLBLGen even for your HOME projects!

All you have to do is point the LLBLGen app to the database, select the tables (and other entities) you want, and hit generate. It automatically creates a Visual Studio 2005 (or 2003 if you HAVE to use that icky thing) project for you. You can either include that project into your solution or compile the assembly and just us the compiled files. You only need to use LLBLGen again when you schema changes, which, as every architect knows...shouldn't be happening that often.

This rant is brought to you by the following sponsor...

DataSet dataSet1 = new DataSet( );
SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter( );


SqlConn1 = new SqlConnection(connString);
SqlConn1.Open( );


SqlCommData = new SqlCommand("GetDraftBox", SqlConn1);
SqlCommData.CommandType = CommandType.StoredProcedure;


sqlDataAdapter1.SelectCommand = SqlCommData;
sqlDataAdapter1.Fill(dataSet1, "MailList");


return dataSet1;

I was porting this old app from .NET 1.x to .NET 2.0 and I kept seeing stupid garbage like this. I got SO sick of it I decided to disconnect the logic tier and connect it to the LLBLGen access layer. Here's what I have now…

DraftMailCollection draftMailBox = new DraftMailCollection( );
draftMailBox.GetMulti(null);
return draftMailBox;

THAT'S IT!!! Short, sweet, strongly-typed, intellisense LOVES it, it's pretty (you gotta LOVE the VS2005 color scheme), and it's VERY easy to extend.

As another quick example here's how you would translate the following code into LLBLGEN code. First, the SQL code...

select *
from Person
where
PersonUserName = username and
PersonPassword = password;

Now the LLBLGen code...

   
PersonCollection people = new PersonCollection( );
IPredicateExpression filter = new PredicateExpression( );
filter.Add(PredicateFactory.CompareValue(PersonFieldIndex.PersonUserName, ComparisonOperator.Equal, username));
filter.AddWithAnd(PredicateFactory.CompareValue(PersonFieldIndex.PersonPassword, ComparisonOperator.Equal, password));
people.GetMulti(filter);

Yes, joining is also BEYOND easy and, yes, it databinds to GridViews with no extra work. I use it all the time in my ObjectDataSources.

OK one last example... well two. This one should be the straw that breaks...something. Look at this ADO.NET code (I'll leave some of it out though)

sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "insert into Customers (CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax )values(@CompanyName, @ContactName, @ContactTitle, @Address, @City, @Region, @PostalCode, @Country, @Phone, @Fax)";
sqlCommand.Parameters.AddWithValue("@CompanyName", companyName);
sqlCommand.Parameters.AddWithValue("@ContactName", contactName);
sqlCommand.Parameters.AddWithValue("@ContactTitle", contactTitle);
sqlCommand.Parameters.AddWithValue("@Address", address);
sqlCommand.Parameters.AddWithValue("@City", city);
sqlCommand.Parameters.AddWithValue("@Region", region);
sqlCommand.Parameters.AddWithValue("@PostalCode", postalCode);
sqlCommand.Parameters.AddWithValue("@Country", country);
sqlCommand.Parameters.AddWithValue("@Phone", phone);
sqlCommand.Parameters.AddWithValue("@Fax", fax);


sqlConnection.Open();


string id = (string)sqlCommand.ExecuteScalar();


sqlConnection.Close();

Some would say that it would not look so bad if the insert was in an SP. Um, ok...so you want to code in more than one place? No thank you. Also, what happens if there is no id to return? I've noticed that .NET 2.0 doesn't like that too much.

Now heres the LLBLGen code...

CustomersEntity customer = CustomersEntity( );
customer.CompanyName = companyName;
customer.ContactName = contactName;
customer.ContactTitle = contactTitle;
customer.Address = address;
customer.City = city;
customer.Region = region;
customer.PostalCode = postalCode;
customer.Country = country;
customer.Phone = phone;
customer.Fax = fax;
customer.Save( );


string id = customer.CustomerId;

Yeah...wow. Not only that, but in the SQL code you also have to do all that ADO.NET stuff. Not with LLBLGen, it's all in one!

I've been using LLBLGen for almost a year now and I have to say that my productivity has SOARED because of it. LLBLGen + .NET 2.0 + Firefox is a smart, er..., GENIUS match that should not be ignored, but rather ran towards!

To get a 30-day trial copy of LLBLGen follow the below link. I'm sure you will love it and for only $300, your manager will as well.

MSDN Nuggets WCF Mania!



I just did my weekly check of the MSDN nuggets page and found that Mike Taulty has been hard at work. He just released 6 more WCF videos.

  • Message Encoding
  • Message Patterns
  • Sessions
  • Instancing
  • Concurrency
  • Exceptions

Given the great quantity and quality of videos out there on WinFX technologies there is absolutely no reason people can't learn these new technologies. You don't need to read books, study whitepapers, or listen to those Geneva-convention-violating boring webcasts, all you have to do it click and pay attention. It's as if osmosis truely is a viable way of learning!

You can access these videos at the below link.

MSDN Nuggets

trycatch in .NET 2.0 - Note



Here is a comment Joe made about my previous post.

... One additional facet that will probably go (mostly) unnoticed is that you can throw exceptions across assembly boundaries, and the wrapping will occur based on the assembly-level attribute on the assembly whose catch block is being evaluated. This makes interoperability with code that isn't on the wrapping plan, e.g. COBOL or Eiffel, work seamlessly as you would expect.

...

This comment is rather hidden in how I have my page designed, but I thought it worthy of it's own posting anyhow.

trycatch in .NET 2.0 - Part 2



As I pointed out in a previous entry, try{}catch{} works differently in .NET 2.0 as it does in .NET 1.x. In 2.0, non-exception "throwables" are wrapped in a RuntimeWrappedException which can be caught by try{}catch(Exception ex){}, while, to catch then in .NET 1.x, you were required to use try{}catch{}. This led me to wonder 1) how does this work? and 2) is there even a purpose for try{}catch{} anymore?

So I started my research by… well, passing the buck, or going to the source, depending on your view on things. The first thing I did was ask Brad Abrams if he had some insights about this. He then forwarded me to Jonathan Keljo who I guess then forwarded me to Joe Duffy…sheesh what a line up! The best of the best of the best right there! Goodness, I feel like an ant…

Anyhow… here's the thing. Joe affirmed that there are at least two purposes for try{}catch{} in .NET 2.0

Here are his exact words…

(1) If your assembly doesn't have "wrapping" turned on;

(2) If you don't care to access the exception information via a variable. This can help to reduce the temptation to accidentally do a catch(Exception e){ //; throw e; } when you meant to do catch { // throw; }.

OK cool, now what about the mechanics? Joe explains that the wrapping of RuntimeWrapperException around non-exception throwables is due to the fact that C# and VB auto opt-in all assemblies to what they call "the wrapping plan". This means there is a RuntimeCompatibilityAttribute(…) on the assembly where, in this case, WrapNonExceptionThrows=true is set. When this is the case all non-System.Exception "exceptions" get wrapped into a RuntimeWrappedException, which, as Joe points out of course does inherit from System.Exception. Conversely, if WrapNonExceptionThrows=false is set, then there is no magical wrapping.

Let's see this all in action. But before we do, last time I wrote about this I forgot to what mention happens when you compile the below code (this is the same code from the previous blog entry about this topic)

// ThrowerHarness.cs
namespace ThrowerExample
{
    class ThrowerHarness
    {
        static void Main(string[] args) {
            try {
                Thrower.ThrowException( );
            }
            catch (System.Exception ex) {
                System.Console.WriteLine("System.Exception error: " + ex.Message);
            }
            catch {
                System.Console.WriteLine("Non System.Exception based error.");
            }

        <span style="color: rgb(0,0,255)">try</span> {
            Thrower.ThrowString( );
        }
        <span style="color: rgb(0,0,255)">catch</span> (System.<span style="color: rgb(43,145,175)">Exception</span> ex) {
            System.<span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"System.Exception error: "</span> + ex.Message);
        }
        <span style="color: rgb(0,0,255)">catch</span> {
            System.<span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Non System.Exception based error."</span>);
        }
    }
}

}

Compiling this code actually gives the following warnings...

throwerlib.cs(16,7): warning CS1058: A previous catch clause already catches all
        exceptions. All non-exceptions thrown will be wrapped in a
        System.Runtime.CompilerServices.RuntimeWrappedException
throwerlib.cs(29,7): warning CS1058: A previous catch clause already catches all
        exceptions. All non-exceptions thrown will be wrapped in a
        System.Runtime.CompilerServices.RuntimeWrappedException

As you can see, we know at compile that try{}catch(Exception ex){} will grab the exceptions.

Here's the IL we are using, which contains the Thrower class and is referenced by the C# application.

// ThrowerLib.il
.assembly ThrowerLib { }


.class public Thrower {
    .method static public void ThrowException( ) {
        ldstr "ThrowException exception from the IL world!"
        newobj instance void [mscorlib]System.Exception::.ctor(string)
        throw
        ret
    }
.method <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> ThrowString( ) {
    ldstr <span style="color: rgb(163,21,21)">"Weird exception!"
throw ret } }

Of course, there's our command syntax...

ilasm /t:dll ThrowerLib.il
csc Thrower.cs /r:ThrowerLib.dll

After a successful assembly and compilation, running this application gives the following output...

System.Exception error: ThrowException exception from the IL world!
System.Exception error: An object that does not derive from System.Exception has been wrapped in a RuntimeWrappedException.

Now, what about what Joe was saying about the RuntimeCompatibilityAttribute? Well, if we were to tack the following onto our existing class, we would get absolutely no warnings. Pretty cool...

using System.Runtime.CompilerServices;
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)]

Not only that, but here's the output as we would expect.

System.Exception error: ThrowException exception from the IL world!
Non System.Exception based error.

As you can see it did not wrap the exception. So, now, the picture of how things work and how to modify them is a bit more complete.

You can download the code for this entry by the link below.

Joe Duffy also has an explanation of this, although his is from the Beta 2 era (I only see one change -- WrapNonClsExceptions -> WrapNonExceptionThrows; but there may be more). Here is his article.

Video 1 (FWD) - "Setting up your Firefox Development Environment"



Finally! Here's the long awaited part 1 of my Firefox for ASP.NET 2.0 Developers Video Series. I will be releasing more parts to the series over the next few weeks.

This video is titled "Setting up your Firefox Development Environment" and contains valuable information on setting up your web development environment for maximizing efficiency. More setup information relating to this video will be mentioned in future videos as the utilities used in future videos of course also require setup.

Furthermore, this video is valuable not only to the professional web developer (as well as the non-professionals who still use tables for layout), but it's also valuable for anyone interested in maximizing their web experience.

Below is the link to part 1 of the Firefox for ASP.NET 2.0 Developers video series. You can download Visual Web Developer 2005 Express and Firefox 1.5 below as well.

New Blog Separation

Alright! So I decided to separate my professional information from my personal by creating a few separate blogs instead of having them all crammed into my website. From here on out, my website at davidbetz.net will be for my own stuff and this one here in particular will be for WinFX.

In the next few weeks I plan on putting up a lot of new information and hopefully I'll keep up a nice flow of blogging…

.NET 2.0 trycatch and trycatch(Exception ex)

One thing that I found rather interesting about .NET 2 that's different from .NET v1 is how v2 handles non-exception throwables differently.

First, a little background...

In case you don't know, the following two pieces of code are completely different.

try {
    Thrower.Start( );
}
catch (System.Exception ex) {
    System.Console.Write("Error!");
}

try {
    Thrower.Start( );
}
catch {
    System.Console.Write("Error!");
}

The difference is not that the first catches exceptions from unmanaged code and the second second doesn't, the first actually does catch those exceptions. The difference is also a bit more important than the mere fact that in the first one case we capturing the exception data in an exception type and in the other we aren't. The real difference stems from the fact that that in .NET you can throw things other than exceptions and in v1 you used the latter code to catch those non-exception throwables.

Here's an example of how to throw a non-exception. Yeah, you basically have to use the IL, or a compiler that doesn't check for this stuff.

// ThrowerLib.il
.assembly ThrowerLib { }


.class public Thrower {
    .method static public void Start( ) {
        ldstr "Oops"
        throw
        ret
    }
}

Here we are throwing "Oops". That's obviously a string, not something derived from System.Exception. In v1 you could use try{}catch(Exception ex) {} as a catch all for all exceptions, but that would not catch this error as it's not an exception. To catch this, you would also have a catch{} at the end.

OK, so how's v2 different? In this world, the non-exception item thrown is wrapped up in a real exception. So, in .NET v2 you can actually use your normal try {} catch(Exception ex){ } to also catch these non-exception throwables as well.

They are actually thrown as a RuntimeWrappedException. So the following app compiled an run in .NET v1 would explode into pieces, but would would gracefully end in .NET v2.

// ThrowerLib.il
.assembly ThrowerLib { }


.class public Thrower {
     .method static public void ThrowException( ) {
         ldstr "ThrowException exception from the IL world!"
         newobj instance void [mscorlib]System.Exception::.ctor(string)
         throw
         ret
     }
 .method <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> ThrowString( ) {
     ldstr <span style="color: rgb(163,21,21)">"Weird exception!"
throw ret } }

// ThrowerHarness.cs
namespace ThrowerExample
{
    class ThrowerHarness
    {
        static void Main(string[] args) {
            try {
                Thrower.ThrowException( );
            }
            catch (System.Exception ex) {
                System.Console.WriteLine("System.Exception error: " + ex.Message);
            }
            catch {
                System.Console.WriteLine("Non System.Exception based error.");
            }

        <span style="color: rgb(0,0,255)">try</span> {
            Thrower.ThrowString( );
        }
        <span style="color: rgb(0,0,255)">catch</span> (System.<span style="color: rgb(43,145,175)">Exception</span> ex) {
            System.<span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"System.Exception error: "</span> + ex.Message);
        }
        <span style="color: rgb(0,0,255)">catch</span> {
            System.<span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Non System.Exception based error."</span>);
        }
    }
}

}

XHTML 1.1 Escaping (Chapter Excerpt 3)



One thing you will inevitably notice when working with the ultra strict XHTML 1.1 is how the ampersand (&) works. In HTML you never had to worry much about the ampersand, though you could use it to implant an HTML space (&nbsp;). Now given that XHTML is XML, you simply can't get by with the rules of HTML. In the XML world, if you want to save an XML document with an ampersand, then you have to escape it. If you are familiar with C-based programming languages, then you know all about special characters like this. In those languages you have to "escape" certain characters such as the backslash (), with another backslash.

In fact, in Altova's XMLSpy application you will get a stopping warning if you have XML that looks something like <b>&</b>. The appropriate way to have an ampersand in XML is to write it as &amp;. This is very similar to what you could do with the   space in HTML and it's not that far off from what we already do. For instance, if you wanted to write &nbsp;. In fact if you want to write &amp;nbsp; you have to write &amp;amp;nbsp. So, if you know HTML, you already know the fundamentals of this rule. It's just that in the strict world of XHTML 1.1, you can no longer let little mistakes enter your code.

Now this rule about dealing with ampersands doesn't end with standalone ampersands, but also applies to ampersands in links. For instance, you can't just have a link like default.aspx?id=3&category=5. Your link has to transform to default.aspx?id=3&category=5.

Fortunately ASP.NET 2.0 is smart enough to deal with things like this in your databinding. For instance, look at the following code…

ASP.NET 2.0 Code

<asp:GridView ID="gvLinks" runat="server"></asp:GridView>

Code Behind

C#

String[] links = new String[] { "http://jampad.net/default.aspx?id=1&name=2", "http://jampad.net/default.aspx?id=1&name=2&frog=3", "Amburgers & Wootbeer" };
gvLinks.DataSource = links;
gvLinks.DataBind( );

Believe it or not, ASP.NET will output produce the following...

<table cellspacing="0" rules="all" border="1" id="gvLinks" style="border-collapse: collapse;">
    <tr>
        <th scope="col">Item</th>
    </tr>
    <tr>
        <td>http://jampad.net/default.aspx?id=1&amp;name=2</td>
    </tr>
    <tr>
        <td>http://jampad.net/default.aspx?id=1&amp;name=2&amp;frog=3</td>
    </tr>
    <tr>
        <td>A&W</td>
    </tr>
</table>

While I'm not a big fan of looking at table code, I am however a huge fan of automation. As you can see here, you don't have to fight with manually escaping data binding ampersands. Thus, you can give ampersands in XHTML data binding a vote towards deterministic.

XHTML 1.1 and DataBinding (Chapter Excerpt #2)



When doing serious data binding in ASP.NET you may want to reconsider using XHTML 1.1 or XHTML 1.0 Strict at all. The rule is simple: use the document type that can be deterministicly proven to be proper in your situation. Put another way, unless you have deterministicly proven that there will never be any invalid markup in the data, you should always use XHTML 1.0 Transitional.

If the binding data has some odd markup, then you will end up sending invalid XHTML 1.0 sent to IE breaking validation or sending invalid XHTML 1.1 markup to browsers such as Firefox, halting the rendering.

But what does it mean to be deterministicly proper? To put it simply it means to absolutely garuntee that the data will always be proper, that is, to be able to always predict the properness of data. This does not mean "well, it worked for 100,000 tests, so it's good enough", but rather it means that it absolutely will always work 100% of the time. You can get this level of determinism by looking at the symantics of what is going to be bound. For example, if you are binding a table with numbers, which will always be numbers, then you should have a level of determinism here. However, if you are binding a table with unvalidated under input, then you do not have determinism as you have no idea what a user will input. The user could input <b><i></b></i>, which will break the page. You have no idea. Having a proven, not demonstrated, view of data is what this is all about.

Here are a few guidelines that should help you with determining what is and not deterministic.

These things are never deterministic...

  • Unvalidated user input
  • Unvalidated external data
  • HTML
  • Anything else with angle brackets (<, >), except wellformed XML

Given symantical care, these things should be deterministic...

  • Wellformed XML
  • Alphanumeric strings
  • Base64 encoded data
  • Alphanumeric strings

To reiterate: only use the document type that is deterministicly proven to always be proper.

Excerpts from my XHTML 1.1 Chapter



One of the great things about XHTML 1.1 is that you are never allowed to serve it's content as text. You can send every type of XHTML 1.0 as text all day long, but never XHTML 1.1. You say you never send as text anyhow? Sure you do… that's what the text/html content-type is all about. The default for every web server (that I know of) is to send "browser" content (i.e. HTML, XHTML) as the text/html content-type. To use a different content-type you have to specifically say so.

The typical way to send XHTML 1.1 content is actually with the application/xhtml+xml content-type. To server a page using this type in .NET, you simply state the following in the early parts of your .NET page rendering (at the Init or Page events).

C#

Response.ContentType = "application/xhtml+xml";

VB2005

Response.ContentType = "application/xhtml+xml"

When you do this, you kick modern web browsers, like Firefox, into what I like to call "parsing mode", "ultra strict mode", or "application mode" depending on my mood, but what it really is is XML parsing mode. In my lectures I often say "HTML is fundamentally unparsable". What I really mean is "HTML is fundamentally unparsed". That is, browsers tokenize HTML (via scanning), rather than parse it via XML parsing. Not to say that web browsers parse XML per se, but they could fundamentally do so it they wanted to. XHTML is XML and therefore "XHTML is parseable". Kicking modern web browsers into this ultra strict mode actually forces the browser to parse the page in an XML centric manner. What's this mean? It means that if your XML (XHTML) is not well-formed, it will throw an error. It's important to note that when you are in this ultra strict mode, the browser is not a validator (that would be REALLY cool), but is more of a well-formedness checker and is the closest things we have to a runtime compiler (which, I know, seems like an oxymoron.)

So, why do this work to get this ultra strict mode? For one simple reason: QA! Quality assurance requires that you take your work seriously. You can't just throw together a bunch of pages and throw them out on the web. If you were writing C#, C++, or Java you would be forced to run your code through a compiler to check for errors. By using ultra strict XHTML mode, you again get this forced compliance.

One word of caution...and it's a common word of caution. Gosh, no matter what I say or what I do on the web it always seems to be the same word of caution: this doesn't work in IE! This is because IE, by default, has absolutely no idea what application/xhtml+xml is. If you try to send this type of content to IE, it will probably try to download the file locally. Now there are times when it will load fine, but what usually is happening in these cases is that the content type is specified in the Windows registry to tell IE how to render it. Since we are talking about the web here, and not the Intranet world we have to follow the universal rules of the W3C, ECMA, and...well least common modern denominators (I throw the word modern in there just in case anyone wants to say that Netscape Communicator 4 is the LCD...and for the record, I don't care about any 4th generation browsers.)

So we need to make sure that IE doesn't get this ultra strict content type. Consequently, we won't have ultra strict mode in IE. Now, if you're paying attention at all you will notice that we have a page with at least two content-types required to support two different planets of browsers (IE, the rest of Earth). You can't send two at the same time. Not a problem. All we need to do is whip out a quick condition based upon what the browser can and cannot do.

When it comes to server-side browser detection some people like like to rely on the UserAgent string of the browser. This is actually a very bad idea due to how easy it is to modify a browser's UserAgent string (especially in IE with all the IE toolbars out there!). I actually read somewhere where someone said that "using the UserAgent is the fastest way to hell" I'd have to go along with that hyperbole.

Here's what you really do: test if the browser can accept the application/xhtml+xml content-type. If they can use it, use it. If not, don't. That's all there is to it, but before I get into the code there's one more thing. We're not talking just about the content-type here, were also talking about the document type (the DTD). If the condition comes back negative, that is, it does not accept xhtml+xml, then you can't use XHTML 1.1 either. So you also have to control the content-type nad the document type in the same shot. This is also not a problem.

Here's a standard method I use in the pages I want to be in ultra strict mode.

In the ASP.NET page, I replace the doctype with the following.

<asp:literal id="litDoctype" runat="server"></asp:literal>

Now in the code-behind I do the following...

C#

Boolean debugMode = false;
private void SetDoctype( ) {
    Boolean mimeTypeOverride = false;
    if (Request.QueryString["xhtml"] != null && Request.QueryString["xhtml"] == "1") {
        mimeTypeOverride = true;
    }
<span style="color: rgb(43,145,175)">Boolean</span> realBrowser = <span style="color: rgb(0,0,255)">false</span>;
<span style="color: rgb(0,0,255)">if</span> (Request.ServerVariables[<span style="color: rgb(163,21,21)">"HTTP_ACCEPT"</span>] != <span style="color: rgb(0,0,255)">null</span> || mimeTypeOverride) {
    <span style="color: rgb(43,145,175)">String</span> httpAccept = Request.ServerVariables[<span style="color: rgb(163,21,21)">"HTTP_ACCEPT"</span>];
    <span style="color: rgb(0,0,255)">if</span> (httpAccept != <span style="color: rgb(0,0,255)">null</span> &amp;&amp; httpAccept.IndexOf(<span style="color: rgb(163,21,21)">"application/xhtml+xml"</span>) &gt; -1 || mimeTypeOverride) {
        realBrowser = <span style="color: rgb(0,0,255)">true</span>;
    }
}


<span style="color: rgb(0,0,255)">if</span> (realBrowser &amp;&amp; !debugMode) {
    Response.ContentType = <span style="color: rgb(163,21,21)">"application/xhtml+xml"</span>;
    litDoctype.Text = <span style="color: rgb(163,21,21)">""</span>;
    litDoctype.Text = <span style="color: rgb(163,21,21)">"\n"</span>;
    litDoctype.Text += <span style="color: rgb(163,21,21)">"\n"</span>;
}
<span style="color: rgb(0,0,255)">else</span> {
    Response.ContentType = <span style="color: rgb(163,21,21)">"application/xml"</span>;
    litDoctype.Text = <span style="color: rgb(163,21,21)">"\n"</span>;
}
}

VB2005

Dim debugMode As Boolean = False
Sub SetDoctype()
    Dim mimeTypeOverride As Boolean = False

    If Request.QueryString("xhtml") <> Nothing And Request.QueryString("xhtml") = "1" Then
        mimeTypeOverride = True
    End If


    Dim realBrowser As Boolean = False
    If Not (Request.ServerVariables("HTTP_ACCEPT") Is Nothing) Or mimeTypeOverride Then
        Dim httpAccept As String = Request.ServerVariables("HTTP_ACCEPT")
        If Not (httpAccept Is Nothing) And httpAccept.IndexOf("application/xhtml+xml") > -1 Or mimeTypeOverride Then
            realBrowser = True
        End If
    End If


    If realBrowser And Not debugMode Then
        Response.ContentType = "application/xhtml+xml"
        litDoctype.Text = ""
        litDoctype.Text = "" & vbNewLine
        litDoctype.Text += ""
    Else
        Response.ContentType = "application/xml"
        litDoctype.Text = ""
    End If
End Sub

This code is actually longer than you might expect, but this version is a bit more robust than a simple condition. The first to notice about this code is obvious: it checks to see if the browser can accept the application/xhtml+xml content type by checking the HTTP_ACCEPT server variable. Depending on the result, the browser either gets application/xhtml+xml content type and the XHTML 1.1 doctype or text/html content type and XHTML 1.0 Transitional.

Secondly, as you can also see, I've included a debug mode which, if set to true, will tell the page to serve the "less-strict" doctype. This comes in handy when you want to make sure you get the "less-strict" doctype. I'm using a private class boolean field named debugMode as a means to put the entire page into debugMode. You could also use a query parameter to put just this one part into debug mode.

Finally, you can see something rather odd towards the beginning of the code. Even though we are doing all of this to guarantee well formed XML, this does not in any way give us any information about validation. That's where this other part comes in. If you were go point the W3C validator at this page it would actually get the XHTML 1.0 Transitional doctype with the text/html content-type. That's all well and good for validating against that doctype, but you technically have two different versions of the same page here. You need to validate against the XHTML 1.1 version as well. So, with the inclusion of a quick query parameter check I'm allowing for the ability to give the W3C validator a Url such as default.aspx?xhtml=1 which will force the page to be in XHTML 1.1 mode. This is a little easier than always having to tell the W3C validator the XHTML 1.1 override (I never much liked the warning it gives you anyways when you do it their way anyhow). As I mentioned previously, you could use a similar technique for for it into the "less-strict" mode. One idea would be to set default.aspx?xhtml=0 to kick in "less-strict" mode.

Base64 PNG Server

In my mind, one of the coolest things tht modern web browsers can do is deal with base64 PNG images. PNG images are the "new standard" in web images. They can be very small in size or they can be larger as true color images depending on your needs. They don't replace everything, but they do replace a lot.

A base64 PNG image is a PNG image encoded as base64. Base64 encoding is a way to encode non-printable characters (stuff you can't see, but the computer can read) into printable characters (things like letters and numbers).

Base64 PNG images (which are text) can actually be read by modern web browsers as real images. In fact, it's one of my qualification requirements for being a modern web browser (actually there are MANY requirements in my mind). You can actually use base64 PNG images directly in CSS. Here's an example...

background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAABkCAYAAABaQU4jAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAC6ZJREFUeF7t3c1xHLkZBuC9++Lj+iD55AScgCNQBM7AGTiFra2ltso3xcAkmMUmQ3qABjBfY4D+IcUy5Xm2iiWJ09M/TzeJd4EPmJ9+8h8BAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgAABAgQIECBAgACBDyHw+feXv4++/vLr898+xAmePIlPvz3//Pm35399+vr87/zn5d9Hd1Hfd3T7tN2f//Pyp+SX/jzzPtv+bwTq/Tpy9Lrtj/qzcOQabUOAAAEC7yCQg9XXl5fp18PzHymovMOh32WXnx6ef/l8Oef2la4t/fvr8z/3DvjXh5d/ZIfL9nvbxtdzkLu870dyOnN9/2/b1vuVnv29a2vbPjw/7W3rdQIECBAg0ARawCpBKjUo7evh+XEJJ5fwcAkuH50tNoa11yqHpnIN6e9b13DZ7knA+uh3+e3nJ2C93dAeCBAgQGBHIASs4f+h59dLj9BHx6zn2Q8Jpt6rEhK/za7hEiC/1SCmB+uj3+m3nZ+A9TY/7yZAgACBAwJ7ASvtovXsTIZUcs1TqOPaq3lK9Sxx+73TjNvP9l2H9y5B6XG0v3S8WR3N5T1fliHSSxB7RZicDRH2x6zXfBMAi91enc9Z53zvwn1J/66W06AZ7uXe+fT737vv/TFj3drWeZ15Vo6c0yxgRd96rmHY2BDh3g+q1wkQIEDgKnAwYOWappFbCjSt56fWcqXhxkHQyY1oHYaLdV+TGqnSe7YM2+3suzWal6L2M/c3FzEv55t7t75rwFrC2uX8S3BbX8OX3KB3HvU8+ms445zem0NjGRoNdk/te4OwPDnG06hWKXvf7n9432eBt9at5d7DahPOK004mBxjOFxdhoNHz8uq53IUsFpPbQna9Zzrz8csuJ951mxLgAABAncksBWwUgCojd+oBis3yEt91rdVD1ZpMPuw0LZPjXPtWQm9RrEHpISxXP+VG9qyfWuMu6Lj2MvWGv/SG7VVfF5DRZ0B+A4BK4fTfE7pGtK11ML7EkRTMNiqFTvr3OxKcE3HTfuv+8nH7wJW9Yv3MtS0/RHvTezVyX/v7s0sJMYfq1j7VwNuOl67D8Eph8VyDeE8VyFr73mJ59QHrBqyay/m6DxNYLijX4oulQABAt9DYDWLMM6+q38vAWrYC1F6aDZeW/V6lfByM9RSZv49xSGpFgYGPVItZIXXQoF67qVJ25SgVQvXb45bw05qwFuPxfccIpwU18cws2rMS6joG/OZ26zHrdqNivpHw71tiLP04g3PKfRIhu2bW+41Kz1ypwPWoDetBt1R71nt1Tr6vPS1eX3AuvYi3s40bT1YP9BM2u/xe8E+CBAgQOCNAl1PQgon8astdzDqwdo69KgnqA33HBjG2+pJGtXFxIDVr0fVeuFCI1nCQBsafLeANZjePwo5OSyVJTPOWE+dJ0O6o2PX781qrvpjxNmaR+q0hgG8XusguOzV0+VA3i2LsfW89PVd9fzXQ4rjZTwErDf+gvF2AgQI3KvAXg3Wuk7othEqw4hp7amlvif0fKW/R9faMIYhsqf0vb6R3gl9SwDs1quahZZ0/NzAdtv3Q4MfKWCla+mfx6POe/dzErCWodh1uF4H7cvr9T7VcNrXxR1Za6w5bwSsvXXF+gC2d803lmXdshb4L9e2tYRH7hHVg3WvvyJdNwECBF4ncKRxms2kirPuUuMc19Ca9SiUWqDrkgiluDkWER8KWOl4YdhqK2Dl3qEw9BeGBh9X637Vwu2wJtgR1ekswskQ6l4PVh+wzjjv3c9XBqwctm6C8FKEfi2cP7Go61bP0F7A6q9x75qnAaus71bD5exe52fnQK/rkWfFNgQIECBwJwJHGqcYeCpL7BWa1snsrIie9xFmitWhsbDvw1Pj27DVZMX2GLCu226sYH9iRff3DFhnnffu5zRg7dyrvR+HFpwPuh0KWJPFbUNAXmZ+1k8jOLjaej/jtA05zo6XAtaBVd/3jLxOgAABAnckcKRxqgt1xp6VUOg8nDLf92Cluqj0ntFQzKSmapl9N/gcwTxclod5rkOWW3U7fWCrny/XZjLGz2KsQ5zle0cehfcMWGed+966/vxHAes6u3Bch1R7+eq+tj6vca8nse1jY4hwL2C3SQ7h/m/VYNXzrbV5w2UaJhMSjtx/2xAgQIAAgRuBrYCVa21WazhdG+CwOvrNwp5xev+gx+u2vqh+ll/oQdia2TaaRViCRVkDaR0URg3y7FHYaqhn73nPgHXWOZ3jqKg/+5QV7ftlGmLAvVkEtc5sjLMIy/Ic/bBZW+7gQG/YXvF4C2pdj2R+32CmZ+iFWq95tcxsXK3jNgpYeSmIUocW77MPe/ZLkwABAgReJXBkmYbZx8y0IuFafxU/aHkwVNSCzrKMwi+5Z6Q21pfv9bP/YjF73T587yaoxbWQ+mUaYr3WFtRHC1itR6o0/sXs+oHWI+caKsoSG73zaB2s7t7kJS7ivYn1V53zUsdW7/3BD73eC1iTYyy1e8vzs1oiYhWw++exWzx0FLBWwXQQ9Pu6uFf9sHkTAQIECNyPQFtdfTKDLDVG04+YqQuRhtmDqaFO26fGeRRqcuPWzThM7+nDVb0DpUYrzlDMxfTT3qTROZ2YATY7781QVou9u0Losq+bzz/MYWZQNF7vRXo9Hq8t+HrCud6DEEgeV8sSjFdy/1JnV4b3fRsN0/b7L9uniQc3wWdk1567jeLxyXU/bi0NUZ6v62zWZTLE6pzqM9Xvp82YTe8pQ9N12/6e3M9vCFdKgAABAgQIZIFaWzbiqOH27OcGoiVAgAABAgQI3LVAHUYdri+2sfr+XaO5eAIECBAgQIDAlkD4vMM8nJp6tNrQ2VKXdWgYjzIBAgQIECBAgEAQaOuLleUHztZIwSRAgAABAgQIENgQsEimx4MAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAAQIECBAgQIAAgU2B/wJmPk0do+6gLAAAAABJRU5ErkJggg==);


Well, it's not SUPPOSED to be small! It's supposed to be embeddable. And it is. But think for a moment. You can take an image (not just PNG mind you, GIF can do this as well) and turn it into Base64. Now, can't you dynamically load images on the client? Well, yes you can... All you have to do is do a remote call to somewhere which will send the Base64 stream back.

One you get the stream back all you have to do is prefix the base64 stream with "data:image/png;base64," and assign the entire value to the src property (attribute) of an img object.

Here's an example I put together a few months ago of how you can do all this... Firefox users only please! IE6 won't get NEAR base64 images.

PNG Client/Service Example

Actually, this is also a great example of how to work with web remoting (I just CAN'T call it Ajax, that's too weird) and how to dynamically work with XML files.

JavaScript Graphics Development

Samples (primarily for Firefox, but IE support was added)

Introduction

A few years ago I found an article which stated that there are three things that JavaScript cannot do. The article listed these three as local file actions, networking, and graphics. How true is this? First off, it's very true that JavaScript can't access local files. I think we can all agree that this is a feature. I mean, do you really want to go to a website and have that website access your local files? Copying them to their own machines? Writing out new files? Copying viruses locally? If you want to be able to do stuff like that then you can use Internet Explorer. It hosts a technology known as ActiveX which allows just these things. Everybody I know has learned this the hard way. JavaScript on the other hand is safe and clean with regard to viruses. But, can JavaScript do networking? It really just depends on what you are trying to do. If you're trying to access a resource across over a local network, you're out of luck, however if you would like to access resources on a web server, JavaScript can easily do this via XmlHttp. Furthermore, in modern web browsers, JavaScript has the ability to work directly with SOAP messaging and web services (though many times as a wrapper of XmlHttp). So, yes it can, but only in incredibly safe ways (which is a plus).

Lastly, what about graphics development? While many people have always thought it to be impossible, it's actually been possible for many years. This is the topic I would like to discuss here.

Pixels

The basis for all graphics development is basically the pixel. It's the simplest and most foundational unit of graphics development. With the ability to create pixels, the sky (or, rather, web browser performance) is the limit for graphics development. But, JavaScript can't write pixels, right? Sure it can. The trick behind JavaScript pixels is the use of standards XHTML objects. In our case we are going to use a very small colored div object to create a pixel. That's really all there is to it. To create more advanced graphics, you simply create more div objects. The beauty behind using a div object is that JavaScript can seamlessly interact with them and they are easy to place using simple 2D coordinates. In addition, div objects are easily customizable via CSS.

Using a div is great, but what size and shape should the div be exactly? You would think that it?s a 1px by 1px div object with a colored background and no border, but that?s won?t work since the buggy IE6 for Windows can't handle 1px by 1px div objects; it actually renders them as being vertical bars. To get around this problem our pixels will be created from transparent div objects with just about any height and a width of 1px and a colored border on the top only. This div object renders as a simple pixel and allows both Mozilla Firefox and IE to render pixels flawlessly.

I've stated at the outset that the prerequisites for this is understanding of the DOM, understanding of basic CSS, and understanding of modern web development or design paradigms. This is because all graphics development here relies heavily on the DOM, uses basics CSS as well as modern web development and design paradigms. If you are living in the old paradigms of presentation HTML, then I highly suggest you study up on XHTML/CSS development and design as well as shedding your old philosophies before continuing. Understanding of the DOM is also critically important for any modern web developer, since it?s via the DOM that you create new objects. This is what I'm going to demonstrate first.

To create a pixel you simply have to create the previously described div and put it somewhere.

function PlotPixel(x, y, c) {

    var pixel = document.createElement('div');

    pixel.className = 'Ink';

    pixel.style.borderTopColor = c;

    pixel.style.left = x + 'px';

    pixel.style.top = y + 'px';

    parentObj.appendChild(pixel);

}

As you can see in the code snippet, and a new element (object) is created, the Ink className is assigned to it, the border top is set, the width and height are both set to 1px, the pixel location is set, and then the pixel is assigned to a parent object (we?ll discuss this a bit later).

The Ink class is as follows and it's rather simple.

.Ink {

    position: absolute;

    background-color: #fff;

    border-top: 1px solid transparent;

    width: 1px;

    height: 1px;

}

The above JavaScript and CSS snippets are simplified version of what you could actually use. In reality you would customize both to suit your needs, or you could keep these simple versions, creating other graphics mechanisms to rely on them. One example I'm thinking of is a rectangle. With regard to the mechanism I just described, a rectangle in this context is just a pixel with a width or height greater than 1px. So, you could rewrite the PlotPixel method to actually be a DrawRect method and create pixel with DrawRect(x, y, 1, 1, c), though it's better practice to write that method separately though.

Now, the most obvious question is where did this pixel get places? As we see from the above pixel code, it was appended to the parentObj object, but what is that? This is the root in the DOM tree that is going to house this child pixel. In practice it would either me another DOM created object, like a canvas object (discussed later) or a hard coded object in the structure of the page. It?s actually a good practice to keep a hard coded object in the structure of your page so that dynamically created objects have a common root. I refer to this special object as a dynamic attacher.

All you have to do to create a dynamic attacher object is create a simple div which will sit immediately after the body opening. If you put it anywhere else in the body object then you will probably end up having object positioning problems. This is because whatever is above the object adds to the object's positioning. So if you put your page's <h1> prior to the dynamic attacher, then your objects are going to shifted by the size of the <h1>.

So, put the following code immediately after the start on the body object.

<div id="dynamicAttacher"></div>

To utilize this object, you simply have to get a JavaScript reference to this object.

var dynamicAttacherObj = document.getElementById('dynamicAttacher');

In the context of the above pixel function, the JavaScript object which references the XHTML object was called parentObj. Since the DOM is a tree, you can nest objects under other objects. The dynamic attacher doesn?t have to be the parent of the pixel, but it should be the root of your graphics tree. In fact, it should really only have one child and all further objects should be added to that child (which of course then, makes it a parent.)

That's about all there is to it with regard to creating pixels. With that one function you have a new world of possibilities. Years ago, many people used a similar type of method to create simple effects like snow fall. However, all the effects that I've ever seen followed the old HTML paradigm of thinking. The method I'm using here is standards compliant and follows the Ajax (Asynchronous JavaScript with XML) model of thinking. But, you don't have to stop with pixels though. What about lines?

Lines

According to geometry, a line is a straight 1-dimensional object with no thickness and extends infinitely in both directions. Well, we won't be creating anything with no thickness and we sure aren't going to even imagine creating something of infinite length, but what we can do is create line segments with thickness.

Creating a horizontal or vertical line is rather simple and if you know anything about graphics development at all then you know that you simply have to iterate through a loop n-times where n is the length of your line. This is true, but in web development it's much easier. While in classic graphics development a box is created by many pixels, in web development a pixel is created by a box.  In other words, we can simply create an elongated pixels.

You might think that a method to create this elongated pixel is nothing more than the DrawRect method I mentioned earlier, but that won't work since legacy IE6 can't handle div objects of unit height. So, we actually need to create DrawHorizontalLine and DrawVerticalLine methods. They might look something like this.

function DrawHorizontalLine(x, y, l, c) {

    var longPixel = document.createElement('div');

    longPixel.className = 'Ink';

    longPixel.style.borderTopColor = c;

    longPixel.style.width = l + 'px';

    longPixel.style.left = x + 'px';

    longPixel.style.top = y + 'px';

    parentObj.appendChild(longPixel);

}

function DrawVerticalLine(x, y, l, c) {

    var longPixel = document.createElement('div');

    longPixel.className = 'Ink';

    longPixel.style.border = '0';

    longPixel.style.backgroundColor = c;

    longPixel.style.height = l + 'px';

    longPixel.style.left = x + 'px';

    longPixel.style.top = y + 'px';

    parentObj.appendChild(longPixel);

}

Do you see the difference between the two methods? The horizontal line basically created an elongated pixel, while the vertical line is created by a completely different method entirely.  If you recall, the PlotPixel method used a transparent background with a colored top border to create a pixel. If we were to try to create a vertical line using that method, then we would get into trouble really fast since only the top of the line would be colored. So we actually had to create a div object with no border, a colored background and a height of the length.

What about lines that are diagonal? First off, the following is not going to help anyone.

function DrawLine(x1, y1, x2, y2, c) {

    var longPixel = document.createElement('div');

    longPixel.className = 'Ink';

 

    for(var x = x1; x < x2; x++) {

        for(var y = y1; y < y2; y++) {

            plotPixel(x, y, c);

        }

    }

}

The reason this isn't that useful is that first off it's creates a box. Secondly, even if it you were to create something that created something like a line using a simple 'for' loop, you could only create a perfect 45 degree angle because of the fact that the screen is not continuous, but is rather made up of discrete units. To create a computer graphics line properly, you would use Bresenham's Line Algorithm as created by Jack Bresenham in 1962 at IBM. The algorithm uses some simple algebra to approximate the most accurate line possible. Here is the appropriate DrawLine method.

function DrawLine(x1, y1, x2, y2, c) {

    var steep = Math.abs(y2 - y1) > Math.abs(x2 - x1);

    if (steep) {

        t = y1;

        y1 = x1;

        x1 = t;

        t = y2;

        y2 = x2;

        x2 = t;

    }

    var deltaX = Math.abs(x2 - x1);

    var deltaY = Math.abs(y2 - y1);

    var error = 0;

    var deltaErr = deltaY;

    var xStep;

    var yStep;

    var x = x1;

    var y = y1;

    if (x1 < x2) {

        xStep = 1;

    }

    else {

        xStep = -1;

    }

 

    if(y1 < y2) {

        yStep = 1;

    }

    else {

        yStep = -1;

    }

    if(steep) {

        PlotPixel(y, x, c);

    }

    else {

        PlotPixel(x, y, c);

    }

    while(x != x2) {

        x = x + xStep;

        error = error + deltaErr;

        if(2 * error >= deltaX) {

            y = y + yStep;

            error = error - deltaX;

        }

        if(steep) {

            PlotPixel(y, x, c);

        }

        else {

            PlotPixel(x, y, c);

        }

    }

}

For more information on Bresenham's Line Algorithm, check Wikipedia or any online computer graphics tutorial.

Not only do you now have the ability to create a line, you also have the powerful ability to create a vital graphics component.  The most basic component of a polygon is a line.  Now that you know how to create lines, using them to construct shapes should be easy.

Creating a polygon is as simple as drawing the start of one line at the end of another.  You can create closed or open, complex or simple, or even wild and erratic objects using this method as the basis.  But, what about circles? Given that a circle in Euclidean Geometry is an infinitely sided polygon you should definately use the line method, but how about we try something different?

Circles

Creating a circle is one of the easiest things anyone can do in computer graphics. At least it was 15 years ago when I would create them in game development. These days our screen resolutions have gotten a bit better than the 320x200 I used to work with. Let's begin by examine how we used to create circles using that old school method.

This method relies on the fact that you can create a circle by rotating a line around a center point and plotting the end of the line, much the same way you would draw a circle with a compass. In computer graphics however, we will rely on trigonometry, not on a physical a device.

The basic math behind this method is simple. Given a center point of P(x,y) and a radius r and angle a, you can find the point on the circle C(x,y) simply by finding the components x and y where x is r + Cos(a) and y is r + Sin(a). That's great, but this isn't the middle ages or third grade so we are going to be using radians instead of angles. Now, given a in angles we now have C(x, y) in radians where x is r + Cos(a*pi/180) and y is r + Sin(a*pi/180). In practice, you simply have to plot the pixel C(x, y) at every angle from 0 to 359.

Graphics.prototype.DrawCircle = function(xc, yc, r, c) {

    for(var a = 0; a < 360; a++) {

        PlotPixel(r * Math.cos(a * Math.PI / 180) + xc, r * Math.sin(a * Math.PI / 180) + yc, c);

     }

}

On a 320x200 resolution screen this shows a perfectly enclosed circle, however not on our modern screens.  The reason this worked 15 years ago, but not today is because this method draws only one point for every degree in a circle.  For a lower screen resolution every one of these points would touch each other, however on our modern screen this leaves enormous gaps between the circles.

So what do we do? The answer simply lies in geometry. I'm not going to explain the math behind this, but I will say that it uses the 2D circle formation and symmetry. You should be able to find a good explanation of modern methods of creating a circle online, but here is the code for it.

function DrawCircle(xc, yc, r, c) {

    var x = xc - r;

    var y = yc - r;

    yc = yc - r /2;

    xc = xc - r;

 

    circle.style.left = x + 'px';

    circle.style.top = y + 'px';

    circle.style.width = r * 2 + 'px';

    circle.style.height = r * 2 + 'px';

    var r2 = r * r;

    x = 1;

    y = parseInt((Math.sqrt(r2 - 1) + 0.5));

    PlotPixel(xc, yc + r, c);

    PlotPixel(xc, yc - r, c);

    PlotPixel(xc + r, yc, c);

    PlotPixel(xc - r, yc, c);

    while (x < y) {

        PlotPixel(xc + x, yc + y, c);

        PlotPixel(xc + x, yc - y, c);

        PlotPixel(xc - x, yc + y, c);

        PlotPixel(xc - x, yc - y, c);

        PlotPixel(xc + y, yc + x, c);

        PlotPixel(xc + y, yc - x, c);

        PlotPixel(xc - y, yc + x, c);

        PlotPixel(xc - y, yc - x, c);

        x += 1;

        y = parseInt((Math.sqrt(r2 - x*x) + 0.5));

    }

    if (x == y) {

        PlotPixel(xc + x, yc + y, c);

        PlotPixel(xc + x, yc - y, c);

        PlotPixel(xc - x, yc + y, c);

        PlotPixel(xc - x, yc - y, c);

    }

}

Looking at it you will actually be able to see the symmetry it's doing. It will plot a pixel at C(xc + x, yc + y) then at 7 other mirrored points on the circle. You may also notice the r2 = r * r (r squared) in there and recall from a Calculus or advanced geometry course how a circle is actually defined.

Speed Considerations

You can do more complex things with JavaScript graphics development, but you have to remember that each pixel is actually a div object. So an implementation of a flood fill algorithm used to fill areas with a certain color may not be something you will want to manually do any time soon. For things like that, you may want to switch to SVG graphics as seen in Firefox 1.5.

As far as performance of web browsers, Gecko, Firefox's rendering engine, is currently the fastest of the web rendering engines on the market and it will be able to take on many of the graphics development projects you throw at it. Trident, IE6's rendering engine should also be able to handle it, but you should take special care when even thinking about offering any Opera support. Opera's rendering engine, Presto, is the slowest of these web rendering engines and it's not just slow, it's really slow. You won't really be able to do any manual graphics creation using Opera's engine, so you may actually want to give them a stop sign and a redirect to getfirefox.com to help them along.

Canvases

Now that you have seen some of the basics objects you can create using JavaScript Graphics Development, what about interaction of the objects? This is actually very easy in standards-compliant browsers (i.e. Firefox/Mozilla), but can get rather weird in IE and Opera (especially Opera.), so I'm really only going to demonstrate the proper way of doing this without using any special IE or Opera tools.

Before I explain actual interaction, you will need to understand the concept of a canvas object. Without a canvas, you simply have a ton of objects all over the place with no connection between them. A canvas will allow you to group your pixels together in a larger parent object. You could theoretically group your pixels by giving them a common id prefix or create a virtual attribute identifying them with each other, but the DOM is a tree and to group things together they need only be on the same branch.  A canvas is that branch.

To create a simple canvas you could use something like the following code.

function CreateCanvas(w, h, id) {

    var canvas = document.createElement('div');

    canvas.className = 'Absolute';

    canvas.id = id;

    canvas.style.width = w + 'px';

    canvas.style.height = h + 'px';

    canvas.PlotPixel = function(x, y, c, id) {

        var pixel = document.createElement('div');

        pixel.className = 'Ink';

        pixel.id = id;

        pixel.style.borderTopColor = c;

    pixel.style.left = x + 'px';

        pixel.style.top = y + 'px';

        if(x <= parseInt(canvas.style.width) &&

                y <= parseInt(canvas.style.height)) {

            this.firstChild.appendChild(pixel);

        }

    }

    canvas.SetLocation = function(x, y) {

        canvas.style.left = x + 'px';

        canvas.style.top = y + 'px';

    }

    canvas.CreateBorder = function(width, style, color) {

        this.style.border = width + ' ' + style + ' ' + color;

    }

    canvas.CreateContainer = function(w, h, id) {

        var container = document.createElement('div');

        container.className = 'Absolute';

        container.id = id + 'Container';

    container.style.width = parseInt(w) + 'px';

        container.style.height = parseInt(h) + 'px';

        return container;

    }

    canvas.CleanCanvas = function( ) {

        if(this.firstChild) {

            this.removeChild(this.firstChild);

        }

 

        this.appendChild(this.CreateCanvasContainer(this.style.width, this.style.height, this.id));

    }

    canvas.appendChild(this.CreateContainer(w, h, id));

    return canvas;

}

Did I say simple? Well, ok, maybe it looks a bit complicated, but it really is simple. This method will create a canvas object and then return the canvas object. That's the gist of the matter, but as you can see there's more going on. The first thing you will notice is the internal PlotPixel function on the canvas. If you have never worked with JavaScript OOP, this is going to seem really odd. In JavaScript you can actually assign methods just like you would any variable. Other languages do this too, but they may have a special name for this process. C#, for example, calls these types of methods, anonymous methods. Regardless of what you call it, you're creating a function.

In fact I'm not just creating one function, but a few. The first is our new PlotPixel method, the second SetLocation actually moves the canvas to a place on the screen and the third, CreateBorder, is really just an added bonus for creating a canvas border. Then there is a function, CreateContainer, used to create the container object which will actually hold the pixels and finally a cleaning method, CleanCanvas, used to clear off the canvas.

There is one thing that I should definitely explain. In the PlotPixel function, there was the following code:

if(x <= parseInt(canvas.style.width) &&

        y <= parseInt(canvas.style.height)) {

    this.firstChild.appendChild(pixel);

}

The conditional is actually implements clipping. Clipping is where something is only seen within a certain area. For instance, in a video game where an enemy walks half way behind a wall, only half of the enemy is seen. The other half is clipped. Here, this makes it so that only pixels within the canvas area are drawn, therefore saving memory and helping performance out a bit.

The second thing to notice in that code snippet is the this.firstChild line. This line actually assigns the newly created pixel to the container object of the canvas, this container object contains the actual content of the canvas. If you look at the canvas function again, you will see that the last thing it does before returning the object is create a container object and assigns it as  a child of the canvas. Since this is a newly created canvas object, this is the first child. Thus, by adding the pixel to the first child of this canvas, the pixel is actually being added to the container of the canvas, which is exactly what this line is doing.

To use a canvas you simply have to create one and then append objects to it's canvas. Here is how to create the canvas:

var canvasObj = CreateCanvas(w, h, id);

I know, that's rather obvious. You simply give it the width, height and what ID you want to call it. That's it. To draw a pixel on  the canvas, you simply call the canvas.PlotPixel method. The pixels are then automatically applied to the canvas. But what about actually seeing the pixels? Adding them to the canvas is great, but we never assigned the canvas to anything.  If you recall, you have to actually assign the object as a child of the dynamic attacher object discussed earlier, or to something that is attached as a child of the dynamic attacher object.  So let's create an Attach method to help us out.

function AttachObject(parentObj, childObj) {

    parentObj.appendChild(childObj);

}

You just give it a parent and child object and it applies it for you. So in practice you could do the following.

var canvasObj = CreateCanvas(100, 100, id);

canvasObj.SetLocation(0, 0);

canvasObj.CreateBorder('1px', 'solid', '#000');

canvasObj.plotPixel(10, 10, '#000');

canvasObj.plotPixel(10, 11, '#000');

canvasObj.plotPixel(10, 12, '#000');

canvasObj.plotPixel(10, 13, '#000');

canvasObj.plotPixel(10, 14, '#000');

canvasObj.CleanCanvas( );

canvasObj.plotPixel(10, 10, '#000');

canvasObj.plotPixel(11, 10, '#000');

canvasObj.plotPixel(12, 10, '#000');

canvasObj.plotPixel(13, 10, '#000');

canvasObj.plotPixel(14, 10, '#000');

AttachObject(dynamicAttacherObj, canvasObj);

This is actually a horizontal line since we are plotting pixels vertically, clearing the canvas off, and then plotting pixels to the right. The rest should be fairly self explanatory.

You could expand on this example by adding the line and circle methods to the canvas, or you could go even further and create all your geometric shapes under the canvas class to allow everything to be canvased and therefore encapsulated as a larger entity.  Speaking of larger entities...

Widgets

What if you did create some entity using a canvas.  What about manually moving the entity? This is actually rather easy. Due to the tree structure we have been working work, JavaScript allows us to move simple objects as well as complex objects. That is, given that the object has a way to be found (i.e. by an id) we can move the object directly or we can move the branch the object lies on, there by moving all the branches child objects including this object. By adding this functionality, we have effectively turned a basic object into an entity known as a Widget.

So where do we start with interaction and the creation of a simple widget? There's really only two things to do: make sure the object has an id and do capture some events like mousedown, mouseup, and mousemove . I'm actually only going to show the very basic way of doing this. In reality, you would probably actually add more error checking and as well as other basic windowing features but this will do for now.

function ultraSimpleMovement(obj) {

    obj.moving = false;

    obj.addEventListener('mousedown', function(evt) {

        obj.layerX = evt.layerX;

        obj.layerY = evt.layerY;

        obj.moving = true;

    }, true);

    obj.addEventListener('mouseup', function(evt) {

        obj.moving = false;

    }, true);

    obj.addEventListener(obj, 'mousemove', function(evt) {

        var x = evt.clientX;

        var y = evt.clientY;

        if(obj.moving) {

            obj.style.left = (evt.clientX - obj.layerX) + 'px';

            obj.style.top = (evt.clientY - obj.layerY) + 'px';

        }

    }, true);

}

As you can see by the use of addEventListener, this code is only for standards compliant browsers and systems. Thus, if you really need to have IE6 support, then you will have to add a few tests in there as well as use a few non-standard Microsoft DOM methods and events.

There are a few parts to this code, but most should be self explanatory. The basic mechanics work something like this...

  1. Create a virtual attribute called moving which is set to false.

  2. Capture mousedown and on mousedown set that virtual attribute to true.

  3. Capture mouseup and on mouseup set that virtual attribute to false.

  4. Capture mousemove and if the moving virtual attribute is true, move the object.

Those are the obvious parts though. The less obvious parts involve the use of both evt.clientX (and evt.clientY) as well as evt.layerX (and evt.layerY). evt.clientX and evt.clientY actually tell you where the mouse is with relation to the client are, while evt.layerX and evt.layerY tell you where the mouse is with relation to the current object. Why am I using both here? If you didn't use the second ones, when you moved an object your mouse would immediately jump to the upper left of the box since you are moving the upper left, top part of the box to that location. You need to subtract where the mouse is currently from where it is on the screen to keep the mouse 'grabbed' where you originally 'grabbed' it.

In a production system, however, you would use something a bit more robust to account for the mouse moving too quickly out of the box area as well as other considerations.  You would also probably want to add more logic to control where the widget could be placed and how the widget may be moved.  Perhaps you only want people to move the widget by a handle on the top, or maybe you want the entire thing movable by any part.  Whatever you would like to do, the ideas shown above are a good foundation.

Application

So what could you do with all this? First off, the widgets are self explanatory. You could create a system with a floating calendar . If you were to link techniques similar to these to other Ajax principles like asynchronous processing (i.e. XmlHttp), you could allow users to design their own portals without ever doing a single post back. This is very similar to what Google dos for their portal and what Microsoft does with live.com.

Non-widget applications, however, may be more up your alley. One sample application I built is a JavaScript sin-wave example. This example shows how you can plot various parallel sin-waves using JavaScript graphics. You could extend this application by creating a trigonomic graphing calculator. You could use the same techniques to do simple animations, visual-aide demonstration, or even web assistants on your websites, all without images.

Another example I've built is a JavaScript graphs and chart library.  The example isn't so much an example as it is what I'm using on my personal website to render data.  It was created completely using JavaScript and the DOM.  In fact, the only hard-coded item in the page structure is my dynamic attacher object.  The library also has widget capabilities.

The Future

The most obvious graphics technology is Macromedia Flash.  However, using Flash has many disadvantages including the requirement to purchase Macromedia Flash, the high learning curve of Flash, as well as a proprietary graphics format.  With Flash you create the graphics and then interact with them.  The Flash animations are in a Flash format and have no code representation, so, editing Flash requires Macromedia Flash.

One technology that is increasing in popularity is SVG or Scalar Vector Graphics. Using SVG, web developers can display vector-based, instead of plain raster-based images in a web environment.  Using SVG programmers have full access to the code of the graphics.  That is, unlike Flash, SVG graphics are in code which allows for easy and powerful editing.  Firefox 1.5 is the first major web browser to provide native SVG support.  Interaction with SVG is done via JavaScript, which can either be an advantage or a disadvantage depending on if you are a JavaScript expert or not.

Another great web graphics technology is WPF/E.  WPF, Windows Presenation Foundation is Microsoft's unified graphics system component of the .NET Framework 3.0.  It's used to create anything from business applications to more complex 3D games with a single unified graphics programming interface.  WPF/E, Windows Presenation Foundation/Everywhere, is Microsoft's technology that takes the WPF out of the Windows world and out to the world.  WPF/E shares the same easy to use unified .NET programming interface as WPF, minus 3D capabilities.  WPF/E works not only in Windows and IE, but also in Mozilla Firefox, Apple Safari, and well, everywhere else basically.  Using WPF a developer could create a powerful desktop application using the very intuitive, elegant, and powerful C# programming language and then publish the application on a website allowing Firefox and Safari users to get in on the action.  In addition, WPF/E components in a web browsers are controllable by JavaScript.  For these reasons, WPF/E has been called "the Flash killer".

Conclusion

As you can see, despite the myths about JavaScript you can do graphics development. All that's requires is knowledge of the DOM and knowledge of JavaScript.  These skills combined with Ajax paradigms, you too can create powerful web component as seen on Google portal and live.com.  Furthermore, you can use these kills plus Ajax paradigms in applications integrating SVG or WPF/E components to create even more powerful web applications.

What is Ajax?

Introduction

I'm never been one to start by uselessly stating what an acronym stands for, but since it may be helpful in this case, I'll break my own rule this once: AJAX ("Ajax") stands for Asynchronous JavaScript with XML. It's the future of web development and for many, including myself, it's been what web application development has been about for years.

You can think of Ajax web development as being the quantum mechanics of the web development world. The paradigms are different, the players are different, and even the rules are different. Traditionally a web application goes through a "roundtrip" to process and update data to the user. That is, the web browser sends the server a request and then an entirely new page loads to complete a "roundtrip." This is a synchronous processing method where the client and server take turns I a synchronous manner. Ajax, by definition, thanks to the 'A', is asynchronous, so you no longer have to wait for an entirely new page. The user sends a request, goes about his or her other business and then receives an update on what he or she requested. No more waiting for just one thing to be completed at a time. To avoid the needless "roundtrips", the user just sends a request on the fly to the server for some specific data and receive only the data he or she requested without the waste of getting an entirely new page.

While I have been developing Ajax applications since before this millennium, it has only recently become popular with the general web population. The most obvious example of an Ajax application is Google's Gmail. People often ask me why Gmail is so different than other online message/e-mail services. In my answer there are of course allusions to the life-saving concepts of labels instead of folders and conversations instead of e-mails, but also there is my answer regarding its use of asynchronous technology.

In Hotmail and Yahoo! Mail, when you want to, for example, mark a message or series of messages as read you have to press a button and wait for the server to complete a "roundtrip." That is, you have to wait for the server to send you an entirely new updated page. In Gmail, with its use of Ajax technology, there is no roundtrip. So, while the other e-mail services refresh the entire screen when a user presses the button, thus sending a tremendous amount of redundant information to the user, Gmail works with only the appropriate components. In this case, it would send a message to the server telling it that you want to mark a series of messages as read and the server will send your browser back a confirmation all without a roundtrip and alter the screen accordingly. This process saves bandwidth and therefore, time.

That is just one example of a popular Ajax application. Another great example is Google Maps. I've never personally talked to a person who wasn't absolutely amazed at this website (ok, it's an application, but most people call it a website.) You can navigate all around the United States on just one little screen. The application almost never does a "roundtrip", thus gives the user a lightening fast user experience.

But, Ajax isn't just about asynchronous processing to allow for lightening fast applications and websites. The next part is the JavaScript portion. JavaScript is often called the most misunderstood programming language in existence. I would definitely have to agree. When most web developers think of JavaScript they think of data validation or some sort of form processing to allow simple messages like 'Sorry, but your phone number doesn't seem to be in the correct format.' Or a simple message like in Yahoo! Mail 'Are you sure you want to empty the trash box." Some with regard to JavaScript may even think of some sort of dynamic presentation like changing the text on the screen. But JavaScript is more than a simple scripting system, it's an extremely power programming language which brings to the table a tremendous amount of possibilities. This isn't just true for JavaScript as defined in the past 13 years of it's life, but more so future versions like ECMAScript version 4 that is soon to be public with the release of Firefox 1.1 due in the third quarter of 2005.

Going back to the example of online mail service, when you hit a reply button in Hotmail or Yahoo! Mail, a request is sent and, as before, a tremendous amount of redundant information is sent back to the user to create an entirely new screen just for the message response. In Gmail, however, you simply click in the reply box. Done. It immediately creates a new e-mail around the mouse cursor. It does this by using JavaScript to dynamically alter the page is drastic ways. What may take 4 seconds in Yahoo! Mail and Hotmail, now takes less than a second with Gmail. So, if you are a dial-up user, you need to be using Gmail. Well, actually, if you are a human, you need to be using Gmail. This is all thanks to Ajax technology.

Using JavaScript, an expert web developer could theoretically create entire web solutions without ever touching a single line of server-side code. With Firefox a developer could even utilize Firefox's built in SOAP and WSDL capabilities to do all necessary web service processing. Then a developer could use JavaScript to update all necessary pieces of the application with the new data retrieved by the web service. Of course in practice you would have a middle layer of C#, PHP, JSP or whatever to do your server-side accessing to play the middle-man role between the client-side application and the database and file servers. Put another way, Ajax allows you to keep your middle layer as small and efficient as possible.

JavaScript allows you to access and manipulate virtually any object on of off screen. It's your key to deploying web-based desktop-like applications. Soon, in ECMAScript version 4, you will be able to work with things like XML with incredible easy. It's already no problem to work with XML and you can currently use JavaScript to open a local or remote XML file to allow data access served by your middle layer, but soon there will a new syntax and language structure which will allow for more intuitive and more powerful XML processing than ever seen in any other technology. You can thank Firefox 1.1 for making this new technology, ECMAScript version 4, something that we can all use publicly on the web. It's actually no coincidence that JavaScript works so well with XML. The last letter of the AJAX acronym is the X which represents XML.

When some people think of XML, they think of a data format and when some people think of HTML they think of a presentation format. Well, while it may sound like I'm building up to a correction, these theories are actually absolutely correct. XML is for data and HTML is for presentation. But with Ajax and in the world of modern web-standards, there is a technology which combines the two. Thus enters XHTML.

XHTML combines XML and HTML to create something that is not data, and definitely not presentation, but creates rather a page structure. XML by itself cannot render data and therefore cannot solely be used to put controls (i.e. text boxes, buttons, etc…) on the screen and HTML is actually unparsable by today's standards, so it can't be used in strict production environments. XHTML combines the visual aspect of HTML with the parsability of XML to create the new canvas used in modern websites and web applications. With the various types of XHTML, a developer can choose that which best suits his or her own needs at the moment. It's actually a little known fact that there are two primary types of XHTML: one that is text based, which is really just HTML written in XML, and one that is application based, which is true XHTML.

In modern Ajax development when you are creating applications you should seek to use the applications version of most technologies. Why? The text version is not parsed like the application version. Deployment of applications requires a way of mechanical testing. Usually this is done with a compiler, which will check your code for errors, but what about uncompilable things like HTML? While with HTML and text based XHTML, you have to do this manually, by using the application based version XHTML you can parse and validate your code just like any compiler would. That is, no Java or C++ application would ever run with poor syntax because the compiler will prevent it from ever being deployed. So is the same with application based XHTML. If your XHTML code is improper, that is, has poor syntax or other problems, then it will not run. You will be able to catch your errors much earlier and you are forced to take XHTML errors as seriously as you would Java or C++ compiler errors. This allows you to ensure that your web applications are proper, thus bringing you another step closer to having web application development really feel more like windows development…and the quality assurance team will love you for it.

While that exhausts the acronym, there are more parts to Ajax. The one that seems to be the most important to many people, including myself, is one that didn't receive a letter in the acronym and that's web-standards. Some people think that web-standards bring you the ability to write standardized code that will work anywhere. Well, anyone who has been a web developer for more than a month knows that this isn't currently the case. While this is of course the ultimate goal, and until then all web browsers clearly miss the mark, the truth about web-standards today is that they are standards because of the high level of standards they bring to your development.

By writing code that is web-standards compliant; you are ensuring your application to be compatible with the future and are saying that you want your application to be usable for another two, five, or even ten-years. Without the use of web standards, who knows how long the proprietary code you used will last? That's a tremendous risk that no company can ever take. Web standards provide a way to ensure that your applications will work ideally for the long haul. Not only that, they are also the best way to ensure they are the most powerful for the long haul. Proprietary features are the equivalent of get-rich-quick schemes in that while they provide you with the initially buzz that originally sold you on the product with the buzz soon dying off leaving you with a distaste for the temporary world you involved yourself in.

To wrap up, you can think of Ajax development as being verified, standards-based, event-driven, potentially object-oriented, JavaScript coded, asynchronous web development which brings the potential of desktop applications to the web. Before Ajax, online mail services were slow and bulky, but now with Ajax and its application in Gmail, we finally have an online e-mail service that is efficient and powerful to meet the today's needs. What about your application development? your websites? Wouldn't you like the public to say the same about your applications and websites? If so, then asynchronous development, JavaScript, XML, and web-standards all wrapped in this new world called Ajax are your new tools for success!

Working with application-based XHTML

Ajax Development

Working with application-based XHTML

By David Betz - 07/16/2005

Introduction

For years presentational HTML was how we created our websites and front-ends for our web-applications, but times change and so do technology paradigms. Today presentational HTML is considered a legacy technology and should not be used in any manner at all. What replaced it is a set of technologies which interweave with each other to create a harmonous symphony of elegance.

Thought HTML was so popular, it suffered from many problems. The first is the fact that it integrated page content with page style. Today this concept is strongly considered taboo due not only to the fact that this type of integration is virtually impossible to management, but also due to the fact that this increases page sizes dramatically. Another problem with HTML is the fact that it was basically unparseable to a human. Sure there are standards stating what HTML should be like, but the rules were never enforced. A human looking at sloppy presentational HTML could really tell exactly what the page is supposed to look like. Many times a browser felt the exact same way. What a developer thought he or she was writing was not exactly that which rendered on the screen. The most common example of the unparsability is the lack of enforcement for requiring the closing of tags.

Many developers and many tools which would create webpages for you used to use the <p> tag as a line break, when in fact <br> was an HTML line break and <p> was the beginning of a paragraph. This brings up two more obvious problems related to that: first, a beginning of a paragraph calls for an ending, but in many old HTML pages the <p> tag was missing. secondly, if <br> is the line break, where does the line break end since text between a less-than and greater-than sign is a tag beginning calling for an ending.

XHTML fixed all of those problems by clearly stating that XHTML is to be written as XML. This naturally created a way for humans and browsers to both be able to easily parse client-side 'presentation' code. First, since XML requires an ending, developers were forces to add </p> somewhere after a <p> to close the paragraph, which gave strong enough hint to the fact that <p> is not a line break. Secondly, since <p> was obviously not a line break, <br/> stood out as an obvious line break and since it does not have an ending it was self closing dude to the / at the end (this is all of course using the old model of design, where using <br> was still considered proper.)

Now with a clear way to parse client-side 'presentation' code, developers had a way to test to see if their code was proper. That is, compliant to standards. A validator became and still is one of the web developer's and designer's most powerful tools. Programmers have their compilers to catch syntax errors, and now web developers and designers had validators. But a problem still remains: This code was parseable, but still not parsed. That is, a developer could write code as good as possible and be in such a hurry to release code that he or she forgets to do the critical step of validating (which is much like forgetting to compile your application.) So, the risk still existed that a developer could release improper code. How is this problem solved? This is where application-based XHTML comes into play.

XHTML Types

XHTML is actually split into two major branches: text and application based. Text based XHTML is XHTML 1.0 and is nothing more than HTML written to look like XML. Technically it is XML, but browsers don't really care. A web browser will look at XHTML with the same eyes it looks at HTML. It could not care less that now you have a sense of properness about your code by putting a little slash at the end of your img object. In this world XHTML is just HTML, with the cleaned ability to read your own code due to your writing code properly. This world contains frame set XHTML as well as what you could think of as two levels of XHTML: transitional and strict.

The transitional version is basically the first level of XHTML. It's HTML written in XML, but it's not really that strict about things. Old paradigms are allowed. That is, tags like font, applet, menu, strike, and u are all still allowed as well as various legacy attributes like 'align' on tags like div and the header tags (i.e. h1, h2, h3, etc...). XHTML strict does not allow for these tag and elements and forbids many, many others and brings a web developer one step further from legacy development and closer to proper coding, but not to the highest level of proper coding we currently have. In HTML the web concepts are focused on the presentation of the page, but XHTML 1.0 changes the focus of the web to various other places and even changes the point of the page itself. That is, the page is no longer a presentational format, but it's rather a structure containing objects. This is especially true with XHTML 1.0 strict, in which it's considered extremely taboo to have any presentational elements in your structure (that's what CSS is for.)

Other than these varieties of XHTML there is the highest level of XHTML we currently have: XHTML 1.1. XHTML 1.1 is actually a very misunderstood format. It's not simply HTML written in XML, it's actually a new format all together. While XHTML 1.0 transitional brought the first level of code clarity to the page and while XHTML 1.0 Strict a stronger sense of a major paradigm shift, XHTML 1.1 brings that paradigm shift to full tilt.

This is traditionally used as application-based XHTML and the standard strongly recommends this. In fact, it's considered poor programming to not use it as applcication-based XHTML. In what I call 'application-mode' Pages are no longer just XHTML pages written to look like XML that can allow for errors, they are actually parsed on the client end just like XML to ensure a quality product.

Just like how you cannot ship out C#, Java, or C++ code before you compile your code, you should not be able to ship out your web code before you validate. One of the great things about a compiler is that not only does it make your product smaller by creating a binary version of it, it also checks for errors. A C# compiler for example will not let your product be released if you try to use an uninitialized variable. It saves you from the extreme problem of having a memory leaking product in production. Validators are the same way, but with XHTML 1.1 you are forced to take web development as seriously as you would any C#, Java, C++, or like development.

One of the reasons for this is that your XHTML page is as I say not a presentational page, but rather a page structure for other things to work off of. Think of it as the foundation for any further work. If you are a desktop-developer you can think of an XHTML page as being like your forms resource file (i.e. resx, XAML file, etc...) You can't expect an improperly written Windows-form to work properly if you don't have the correct format, so you can't expect your XHTML page to work properly if it's not properly written. Thus the beauty of XHTML really shows: it really is XML.

One of the things that makes XHTML 1.1 real XML is the mime type it uses. Text-based XHTML is actually sent with the old fashioned text/html mime type. Thus it's still html. XHTML 1.1 however is sent with the application/xhtml+xml mime type, which kicks the browser into a type of ultra strict mode. If your XHTML page is not proper you will get an error just as you would if you sent improper XML since XHTML is XML.

Something that many programmers may think of with regard to the entire concept of having a parsed page is that while compilers check their code at the server-side, this is checking at the client-side. How does this help the developer? Doesn't that cause more problems because an error skipping our development may still show up at the client? Isn't this the OPPOSITE of what a compiler does? Starting with the last of these and moving backwards, this is exactly what a compiler does, just in a different way. A compiler, among many other things, will make sure you code is right, that is it will check syntax among other thing. That is, it is validated. Unvalidated code is as bad as having code that never went through the test of being compiled. Second, the compiler is at the client-end and the developer will have it as well. This puts more pressure on the developer to do coding properly, a concept which is virtually obsolete. That also answers the question as to how it helps the developer.

Application based XHTML is a very powerful format because it is XML using an XHTML namespace. In these days of meta-data addiction and excessive Q&A testing, you would think that everyone would immediately drop their legacy HTML and text-based XHTML to start creating applications which are required to be proper, not for creating a warm and fuzzy, but for actual survival of the application.

Strictness

n the old days web developers would do page editing, dynamics, and hacks by writing more HTML out to the screen. The most common way of doing this was the document.write method. This allows a developer to create incredible dynamic pages which were capable of virtually anything. You can do similar things in text-based XHTML as well. For example, while document.write as the standard thing to do in the days of presentational HTML the following would be appropriate in text-based XHTML.

object.innerHTML = '<div id="objectId"><span class="Italic">Cats and Dogs</span></div>';

This simply adds text inside of a span inside of a div to some object. It's rather simple to see how this work, but understanding why this is illegal in application XHTML may require explanation.

The one thing that is an absolute constant in application XHTML is strictness. The philosophy is simple: If a compile won't allow that type of slop, neither will application XHTML. So, what's the problem? What's so improper about that innerHTML code? To illustrate, look at the following code.

object.innerHTML = '<div id="objectId"><span class="Italic">Cats and Dogs</div></span>';

Notice anything wrong? The div and span endings are backwards and this is absolutely and critically illegal in XML, thus also in XHTML since it is XML. The risk of allowing improper code in is far too serious to entertain even in the slightest. Thus, it's absolutely illegal to do this.

DOMParser

So, while this may work in lesser browsers, it would cause a browser which respects application-based XHTML to throw an exception. But, what do you do if you had to dynamically place data into another object? The first way to do this is to use the DOM to create manually create the objects.

var divObj = document.createElement('div');
divObj.id = 'objectId';


var spanObj = document.createElement('span');
spanObj.class = 'Italic';


spanObj.appendChild(document.createTextNode('Cats and Dogs'));


divObj.appendChild(spanObj);
parentObj.appendChild(divObj);

While this is the proper way of doing things, this method breaks down when you need to insert data that you don't control, like a blog entry. When a blog entry comes in, you have no idea what objects the writer used in his or her entry. It could have image objects, table objects, or even legacy font objects. With this level of uncertainty, creating the objects to insert manually is not an option. Fortunately, theres a solution.

Firefox has an object called DOMParser which will parse incoming data into appropriate objects. It actually creates an entire object tree from incoming data. You can then use a simple loop to insert all the nodes it parsed. The code for this may look like the following.

var incomingData = '<div id="objectId"><span class="Italic">Cats and Dogs</span></div>';
var parser = new DOMParser();


var doc = parser.parseFromString('<div xmlns="http://www.w3.org/1999/xhtml">' + incomingData + '<\/div>', 'application/xhtml+xml')
var root = doc.documentElement;
for (var i=0; i < root.childNodes.length; ++i) {
	parentObj.appendChild(document.importNode(root.childNodes[i], true));
}

As you can see the incoming data is being places between in a div object with the appropriate XML name space and the parse does all the parsing work for you. All you have to do is iterate though the children nodes of the documentElement of the parsed data appending each of the children found to the parent.

One other thing to consider is optional support for legacy browsers, such as IE6 for Windows. IE6 doesn't even have support for application based XHTML, so there isn't even any point in doing this. But you may want to create a unified solution to handle both systems. For example, you might use the following to handle both.

function applyNewData(parentObj, incomingData) {
	if(new DOMParser( )) {
		var parser = new DOMParser();
		var doc = parser.parseFromString('<div xmlns="http://www.w3.org/1999/xhtml">' + incomingData + '<\/div>', 'application/xhtml+xml')
		var root = doc.documentElement;
		for (var i=0; i < root.childNodes.length; ++i) {
			parentObj.appendChild(document.importNode(root.childNodes[i], true));
		}
	}
	else {
		parentObj.innerHTML = incomingData;
	}
}

This method combines the use of DOMParse with simple use of the object.innerHTML setter. Depending on if the browser has support for DOMParser, the browser will use either the XML DOMParser or use the innerHTML setter.

The html Object

I keep saying this but application XHTML is XML. Text-based XHTML is supposed to be XML, but it's never enforced, so no one can say if it really is or not, but there is no mistake about the fact that application-XHTML is XML. Because of this, each level of the XHTML (XML) tree means something. So, while Presentational HTML as well as the versions of text-based XHTML don't really care about the usage of the html 'tag', in XHTML it's a real. In HTML and text-based XHTML it was there just for looks more than anything. In application-based XHTML, however, the importance is very critical. For example, if you were to set a background color on a page like in the following code.

body {
background-color: #f1f1f1;
}

In this case, you expect the background color to be that color and this is the case with text-based XHTML, but not with application-based. With application-based XHTML, there will possibly be a gap at the top of the page due to the fact that the body object is a child of the html object. To work around this you have to apply the background color to the html object, thought it's a better practice to apply it to both the html and body objects.

html,
body {
background-color: #f1f1f1;
}

This method will fix the background color problem of having the gap at the top of the page. The story is basically the same for anything you traditionally apply only to the body object, or body tag as it used to be called. That is, anything you would traditionally apply to just the body tag, you would probably now apply to both the html and body elements.

Setting application-based XHTML

You can activate application-based XHTML in various ways. First, you can set your file extension to .xhtml or you could set the content-type of the http header to application/xhtml+xml. Doing either of these things will kick Firefox into what I call ultra strict mode and treat your XHTML as it was meant to be treated, as real XML. To add full validation capabilities you will also need to set the DOCTYPE of your page to XHTML 1.1. If you use another type of XHTML, your page will still be treated as real application-XHTML, but validators will validate based on your declaration of the DOCTYPE.

To some developers, Application-based XHTML may seem like an extra worry, but it's exactly that type of attitude that drives quality-assurance teams crazy, creates immediately obsolete applications, and that destroys any remnants left of respect for programming. Application-based XHTML allows a developer to create solid applications without having to rely on the obsolete nature of presentation HTML, which also allows a developer to retain a solid foundation for more advanced development without having to worry about any mistake in his or her user-interface structure.