The .Net Days Of Old

Monday, April 30, 2007 by scott
2 comments

My association with .NET started over 6 years ago. In those early days I used C++ and COM as a point of reference for everything I was learning in .NET and C#. Destructors versus finalizers, Assembly.Load versus LoadLibrary, Metadata versus COM+ attributes, and of course - memory leaks versus managed heaps.

Those were fun times.

I'm gearing up for a customized Pluralsight class that includes material from the Applied .NET and Applied ASP.NET 2.0 courses. I also need some perspective of a Visual Basic 6.0 developer in a .NET land.

This reading list helps to re-live the days of old (from a VB6 perspective):

Looping 101

Sunday, April 29, 2007 by scott
9 comments

Here is a pop quiz for language aficionados.

Examine the following class:

public class Foo
{
   
public int GetUpperLimit()
    {
        Console.WriteLine(
"GetUpperLimit invoked");
       
return 5;
    }

   
public IEnumerable<int> GetCollection()
    {
        Console.WriteLine(
"GetCollection invoked");
       
return new int[] { 1, 2, 3, 4, 5 };
    }
}

Now examine the following console mode program:

class Program
{
   
static void Main(string[] args)
    {
       
Foo foo = new Foo();

       
for (int i = 1; i <= foo.GetUpperLimit(); i++)
        {
           
Console.WriteLine(i);
        }

       
foreach (int i in foo.GetCollection())
        {
           
Console.WriteLine(i);
        }
    }
}

 Without using a compiler, do you know:  

  • How many times "GetUpperLimit invoked" will appear in the output?
  • How many times "GetCollection invoked" will appear in the output?

Now, examine the same console program in VB:

Sub Main()
   
Dim foo As New Foo()

   
For i As Integer = 1 To foo.GetUpperLimit()
        Console.WriteLine(i)
   
Next

    For Each i As Integer In foo.GetCollection()
        Console.WriteLine(i)
   
Next
End
Sub

 Bonus third question:  

  • Will the output of the VB program be the same as the C# program?

I was suprised by the answer to the last question ...

Writing Technical Books

Saturday, April 28, 2007 by scott
1 comment

The skill of writing is to create a context in which other people can think.

-- Edwin Schlossberg

Jeff Atwood presents a visual contrast of two WPF books in "How Not To Write A Technical Book". I haven't read either WPF book, but Jeff's post did provoke some thinking…

Color Me Code

It's amazingly difficult to read code in monochrome these days. Language keywords, program comments, and string literals all blur into lumps. There is now chance to scan the source code for the important bits. Unfortunately, many publishers are unwilling to accept the higher cost of full color printing (except for technical books in the higher-education market, where the consumer is a PHY 101 student and at the publisher's mercy). Most college textboxes are printed in full color, but full color computer text books are a rare find.

If we look at some currently shipping WPF books, we see they are all heavily discounted from their list price and fall into the same price range:

It seems that publishers are pricing their books based on the competition and not on the production costs. Shrinking margins don't bode well for features like color.

I Have a Tip for You

Another topic in Jeff's post was the use of sidebars and callouts. Some people love sidebars. I don't.

A good technical book makes me think. An even better technical book makes me get to the keyboard to try something. Books with colored sidebars on every page are telling me there is something more important to read and rarely make me think or code. Instead, I'm burning cycles on context switching.

Warning: In 5 billion years, the sun will run out of hydrogen and become a red giant. Make sure your offspring will be located at a safe distance.

I see sidebars used as a copout. The author gave up trying to work an important fact into the technology's storyline, and instead threw the content inside a cartoon box. To be fair, it's not the author's fault. All publishers encourage this behavior. I think the publishers want books to look more like the web…

Can I Get An Ad?

Books are competing with the web, to be certain. Magazines are, too. Many tech magazines are free because they are chocked full of ads. Perhaps book publishers will one day start including advertisements to offset the cost of color printing - I hope not.

Fleeting Visions Of Doom

Tuesday, April 24, 2007 by scott
4 comments

Your mind is racing and your fingers are struggling to keep pace. Clickety-clackety-clickety-clackety.

New code, test code, refactored code – it pours across the screen. Clickety-clackety-clickety-clackety.

There is no passing of time in this superb condition of lucidity. Clickety- clackety-clickety-T-T-TWACK.

Opps. What was that?

Something went wrong. A finger slipped! You hit the wrong combination of keys, for sure – but which keys? Was that a menu that flashed by? The intensity of that red disk light fills you with dread. Did you trigger some hidden doomsday command that is now writing 0s to the system drive? When was the last system backup? When was your last commit? Why isn't this computer responding? What on earth is this disk drive doing? Should you cut power now and salvage what you can?

Oh, it's back <exhale>.

It's just the Visual Studio "Add New Reference" dialog.

Cancel.

For a fleeting moment, you thought all was lost.

Now, about that backup….

What's Wrong With This Code? (#14)

Tuesday, April 17, 2007 by scott
11 comments

MSDN says the List.ForEach method will "perform the specified action on each element of the List".

The following program does print out a haiku to the console, but does not make the haiku all lowercase.

