May 2004 - Posts

Upcoming Reporting Services SP1

In a posting to microsoft.public.sqlserver.reportingsvcs, Brian Welcker released some details on the upcoming SP1 for Reporting Services. The SP is currently on track for release in the second half of June. In addition to bug fixes, and performance / scalability improvements, major changes include:

  • Excel rendering extension has been improved and now supports viewing in earlier releases of Excel.
  • PDF rendering extension is more robust and has better matrix rendering performance.
  • Chart control provides more control over display styles.
  • References to external URLs (images and resources) from within a report are now supported.
  • Data caching behavior for report preview.
  • NewLine in expressions is now supported.
  • The style of the HTML Viewer toolbar can now be modified through a style sheet.
  • New URL parameters offer more options for customizing report presentation at run time.
  • Report Manager proxy persists authentication cookies so that they can be used by custom security extensions.
  • Hidden parameters are now supported.
  • Temporary snapshots can be compressed as well as stored on the file system.
  • Integrated security support for accessing report data sources can be disabled.
  • Report hyperlinks can now contain any protocol identifier.
posted by scott with 2 Comments

New Book

As Scott Mitchell points out, the royalties from a technical book shouldn’t figure into your retirement plans. Nevertheless, I went down this road (again) and co-authored a book featuring the ASP.NET Community Starter Kit.

Last summer I was debating if I should take on this assignment or not and looking at the CSK code. I’d have to say the CSK kept growing on me. Unlike the other starter kits the CSK implements advanced features, and it took a bit of tinkering and spelunking to grok all the concepts. I also grew fond of the code because in 1999 I was working on an application doing URL-rewriting and “themeing” the hard way (using C++ ISAPI filters), and I was truly appreciating the elegance .NET was bringing to the application.

When the “A-ha!” moments started to happen and all of the CSK code started to click, I decided I wanted to write the book. While I was knee deep in weekend writing, I decided I not only wanted to write a book about the CSK, I wanted to launch a website using the CSK. Although there are already 1,001 great technical sites on the web, this one would have my stamp on it (for better or worse). With the help of a great friend and colleague, the CSK (with some customizations) became the software for OdeToCode.

The site made it online well before the book did. I just received my copies last week. Even now after I’ve read Scott’s blog about the soft market, and DonXML’s post about the advantages of self-publishing, I’m still happy with the decision. I learned quite a bit during the experience and now have two pieces of work to show for it.

Funny aside: when trying to come up with a name for the site we used the Internet Anagram Server to produce words from the letters in our names (Poonam and Scott). One phrase it kept spitting back was Potomac Snot, which was tempting being as we are near the Potomac river, but she (ok, we) decided it wasn’t the best name for a technical web site. We reserve the right to use this name as a company name for local consulting gigs.

posted by scott with 0 Comments

Nullable?

I’m just not sure I like the nullable type syntax in C# 2.0. Every time I see the shortcut syntax for a nullable type, I cringe a bit.

int? i = 2112; // cringe

The first thought that struck me when I saw this was that C# language now has some decent material for obfuscation contents. C obfuscation contests have been around awhile, and tools like the preprocessor give C programmers plenty of material to work with. For example, I’d never be able to look at this source code and guess that when compiled it plays a game of adventure. It’s both repulsive and fascinating at the same time.

I tried to get comfortable with the new syntax in the May CTP, but I keep getting compiler errors on simple examples:

int? x = 125;
int? y = 33;
int? z = x + y;

Error: "Operator '+' cannot be applied to operands of type 'System.Nullable' and 'System.Nullable'"

I’m thinking nullable type support hasn’t completely made it. The null coalescing operator ( ?? ) doesn’t appear to work yet either:

   int? x = null;
   int? y = 15;
   int? z = x ?? y; //cringe

"Operator '??' cannot be applied to operands of type 'System.Nullable' and 'System.Nullable'"

