August 2006 Entries

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

This program throws an exception at runtime. If you've been burned by this problem before, you'll know what's wrong before you even see the definition for class Bar... using System;class Program{  static void Main()  {    Foo foo = new Bar();  }}abstract class Foo{  public Foo()  {    Init();  }  protected abstract void Init();}class Bar : Foo{  string message;  public Bar()  {    message = "Hello!";  }  protected override void Init()  {    Console.WriteLine(message.ToUpper());  }}

Weird Thread Behavior

I stumbled on a forum posting recently that led me to write the following code: using System;using System.Threading;class Program{  static void Main()  {    ThreadStart doNothing = delegate { };    ThreadStart createThreads =      delegate      {        for (int i = 0; i < 50; i++)        {          Thread t = new Thread(doNothing);          t.Priority = ThreadPriority.BelowNormal;          t.Start();        }      };    for (int i = 0; i < 2; i++)    {      Thread t = new Thread(createThreads);      t.Start();    }    Console.ReadLine();  }} This program behaves badly on a single processor machine, and pegs the CPU at 100% for over two minutes. On a multi processor machine, the program finishes all the threading work in the blink of an eye - only a brief CPU spike. Strangely, if I remove...

My $100 Spending Spree with Windows Workflow

The WF discussion that Brian Noyes kicked off continues with excellent points from Jon Flanders and Thomas Restrepo. The following posts are full of information from smart people who know WF very well: You have to understand a technology to use it effectively…Workflow ComplexityWorkflow Complexity Part 2 Tech evangelist Matt Winkle then asked how to improve WF. In other words - quit bitching and offer us constructive ideas. If I had a $100 budget to improve WF, I'd divide the money as follows: $30 on designer improvements. The designer has a number of minor irritations, but one stands out at this...

My Gripes with Windows Workflow

Brian Noyes' post "Understanding Windows Workflow and its complexities" has me thinking. I know a few people who have given up on Windows Workflow altogether. WF imposes its own paradigm. If your way of thinking is different from the WF way of thinking, you are going to live in a house of pain. Brian's first complaint is about the designer. I've found the designer to be clunky. There are behaviors you come to expect in Visual Studio, like being able to double-click somewhere and have the designer perform some work. The WF designer never acts intuitively. There are also places...

Powershell: Attach Debugger To ASP.NET Worker Process By Name

For those who don't like the "Attach To Process" dialog box, just pass the application pool name to this Powershell function: function debug-wp([string]$name){  if([String]::IsNullOrEmpty($name))   {    throw "Usage: debug-wp -Name "<appPoolName>"   }  $wplist = get-wmiobject Win32_Process -f "Name='w3wp.exe'"  foreach($wp in $wplist)  {    if($wp.CommandLine -match "-ap `"(.+)`"")    {      if($name -eq $matches[1])      {        & vsjitdebugger.exe -p $wp.ProcessID        break      }    }  }  if($name -ne $matches[1])  {    write-host "Could not find AppPool" $name  }}  

Haack for President

Phil Haack's blog has been on fire this month. Here is a sampling: Open Source Is Free Like A FlowerTiny Trick For Viewstate Backed PropertiesLog4Net and External Configuration file In ASP.NET 2.0Fun Iterating PagedCollections With Generics and Iterators All great posts, but the pièces de résistance are "ASP.NET Supervising Controller (Model View Presenter) From Schematic To Unit Tests To Code" and "Tying MVP To the ASP.NET Event Model" I particularly enjoyed the last post. Some people will freak out at the thought of tying the V in MVP to a specific technology. For the business layer and below, the thought is cause for...

What's Wrong With this Code? (#3)

Here is a Visual Basic program with bowling scores in a multi-dimensional array. Two players bowled three games each. The program tries to display the total score for each bowler, but has a small problem. Can you spot it? Module Module1  Sub Main()    Dim allScores As Integer(,) = _        {{101, 128, 143}, {123, 115, 116}}    ' for each player    For i As Integer = 0 To allScores.GetUpperBound(0)      Dim score As Integer      ' for each game      For j As Integer = 0 To allScores.GetUpperBound(1)        score = score + allScores(i, j)      Next      Console.WriteLine("Player {0} score: {1}", i + 1, score)    Next  End SubEnd Module

Windows Workflow as a Rule Engine

One interesting facet to Windows Workflow is how I can combine procedural knowledge with declarative knowledge. Procedural knowledge is the "how-to" knowledge of performing a task. If a bank requires me to make three web service calls to process a payment, I can arrange those three calls inside a Sequence activity and model the exact ordering of calls required by the bank. WF also provides a Policy activity to process declarative knowledge. Declarative knowledge is the knowledge of facts and relationships between data. Instead of "how-to" knowledge, declarative knowledge provides the "what-is" knowledge. For example, if I want to expedite...

Treat Warnings as Errors in ASP.NET 2.0