using System;
using System.Collections.Generic;

class WWWTC
{
    
static void Main()
    {
        
List<string> haiku = new List<string>();

        haiku.Add(
"All software changes");
        haiku.Add(
"Upon further reflection -");
        haiku.Add(
"A reference to String");

        
// make it lowercase
        haiku.ForEach(
                    
delegate(string s)
                    {
                        s = s.ToLower();
                    }
        );

        
// ... and now print it out
        haiku.ForEach(
                    
delegate(string s)
                    {
                        
Console.WriteLine(s);
                    }
        );
    }
}

 What's wrong?  

Event Validation Errors and Network Congestion in ASP.NET

Friday, April 13, 2007 by scott
5 comments

Joseph Rattz emailed me about posts I wrote last year covering ASP.NET event validation (see ASP.NET Event Validation and "Invalid Callback Or Postback Argument" Part I and Part II). In the posts I describe one scenario where an event validation exception can appear, and describe how to prevent the exception. In the scenario, client side script dynamically adds values to a list (select) control. When the user POSTs the form to the server, ASP.NET sees a new value and concludes something is wrong. The list comes back to the server with a value that wasn't present when the list left the server. ASP.NET tracks the legal values by serializing them into a hidden input control with an ID of __EVENTVALIDATION. This event validation feature helps to prevent all sorts of form spoofing attacks.

Joe's scenario was odd, not only because the invalid postback argument exception appeared sporadically, but because the source of the exception was a TextBox control!

ArgumentException: Invalid postback or callback argument.  ...
  System.Web.UI.ClientScriptManager.ValidateEvent(..) ...
  System.Web.UI.Control.ValidateEvent(..) ...
  System.Web.UI.WebControls.TextBox.LoadPostData(..) ...

 

What could ASP.NET possibly validate about a TextBox? A server can expect specific values from a DropDownList, but a plain TextBox allows free form text entry by the user. The answer (via Reflector), is that the TextBox control only validates that its UniqueID is present in the legal arguments described by the __EVENTVALIDATION data. Even after knowing this information, it's hard to see what could go possibly wrong with a TextBox.

Joe's theory, which I believe to be correct, is that the user might create a postback before their browser even receives the __EVENTVALIDATION form input. This could happen, for example, over a poor connection. The resulting POST won't contain the __EVENTVALIDATION input, and thus ASP.NET cannot validate the postback arguments. The klaxons wail. Glass breaks. The runtime throws an exception.

One way to validate this theory is to simulate network congestion with the following control. We flush out the output stream, sleep, and then continue rendering.

using System;
using System.Web.UI;
using System.Threading;

namespace OTC
{
    
public class FlushAndSleep : Control
    {
        
protected override void Render(HtmlTextWriter writer)
        {
            writer.Write (
"Begin Render<br>");

            
base.Render (writer);

            Page.Response.Flush();

            
Thread.Sleep(2000);
            writer.Write(
"End Render<br>");
        }
    }
}

 

Stick the control into the following page:

<%@ Page Language="C#" %>
<%
@ Register TagPrefix="otc" Assembly="App_Code" Namespace="OTC" %>

<form id="form1" runat="server">
    <div>
        <asp:textbox runat="server" id="TextBox1" />
        <asp:button runat="server" id="Button1" text="Submit" />
        <br />        
        
<otc:FlushAndSleep runat="server" ID="FlushAndSleep" />
    </div>
</
form>

 

Run the page and click the button as soon as it appears in the browser. Voila! Instant "invalid callback or postback argument" exception! If you ever see the exception occur sporadically, this might be the reason.

DTS in SQL 2005 - Good News and Bad News

Thursday, April 12, 2007 by scott
3 comments

DTS has always worried me. Unfortunately, I have 331 reasons to worry:

PS > gci -r -i *.dts | group Extension
Count   Name
----- ----         . . .
  331   .dts 

Five years ago, ADO.NET didn't have a bulkload API, and DTS seemed like the best tool for moving and transforming millions of records. This was despite the fact that the binary DTS packages check into source control as opaque blobs, and the cumbersome UI makes even simple changes difficult. We thought we'd need to write and distribute ~50 packages total, but feature growth and support for additional 3rd party databases has ballooned the original estimate.

The application using these packages has to support SQL 2000 for the foreseeable future. Not every customer has budgeted for a new SQL 2005 license, unfortunately. The good news is that SQL 2005 will run the DTS packages, even though it cannot migrate but a handful of them to the new SSIS platform.

Another piece of good news is that you can edit DTS packages in the SQL 2005 Management Studio after downloading some designer components. The bad news is that the designer is still suboptimal. For instance, the Home, End, Backspace, PageUp, and PageDown keys will quit working in the designer. The good news is that this problem is fixed in SP2. The bad news is that the fix changed the designer into a modal dialog. Modal dialogs should be banned from all software in the universe.

If you haven't started your DTS migration yet, here are a few resources I've collected.

DTS Services for SQL 2005 FAQ

SQL Server 2005 Integration Services Backward Compatibility

Known Package Migration Issues

A tool to improve DTS to SSIS migration

Any other good ones out there?

by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!