Then I thought I’d have some fun and try to see what I could break (warning, this is really vulgar):

  using c = System.Console;
  class P
  {
 
    delegate int?? p();
    delegate int? u(int?? x);
    delegate int u2(int?? x);
 
    static void Main(string[] args)
    {
      int?? j = new int??(1);
      int? k = null;
      int i = new int();
 
      p p; p = delegate { c.WriteLine(i); return new int??(new int?(i)); };      
      u u; u = delegate(int?? x) { return x.Value; };
      u2 u2; u2 = delegate(int?? x) { return u(x).Value; };
      do
      {
        i = i + u2(j);
      } while (u(p()).Value > 9 ? false : true);
    }
  }

But, the above executes and prints integers from 1 to 10. I was hoping for fireworks.

I’m still not comfortable with the new syntax, but it looks like I’ll have to wait till the next release to give it a more serious try. I’m surprised nullable types appeared so late in the cycle. Changes like this should come around early and entertain plenty of discussions and flame wars. I’m hoping it doesn’t come out feeling like a bolted-on solution that we have to live with for years.

Ooh, this just in. I have definite problems using MSDN help in the CTP, but RobCaron has the solution. Thank you, thank you, thank you, Rob.

posted by scott with 0 Comments

.Text Threading Bug

If you are one of the 7 regular readers here you might have noticed some problems over the last few weeks. Every so often .Text would display an error page with the message: “Value cannot be null. Parameter name: value”. Once the error happened it would stick around until the application restarted. Unfortunately, the error was appearing everyday. After asking around on some of the boards to no avail I did some sleuthing.

In .Text 0.95 the Stats class has the following method:

public static bool AddQuedStats(EntryView ev)
{
    //Check for the limit
    if(queuedStatsList.Count >= queuedAllowCount)
    {
        //aquire the lock
        lock(queuedStatsList.SyncRoot)
        {
            //make sure the pool queue was not cleared during a wait for the lock
            if(queuedStatsList.Count >= queuedAllowCount)
            {
                EntryView[] eva = new EntryView[queuedStatsList.Count];
                queuedStatsList.CopyTo(eva,0);
 
                ClearTrackEntryQueue(new EntryViewCollection(eva));
                queuedStatsList.Clear();            
            }
        }
    }
    queuedStatsList.Add(ev);
    return true;
}

The first highlighted method is in the call stack when the exception is thrown, but like any good threading bug the problem actually begins somewhere else: queuedStatsList.Add. The Add method is not thread safe and the collection eventually corrupts with a null reference appearing in a slot where an EntryView object reference should be. The EntryViewCollection ctor barfs when it tries to copy the null reference. Because the application can never clear the queue the exception keeps occurring until reset. I only checked 0.96 briefly, but it looks like the problem still exists. If you are running into this problem, one fix is to change the code and move the Add inside of the lock scope (and skip the double check locking):

public static bool AddQuedStats(EntryView ev)
{
    //aquire the lock
    lock(queuedStatsList.SyncRoot)
    {
        if(queuedStatsList.Count >= queuedAllowCount)
        {
            EntryView[] eva = new EntryView[queuedStatsList.Count];
            queuedStatsList.CopyTo(eva,0);
            ClearTrackEntryQueue(new EntryViewCollection(eva));
            queuedStatsList.Clear();         
            
        }
        queuedStatsList.Add(ev);
    }
    return true;
}

If you are having this problem and don’t want to recompile the application, set queueStats=”false” in the Tracking section of web.config.

It seems like I am the only one who was having this problem, which is odd because I certainly don’t have the same number of concurrent users as, say, blogs.msdn.com, but that’s multithreading for you.

I do want to say thanks to ScottW for all his .Text work, hopefully this will add just a little bit of improvement to some great software.

posted by scott with 14 Comments

VS 2005 CTP March 2004