The web.config file controls all compilation settings in a default web site project. To treat compiler warnings as errors, you'll need the following in web.config: <system.codedom>  <compilers>    <compiler                    language="c#;cs;csharp" extension=".cs"        compilerOptions="/warnaserror"       type="Microsoft.CSharp.CSharpCodeProvider,              System, Version=2.0.0.0, Culture=neutral,             PublicKeyToken=b77a5c561934e089" />  </compilers></system.codedom> Note: You can only twiddle with compiler settings under full trust, but then you'll only need this setting at build time.

7 Virtues for Software Developers

Diligence - Diligent developers take ownership of their work without being possessive. Diligent programmers fix broken windows. Humility - Humble developers take pride in their code, but don’t snub constructive criticism. Humble developers know they can always improve themselves. Patience - Patient developers remain calm during times of stress, and don't surrender to the temptations of a quick fix. Patient developers have the endurance to carry a product across the finish line. Liberality - Broad-minded developers base their decisions on proofs and particulars instead of preconceptions and prejudices. Broad-minded developers listen to the other side and attempt understanding. Creativeness...

Dear Candidate

Every so often, I get an email that looks like: Dear Candidate, While conducting a search for our client we came across your resume and it appears to be a good match for this opportunity. Blah blah fast-paced blah blah great benefits blah blah and so on. Using the word "candidate" is not only presupposing, but a sign of laziness. Even the male enhancement spammers can personalize their messages. I'm sure the recruiter will have his pick of top talent with emails like this. I think I'll reply with the following. Dear [Recruiter Name], Thank you for getting in touch about...

What's Wrong With this Code? (#2)

A developer wanted to keep track of some birthdays with the following table design and data. CREATE TABLE [Birthdays](  [Name] varchar(50),  [BirthDate] datetime   )INSERT INTO [Birthdays] VALUES('Gene Wilder',  '6/11/1935')INSERT INTO [Birthdays] VALUES('Nicola Tesla', '7/9/1856')INSERT INTO [Birthdays] VALUES('Miles Davis',  '5/26/1926') To sort the data by name and by date, the developer wrote a single stored procedure to handle both cases. CREATE PROC GetBirthdays  @Ordering intASBEGIN  SELECT [Name], [BirthDate] FROM [Birthdays]  ORDER BY    CASE @Ordering      WHEN 1 THEN [Birthdate]      WHEN 2 THEN [Name]     ENDEND The developer tested the proc by passing a value of 1, and was pleased to see a resultset ordered by birth date. What can go wrong? (Hint: Try passing...

Windows Workflow Hosting

Hosting Windows Workflow is a new article covering the WorkflowRuntime class and the WF services. The article shows how to configure and use the scheduling, persistence, and tracking services provided by Windows Workflow. Feedback is appreciated.

ASP.NET Best Practice Analyzer

The alpha release of the ASP.NET Best Practice Analyzer was about 5 weeks ago. Similar to the popular SQL Server BPA, the ASP.NET BPA evaluates a set of best practice rules and tells you about configuration problems in your applications. The tool checks both machine level and application level config files. Currently, the tool only has a handful of rules. It will raise red flags if the application runs in full trust, or if debug / trace flags are enabled, and a few others. Ironically, the tool suggest AutoEventWireup="false", which isn't the default for C# web forms in VS2005. I can't think of...

Unit Testing Workflow Activities

I've been kicking around the best approach for unit testing a custom activity for Windows Workflow. I haven't found an approach I'm comfortable with as yet. Here is a simple, contrived custom activity. using System;using System.Workflow.ComponentModel;using System.Workflow.ComponentModel.Serialization;[assembly:XmlnsDefinition("http://odetocode.com/wf/activities",                          "OdeToCode.WF.Activities")]namespace OdeToCode.WF.Activities{   public class CreateMessageActivity : Activity   {    private string _recipient;    public string Recipient    {      set { _recipient = value; }    }    private string _message;    public string Message    {      get { return _message; }    }       protected override ActivityExecutionStatus       Execute(ActivityExecutionContext executionContext)    {      _message = String.Format("Message to {0}", _recipient);      return ActivityExecutionStatus.Closed;    }   }} It's tempting to create a unit test that instantiates the activity and calls Execute directly, but most activities are not this simple. The ActivityExecutionContext class is sealed, and mocking out all the...

Something You Don't Want To See In Your Event Log

Source: MSSQL Server17052 : Cannot recover the master database. Exiting. The chkdsk result was ugly, too.....

What's Wrong With This Code?

The developer who wrote the following code expects to see "Hello World!" printed twice. What will the developer see, and why? (Hint: "Hello, World!" will only appear once). using System;class Program{    static void Main()    {        Console.WriteLine(Child.Message);        new Child();        Console.WriteLine(Child.Message);    }}class Parent{    static Parent()    {        _message = "Hello!";    }    static public string Message    {        get { return _message; }    }    static protected string _message;}class Child : Parent{    static Child()    {        _message = "Hello, World!";    }}

Scott Allen
Posts - 869
Comments - 4493
Stories - 14