I’ve been working with the CTP to put together an article for ASPToday. Along the way I’ve kept some notes. Since the version I’ve been working with is now obsolete, I thought I should post these notes before they become too obsolete also.

  • The intellisense features are just too good. My cat even loves intellisense. Her name is Beaker. She occasionally lumbers across the keyboard producing random characters and compiler errors, but with the May build I wouldn’t be surprised if she paws out the source to a CLI compliant “Hello World” program. Thanks to Cyrus and the rest of his team for making this work so well.
  • One request – I didn’t have intellisense or the ability to ‘format document’ in a web.sitemap file. I imagine this is only a matter of time.
  • One more request to consider: when I auto-complete on a method override, the default is to give me a stub method like so:

             {
                  throw new NotImplementedException();
              }

Would it be possible to give me a stub method that forwards the call to the base class with the parameters? This would seem like a more useful stub to build on.

  • Last comment about the editor (honest!). I find the bold class names a bit distracting, as well as the squares that appear around matching delimiters. I lose track of the insertion point when the magic squares appear and start hitting the arrow buttons until they go away.
  • There used to be a “Set As Start Page” option in the context menu for a web form in the solution explorer window, but there is not in the CTP. Hopefully this is just a temporary omission as it’s a nice way to avoid an extra navigation step when starting the debugger.
  • Please don’t change the shortcut keys. It took me months to stop pressing F7 after moving from 6.0 to NET.
  • The data visualizations are coming along very well.

I’m wondering how well the CTPs are working for Microsoft. Are they getting the early and useful feedback they were hoping for? Most of the comments on JRoxe’s request for feedback post seem to be of the “yes I’m using it” type.

Now ... on to the May 2004 CTP.

posted by scott with 0 Comments

TechEd TechEd Blah Blah Blah

I don’t have any news to report from TechEd, because I’m not there. I’m not bitter about it though. I’m very happy here in the humidity of Mid-Atlantic USA. I’m very happy walking outside and not being able to hear myself think over the roar of the brood X cicada. I’d say I get a certain amount of glee when swarms of them bash into my windshield like hail pellets in a heavy storm, but you might think I’m some sort of deranged entomophobic who would rather be at TechEd. I don’t want to give you that impression.

I’m glad I’m avoiding the sore feet, the junk food, the airports, the jockeying for position at an AC power source, and being herded like an animal to feeding troughs for lunch.

That’s what I keep telling myself anyway.

posted by scott with 0 Comments

Embedded Code In Reporting Services

If you’ve ever wondered just what you can do with the Code property of a report, this article serves as an introduction.

posted by scott with 1 Comments

SQL Server 2005 : Reduces Carpal Tunnel Syndrome Too!!

I came across an MS slide deck recently touting business intelligence improvements in Yukon via Duncan Lamb. Check out slide 22 – it measures the tedious mouse-clicking festival I experienced today designing a cube to analyze hospital profitability (or lack thereof).

To build the Sales and Warehouse cubes in the sample Foodmart database using SQL 2000 requires 115 wizards and 1,321 mouse clicks.

Building the same cubes in Yukon requires 7 mouse clicks.

Honestly, I dread the cube editor in Analysis Services 2000. All hail Yukon!!

posted by scott with 1 Comments

The Lab Experiment

The Windows Template Library (WTL) first appeared in the Platform SDK in 1999 I believe, and many Windows programmers latched on to WTL as a lightweight and aesthetic alternative to MFC for building GUIs with C++.

About 4 years ago I was at an after hours conference event where someone asked Tony Goodhew about WTL. Tony was, I believe, a PM for VC++ at the time and the response surprised me. WTL, he said, was “an experiment that escaped from the lab” – something to that effect. He then continued to tell everyone not to use WTL. Not in the “use at your own risk this is unsupported” sense but in a “do not use this because I find it very irritating, and it will be destroyed…” sense.

I’m sure there is a story behind his comments, but even after a couple beers it wasn’t forthcoming. In any case, WTL is the second chunk of Microsoft code to reach SourceForge, where presumably it is now safe from Tony.

Tony’s other irritation that evening was the Remote Object Proxy Engine –ROPE. ROPE was part of the unsupported SOAP toolkit version 1. SOAP on a ROPE sounded cute, but didn’t exactly project a professional image. ROPE didn’t make it to V2. I had fond versions of the early toolkit, because I managed to get a client’s J2EE environment working with my company’s COM+ components pretty quickly, even though we both had early toolkits from Microsoft and Apache which did not implement all of the SOAP encoding specifications.

Come to think of it – I wonder if the person who came up with the name for ROPE also came up with the name for SOAPSUDS. If I remember correctly, Don Box declared ROPE flawed, and now SOAPSUDS dead.

posted by scott with 0 Comments

Test-Driven Prose (TDP)

When I work on an article, or a newsgroup answer, I often find myself writing little bits of code to tinker with the framework. Sometimes I just want to try out a scenario before I write up a theory as fact. Other times I just want to see what happens in edge cases through observation instead of digging into a spec or decompile code with Reflector. I’ve found this is a good way to clarify grey areas of documentation.

Many times these little code snippets live inside a project in a temp directory with the name of ConsoleApplication9 or something along those lines, and they eventually end up in the recycle bin. Then tonight it finally hit me on the head with a thud – I should use NUnit, and formalize these snippets into something useful - an ongoing work of tests and experiments.

Now, whenever a new version of the framework arrives, be it a major release or a maintenance / bug fix release, I can execute the tests and see what has changed or been fixed.

I can see a potential benefit for authors who will want to update a work for future versions of the framework. By codifying a book’s descriptions of framework behavior into unit tests, an author can spend less time reading the “What’s new” section of the framework documentation. When combined with unit tests for all the sample code, the turnaround time for revision could be much quicker, which makes both author and editor happy people.

In this community of bright people, I’m sure someone has already thought of this. Maybe there is already a book out about TDP and I just don’t know about it.

Speaking of books, I’ve also been eyeing the book ‘TDD in Microsoft .NET’ as a potential purchase. Steve Eichert has a positive review, and I’m wondering what Marcie Robillard thinks of the book. All of my TDD knowledge has been built from conference and magazine material, so it would be nice to have a more comprehensive and detailed source of information.

posted by scott with 2 Comments

Long Race for Longhorn

It is the third Saturday in May, in Maryland, and that spells Preakness with a capital P. 100,000 people descend into north west Baltimore. Many of them will end up in the infield for an endurance test of drinking, dancing, betting, gawking, passing out from sun stroke, and all sorts of debauchery.

I enjoy an occasional trip to the track. I never win very much, or loose very much, because I bet pretty conservatively. I determined years ago that betting on horses is not my forte. I look at an evening at the track as an evening of entertainment, more expensive than a trip to the movies – but not if I can win just a couple races. I like to stand outside near the track where I can actually see the dirt fly off the hooves.

The hard part about watching outside is I find it difficult to keep track of the horses. I used to try and stay focused on the horse who could give me the best financial outcome, but by the time they reach the backstretch, I’ve lost sight of the horse. I’m trying to listen to the monotone announcer but it always sounds like “blah blah blah your horse blah blah blah”.

So I’ve decided it is more fun to watch the people around me. As the race gets further along, people become more excited. Some of them clap, some of them stomp, some of them “talk” to the horse. They start to yell and jump and make all sorts of rehearsed gyrations intended to bring good luck. My favorites are the people who have an imaginary whip.

I don’t return my attention to the horses until I can see them well down the backstretch. The horses are beautiful at a night race when their coats are gleaming in the lights and dirt is flying everywhere. I can usually pick out my horse for the last 10 seconds and root him on with a few well timed leg slaps.

Longhorn reminds me of the horse races. I don’t know when this horse will cross the finish line. There are many people who want the product to hurry up, and many people who want the product to go out to pasture. The press tries to create controversy and scandal with all sorts of speculations. At the races, when I can't see what the horse is doing, I start watching what the people around me are doing. With Longhorn, that means putting together little applications.

It is fun for me to see what interesting software people are building with Longhorn. There is the Squarified Treemaps app, the NNTP reader, the Calculator, the Virtual Pet, the TranslateIt!, and I took a crack at it myself with the VSS Label Diff (a real yawner in comparison). By release time I’m sure we will all be in a frenzy.

Anyway, congratulations to Smarty Jones, winner of the 2004 Preakness. If you were my horse, I would have named you Starman Jones - like the Heinlein novel, but at 3 – 5 odds I still would never have bet on you.

posted by scott with 0 Comments

Office 2010

When Beth came to the office door I knew the news wouldn’t be good. High energy and optimism combined to give Beth a cheerful personality, but the look on her face didn’t bode well for the project schedule.

“Well, I’m back from legal,” Beth said. “We have some work cut out for us”.

“What did they say about the latest build?” I asked.

“Big problems with the File commands,” she said, “we have to cut the Import command completely”.

“What?” I asked, dismayed.

“Yep, last year’s ‘SCO versus Corel’ ruling used wording in DMCA III to prevent an application from opening file types registered to another application. It gets worse, though, we will need to cut ‘Save As Web Page’ too.”

“What?” I said, incredulously.

Beth studied a long list of notes on her tablet. “Yep, submarine patents again - small company in Dog Lick, Kentucky has all lossless and lossy picture formats locked up. Until we license some more algorithms we can only render images using 4 bit color bitmaps, but what’s really going to hurt the schedule is the hold up on ‘Send As Attachment’.

“Well,” I said, “Steve and Bill are meeting with President Sheen next week to see if someone can amend CAN SPAM 2009 for us”.

“I hope Charlie can push some senators around,” Beth replied. “The list of approved email clients has been really thin. The ‘Share Over WiFi’ feature has no chance though, and healthcare industry representatives are saying no copies will be deployed unless we allow them a hook into the ‘Open’ command”.

“They can’t do that”, I exclaimed.

“Well, according to the latest HIPPA bill in 2008, healthcare workers need to read, print, and sign an audit form before opening any document which could potentially contain information about a current, past, or possibly future patient, unless the person is standing in the same room with three forms of identification and a notarized release form. Even veterinarians have to be careful now. We have no choice with the current legislation.”

“So what can we have on the File menu?” I asked. “Exit?”

“As long as we RTM before ‘The New Improved PATRIOT Act,” said Beth. “If not, we will need to add the new stealth activity upload.”

“Not a chance of releasing with these setbacks,” I muttered.

”I didn’t even have time to get into the Edit menu with the lawyers,” Beth continued. “I’m sure last month's Supreme Court ruling on the Revised Database and Collections of Information Misappropriation Act is going to kill the ‘Paste’ command”.

“This is stupid!” I blurted. “Applications don’t copy data, people do!”

“Welcome to software design in 2010,” Beth said, then smiled, picked up her tablet, and strode from the room. I sighed heavily, and whirled my chair around. I opened my bottom desk drawer, and pulled out my bar review notes. “No innovation without litigation,” I thought to myself. Those good old days are gone.

posted by scott with 1 Comments

Double Check Locking In The News Again

Once upon a time, Chris Brumme posted about shortcomings in the memory model of the ECMA specification for the CLR. Not necessarily shortcomings from a runtime performance point of view, but shortcomings from a programmer productivity point of view. In the post he discussed why double check locking requires some attention to detail. Specifically, the following code snippet may not be as thread safe as it first appears.

if (a == null)
{
  lock(obj)
  {
    if (a == null) a = new A();
  }
}

There are interesting comments in response to the post, and eventually Jon Skeet devoted a page to singleton construction. Jon avoids the double check locking issue altogether by using a static field initializer in a nested type. The approach Jon promotes works very well except in cases where you do not know the singleton type to construct at compile time. For example, the type of singleton to construct may be an object derived from an abstract base class in a provider / pluggable architecture and the application reads the type to construct from a config file.

If you can’t use a static field initializer, but still want safe, lazy instantiation, then it seems to me that Brad Adam’s post about using the static MemoryBarrier method of the System.Threading.Thread class is the direction to go, for a couple reasons.

To me, the volatile keyword carries specific overtones. I still think of programming with memory mapped IO when I see the volatile keyword. Volatile variables are completely unsafe for caching. Imagine having a byte in memory hooked up to a thermometer laying on your desk. Not even a single CPU machine knows when the memory location may update with a new temperature value – you have to read it from main memory every time. Volatile has an unfortunate connotation for a singleton reference, which after construction isn’t going to change.

Secondly, the use of Thread.MemoryBarrier explicitly calls out what needs to happen for the code to be thread safe. For people who stumble across the code in the future, they will not need to think of the side effects of a volatile variable when Thread.MemoryBarrier is in place.

Not only do we have maintainable code showing programmer intent, there is a performance bonus too. That being said, if this code was not part of a singleton, and other methods were involved, I'd prefer volatile.

posted by scott with 1 Comments

Server Software For The Desktop

For the past four years I’ve always run a server version of Windows on my development machine. I do this for a few reasons. On those rare occasions when I find myself in a server room around a production machine, I feel comfortable knowing where all the buttons and settings are. It’s hard to feel comfortable when you have only a vague memory of where you saw a particular configuration dialog, and pointy haired people stand behind you spouting “Is it online yet?”.

The other reason is that I want to feel like I am getting my moneys worth from my MSDN subscription. Some people keep their subscription discs in numerical order. I like to keep mine ordered by license fees. That way if there is something expensive I have not installed as yet, I can throw it on a virtual PC and tinker around.

Since switching to a DVD subscription two years ago, it’s been much harder to compute the license fee value per disc. It requires a calculator. Then again, the CD subscription was driving me insane years ago. I’m convinced Microsoft implemented the CD numbering and coloring scheme using a stochastic process. First, you received about 2400 CDs each year. If you organized the CDs numerically, it was impossible to find any specific product inside without an up to date annotated index, and you never knew when any particular CD was obsolete. The numbering sequence often left large gaps, but invariably a CD would show up with a number in between two other CDs and all the discs had to be manually bubble-sorted throughout the CD binder. I’m certain the process has driven some percentage of developers to drink. One company I worked at budgeted 40 intern hours a month to organizing MSDN subscription binders for developers.

But getting back to my previous topic, which is running server software on what is essentially a desktop machine. Windows 2003 is different beast and requires some tweaking to offer a pleasant desktop experience. Kevin Moore offers a tip on getting rid of the Shutdown Event Tracking. MSFN has some other tips to enable themes, video acceleration, audio acceleration, and more. By the time you get to the end of the guide, you’ll be able to watch those MSDN webcasts in a nicely themed Windows Media Player at full frame rate.

The only drawback to running 2003 as a desktop OS is you’ll find some software refuses to install, saying it requires Windows XP. Also, some utility software, like good anti-virus software, has tiered pricing for server class machines. On the other hand, it is the only OS where you can install some of the new, expensive stuff.

Oh, and at least some of those obsolete MSDN CDs have found a good home.

posted by scott with 1 Comments

What Goes On At the ASP.NET Website?

First, I think ASP.NET is a great web site, and featuring articles from all over the community helps build a diverse and informative resource for developers.

But…

There are problems which in my opinion devalue the site. I used to think there was some forethought and human intelligence behind the scenes which would take the steps necessary for the site to appear with the polished veneer you’d expect from a site with Microsoft’s name attached, but the ‘man behind the curtain’ appears to be 100% silicon.

Take today’s new article description. This is obviously meant to reach someone who is responsible for the ASP.NET daily article content and not meant to appear on the front page. I’m sorry to say John, even if you used the official contact email of aspnetw3@microsoft.com, you won’t get a response, at least in my experience.

(UPDATE: The article has changed as of 3:20 PM EST. The description used to begin with "Dear Editor, Thank you for accepting my article,,,," Thank you ASP.NET!)

In the past there have been articles that have nothing to do with web development, which doesn’t bother me too much, but when this happens I start to wonder what sort of standards the site maintains. What I do find troubling is how at least two articles were duplicated in the space of 10 days this year, which indicates to me nobody is paying attention to what is going on. The front page content is just a FIFO queue in a database. My guess is, someone could post a link to Michael Jackson's legal documents and the article will show up on the front page of ASP.NET.

I can appreciate filtering content to feature a daily article (indeed, even having a daily article) can be a tough job. Hopefully, someone can step up and address the issue. Given the site’s domain name, and the site’s owner, there are certain expectations to meet. Don’t devalue the site and the work by the author’s who contribute to this resource.

posted by scott with 1 Comments

New Longhorn Bits

Robert McLaws has compiled a list of “things to do” while downloading the latest Longhorn bits, and I may make it through most of them as I still have 5 hours left (not counting the SDK transfer of 380 MB). The transfer rate has steadily been falling from ~ 70 KB/sec to about ~ 20 KB/sec as the evening progresses. I don’t think I will be seeing the installation and setup screen until after a night of sleep. Update: it appears I have downloaded the DDK, not the SDK, as the SDK has yet to appear on subscriber downloads.

Chris Sells points out there will not be any Visual Studio bits to put on this build (M7.2 Longhorn). I might have to grab vi and see if the muscle memory in my fingers can still play :w and yy like the days of old.

Wesner Moise tells us that MSDN has already updated the online Longhorn SDK to reflect the latest build.

Finally, Scoble addressed all the hardware requirement speculators who believe Longhorn will require a creation from the Los Alamos labs to run. I know I’ve been running the PDC bits on what some would consider ridiculously modest hardware – a 1Ghz P3 with 1GB of RAM. Quit laughing! It runs pretty well!

posted by scott with 2 Comments

ASP.NET Validation : False Sense of Security?

A subtle and dangerous bug appears regularly in newsgroup postings, and some have even sighted the problem in sample code from articles and books.

Take the following ASPX snippet:

<asp:textbox id="txtPassword" runat="server"/>
<asp:button id="btnSubmit" runat="server" Text="Submit"/>
<asp:requiredfieldvalidator id="valReqPassword" 
            runat="server" ErrorMessage="Password required" 
            ControlToValidate="txtPassword"/>

And the following code-behind logic:

private void btnSubmit_Click(object sender, 
                             System.EventArgs e)
{
   SetUserPassword(txtPassword.Text);
   Response.Write("Password set!");
}

If you enter a blank password and click submit on this form (in a DHTML capable browser), the validation control prevents the post back and displays an error message next to the TextBox control. Testing complete, validation works, continue to the next form.

I’m sure many of you have spotted the problem, but judging from newsgroup postings this isn’t so easy for newcomers to catch. One can expose the bug by setting the EnableClientScript property of the validation control to false. Now if the user enters a blank password and clicks submit the validation error message still appears, but in addition all of the code inside the click event handler executes. Unless there is a database constraint in place, chances are the user just set their password to an empty string.

Even with client side scripting enabled, we know it would be easy to give the software un-validated input with the System.Net.WebRequest class. Client side validation works so well in the browser, however, so it is hard to see this vulnerability.

The crux of the misunderstanding is how the client side validation behavior is entirely different from server side behavior. On the client side, if validation fails, the flow of execution effectively stops. On the server side, you have to check Page.IsValid and alter the flow yourself.

Darren Neimke posted today about the difficulty in achieving elegance when writing functionality spanning client and server sides. I agree, at times it still seems much harder than it should be to get things right (with pretty code), particularly since the two sides behave so differently. Perhaps failed validation should trigger an exception on the server side - but I realize this would break many existing applications. Still, something to think about ... and watch for Page.IsValid in code reviews.

posted by scott with 2 Comments