Ryan's profileCeiled's stuffPhotosBlogListsMore Tools Help

Blog


    April 23

    ExecutionEngineException when raising the PropertyChanged event

    If you've ever seen an ExecutionEngineException in .NET, you know that it's nasty. It even sounds intimidating. It's the error that's thrown by Environment.FailFast() -- MSDN describes it as "the exception that is thrown when there is an internal error in the execution engine of the common language runtime." Before last night, the only time I'd ever seen it was when I was generating and running my own IL assembly code and I did something wrong like pop too many values off the stack or something.

    However, last night I got it while raising a PropertyChanged event on my INotifyPropertyChanged object, immediately after using PropertyChangedEventManager to subscribe to it. I scratched my head...how the hell did I manage to cause an internal error in the CLR? I restarted Visual Studio, I rebooted my machine, I tried it on other machines to see if it was some sort of crazy corruption on my system, but it was completely repeatable.

    Finally, in desperation, I set up .NET source stepping (something I've been meaning to do for a while anyway) and ran it again -- this time, instead of showing up on the line where I raised the PropertyChanged event, the exception stopped on this code in WeakEventManager.cs:

                bool condition = listener.ReceiveWeakEvent(managerType, sender, args);
                if (!condition)
                {
                    Invariant.Assert(condition, SR.Get("ListenerDidNotHandleEvent"), SR.Get("ListenerDidNotHandleEventDetail", new object[] { listener.GetType(), managerType }));
                }

    That's right...when ReceiveWeakEvent returns false (indicating that the listener did not handle the event being raised), WeakEventManager calls Environment.FailFast(). This is the software equivalent of people in horror movies choosing to shoot themselves in the face rather than turn into a zombie and possibly hurt their friends. It writes an event to the Event Viewer that says "Unrecoverable system error."

    This may be the most ridiculously over-reactive error processing I've ever seen in my life, and for some reason, Google is completely unhelpful on this subject. Searching for "PropertyChangedEventManager ExecutionEngineException" turns up virtually nothing -- the only result in English was a 404, and Google's cached version didn't have either keyword in it, for some reason. Hopefully this will save someone the intense frustration I experienced when I accidentally returned false from a random event handler somewhere, and was told that my execution engine had become unrecoverably corrupt and would be shut down for its own protection. If this post helps you, please tell me so in the comments so I'll know my time wasn't completely wasted.

    November 05

    Installing Virtual PC 2007 SP1 on Vista

    Ok, I spent several hours wrestling with Virtual PC this morning so I could play around with the Visual Studio 2010 CTP that was recently released as a Virtual PC image. Since Googling for the solution was an exercise in frustration, I've decided to post the two steps that wound up being necessary to get it installed properly.
     
    The first problem was that when I ran setup.exe after downloading it, it would give me a UAC prompt, and then nothing would happen. Task Manager indicated that setup.exe and msxml6-KB927977-enu-x86.exe were both running -- left alone for ten minutes, nothing happened. I finally killed them and did some searching. It turns out that running setup.exe directly doesn't work. You need to open a command prompt and run "setup.exe /c /t ." to extract the two installers (msxml6-KB927977-enu-x86.exe and Virtual_PC_2007_Install.msi) that are packed in setup.exe and run them separately. The /c tells it to extract the files, and "/t ." tells it where to put them -- if you don't specify the /t option, they'll get dropped in your Temp folder. I preferred to put them right next to setup.exe.
     
    Once you've extracted the sub-installers, just run the xml patch -- this is a straight-forward installation that you can simply click through.
     
    The one that really took forever and that I never did actually find a solution to online was what happened when I tried to install the MSI. After clicking through the initial prompts, accepting the EULA, and approving the UAC prompt (which consistently took almost a minute to come up after accepting the EULA), it would get halfway through the installation and then start rolling back, giving the message, "The wizard was interrupted before Microsoft Virtual PC could be installed." Looking in the Event Viewer revealed that error 1603 was being reported, but I couldn't find any indication of the cause. Googling indicated that there should be an install log called VPCInstallLog.txt, but I searched my entire C: drive and never found it.
     
    Google gave several possible solutions for this error, ranging from arcane twiddling with DCOM permissions to closing some instant messenger application called XFire, to running some arcane utility for adjusting impersonation settings. None of these seemed to apply to me, and I was completely at a loss. I ran the installer several times to no avail. Finally, I opened an administrative command window (right-click on your command window shortcut and select Run As Administrator) and ran the MSI from there. AHA! It worked. Apparently, the Virtual PC installer simply doesn't handle UAC properly.
     
    I'm honestly astounded that I couldn't find this incredibly simple solution anywhere online. Can an application that claims to support Vista really have such a fundamental problem? If this post saves even one person the time and frustration I spent trying to figure this out, I'll consider the whole ordeal worth it. So please, if you read this and it solves your problem, let me know in the comments.
    March 29

    Delegates and helper functions

    Delegates serve a very important purpose in .NET, and particularly in .NET 3.5, with its tendencies towards functional programming. LINQ simply wouldn't make any sense without them. Along with the influx of concepts from functional programming into .NET has come a more comprehensive set of built-in delegates useful for helper functions in the form of various overloads for Action<> and Func<> that take their parameters as generic methods without imparting undue semantic implications about how they'll be used (for example, Action is appropriate for use just about anywhere you might want a delegate that returns void and takes no parameters, but ThreadStart implies semantic meaning). One result of this renewed emphasis on the use of delegates as cleanly-packaged bits of logic that can be passed around as first-class objects rather than being restricted to simple event handlers, as they mostly were in the original version of .NET, is that the strongly-typed nature of delegates has become more constricting.

    The fact that delegates are strongly-typed is generally a good thing, but it can sometimes get in the way. Consider what is quite possibly the single most common delegate-related pattern in all of .NET:

    protected virtual void OnMyEvent(EventArgs e)
    {
        if (MyEvent != null)
        {
            MyEvent(this, e);
        }
    }

    I can't even count how many times I've written code that looked like this, and it frustrates me to no end. Why? Because I get tired of checking delegates for null. I want to write a helper function that will do the null check for me, to which I can simply pass my delegate and the arguments. One could argue that OnMyEvent() serves that purpose, but I want a generic helper function -- I don't want a new one for every kind of function that I may want to invoke.

    The trouble is, .NET does not provide any simple way to write such a helper function without sacrificing significant performance. Either the signature of the helper function would need to match the signature of the delegate, or it would need to take an object array and call DynamicInvoke() which, according to my measurements, takes about 1,000 times longer than invoking the delegate directly. That obviously won't do.

    Before going into the solution, I probably need to justify the need a bit more. Like I said, the scenario that made me want this solution is pretty trivial. However, it's just one example. Consider the following code:

    public void SetUpWeakBinding(BindingList<int> sourceList, BindingList<int> boundList)
    {
        WeakReference weakRef = new WeakReference(boundList);

        ListChangedEventHandler listChanged = null;

        listChanged = delegate(object sender, ListChangedEventArgs e)
        {
            BindingList<int> weakList = weakRef.Target as BindingList<int>;
            if (weakList != null)
            {
                SynchronizeLists(sourceList, weakList, e);
            }
            else
            {
                sourceList.ListChanged -= listChanged;
            }
        };

        sourceList.ListChanged += listChanged;
    }

    I've elided the part that actually synchronizes the lists, because that's not the point. What this function does is set up a listener on sourceList's ListChanged event that will perform some logic to keep the two lists in question in sync. The important bit is that the boundList is stored as a WeakReference, which allows it to be garbage collected. If it gets garbage collected and the ListChanged event fires again, then the delegate is removed from the invocation list entirely, leaving no trace of the garbage-collected list. This code, minus the SynchronizeLists() call, is equivalent to the if check in the earlier example, only much, much hairier. I implemented this logic for ListChangedEvent this time, but what if later I want to hook up a weak listener of some other delegate type? Copy and paste city. Not good.

    What I really want is a helper function that will give a listener that I can use to intercept and filter a call to a delegate without having to know the signature of that delegate. This would allow me to write helper functions such as the two described above.

    Unfortunately, this requires some pretty hairy code generation, so I'm going to skip posting the actual results for fear of scaring people off. For the purposes of the rest of this post, assume that I have access to these functions:


    public static TDelegateType Wrap<TDelegateType>(Func<TDelegateType> action)
        where TDelegateType : class
    {
        return Wrap<TDelegateType>(action, null);
    }

    public static TDelegateType Wrap<TDelegateType>(Func<TDelegateType> action, Action afterAction)
        where TDelegateType : class
    {
        return DoIckyCodeGenerationWork(action, afterAction);
    }

    If I were to implement Wrap<Action<bool>>() statically, it might look like this:

    public static Action<bool> Wrap(Func<Action<bool>> action, Action afterAction)
    {
        return delegate(bool b)
        {
            Action<bool> realAction = action();

            if (realAction != null)
            {
                realAction(b);

                if (afterAction != null)
                {
                    afterAction();
                }
            }
        };
    }

    The basic idea is that it takes a function which returns a delegate of the appropriate signature, and a function that should be called after the pass-through has occurred. If the first function returns null, then no further action is taken.

    Given these helper functions, our original scenario can be implemented in a generic fashion like so:

    public static T Ignorable(this T action) where T : class
    {
        return Wrap(() => action);
    }

    Now I'm free to do things like...

    action.Ignorable()();

    If action is null, Ignorable() will still return a value, and when I invoke that value, it'll do nothing because the first parameter to Wrap() will return null. I can now also implement the more interesting second scenario, like so:

    public static U GetWeakListener<T, U>(this T weakTarget, Action<U> unsubscribe,
        Func<T, U> listener)
        where T : class
        where U : class
    {
        WeakReference<T> weakReference = new WeakReference<T>(weakTarget);

        weakTarget = null;

        U realListener = null;
        realListener = DelegateHelpers.Wrap<U>(delegate
        {
            weakTarget = weakReference.Target;

            if (weakTarget != null)
            {
                return listener(weakTarget);
            }

            unsubscribe(realListener);
            return null;
        }, () => weakTarget = null);

        return realListener;
    }

    My code to set up a weak listener that synchronizes two bound lists now looks like this:

    public void SetUpWeakBinding(BindingList<int> sourceList, BindingList<int> boundList)
    {
        sourceList.ListChanged += boundList.GetWeakListener(l => sourceList.ListChanged -= l,
            (weakList) => (sender, args) => SynchronizeLists(sourceList, weakList, args));
    }

    Still a bit complicated, of course -- note that the "listener" parameter is actually a function that *returns* the real listener, not the listener itself. The reason for this is that the real listener is likely to need a reference to the weak target, which of course we want to hold onto only as a weak reference. If you were to pass the (sender, args) => ... portion directly, it would end up holding a reference to boundList, which would prevent it from being garbage collected. This is also why the weak target is passed in to that function, because if it referenced boundList directly, then it would never get garbage collected.

    So I finally have a simple way to filter and pre-process delegate calls when I don't have control over the code that invokes them. If anyone is interested in seeing the actual implementation of Wrap(), feel free to request it in the comments.

    February 05

    Software design is hard

    Having celebrated my return to blogging with an almost unmitigated stream of vitriol on the subject of software design, I thought it might be nice to spend a bit of time talking about some techniques I like to employ in order to avoid being the subject of such rants myself. Let me state up-front that I am by no means a certified instructor of software design, and that the following advice is based purely upon my own experience. That said, I hope this will prove helpful to someone.
     

    Techniques

    The hardest part of software design is getting started. Here are some tips and tricks that have served me well in getting past the initial hump quickly.

    Code for Today, Design for Tomorrow
    Don't just sit down and write the first thing that comes to mind, but don't stress out over every scenario you might ever want to handle either. Find the happy middle ground. My process for getting started on a new project generally goes something like this:

    1. Stub out some simple pseudo-code that might solve a problem, if the classes and functions they rely on existed.
    2. Stub out the objects that the pseudo-code relies on.
    3. Return to step 1 and solve a new problem. Repeat until you're able to come up with a few new scenarios in a row that your stubs can handle with little or no modification, or until you can't think of anything else you might want to do with them.

    Note that the emphasis in this process is not on future-proofing or on exhaustively analyzing the full problem space, but on coming up with a good way to get where you want to go. Also note that the focus is on the code that uses the objects you're designing, rather than the objects themselves. A side effect of this is that whenever possible, you should design your interfaces from the outside in, meaning that the first set of objects you design should be the simplest and most outward-facing. You don't want to write the complex inner machinery until you've demonstrated to yourself that the external interface you're working towards will be workable.

    This is actually a recursive process...once you've refined the stubbed-out objects in step 2 based on the requirements that you discover by thinking of problems to solve, you can start adding stubbed-out pseudo-code to the objects themselves, assuming that another set of classes and functions exist, and repeat the entire process until your "pseudo-code" relies entirely on classes and functions that already exist.

    Iterative Complexity
    A good API will have several "views" people can choose to take of it. When you're stubbing out your interfaces, think about who will want to use them, and what sorts of trade-offs between flexibility and simplicity those people will want. I've found that the majority of architectures I've designed expose three levels of complexity:

    1. Superficial: simple objects and helper functions that assist in manipulating them in common ways.
    2. Integrated: when a developer needs to move off the beaten trail a bit, there are more granular objects available that give more flexibility and control.
    3. Extension: when a scenario pops up that the developer didn't think of, there are mechanisms for replacing and extending the default functionality.

    A good example of this phenomenon is an object synchronization framework I wrote recently that's intended to simplify the task of keeping data and views of data from multiple sources in sync. Without focusing too much on the details, the three levels at which one can use this framework are as follows:

    1. Superficial: the vast majority of bindings can be accomplished by calling a simple helper function with a name like BindToProperty() or BindValueToValue().
    2. Integrated: there are a variety of objects one can use directly, such as PropertyAdapter or ViewAdapter.
    3. Extension: there are a variety of objects one can inherit from to provide additional functionality, such as Translator or ValueDomainObjectHolder.

    Understanding that your code will be seen from different perspectives by different people can also be useful when doing your initial design. The stubbed-out pseudo-code from step 1 becomes your superficial layer, the stubbed-out interface and class definitions from step 2 become your integrated layer, and the internal objects resulting from recursing on the whole operation will guide the creation of your extension layer.

    To Thine Own Self Be True
    Before you write a class, know what it represents. Know how it relates to the other classes you've already written, and to the ones you plan to write. Keep a list of these representations and relationships so you don't forget and duplicate something. As much as possible, try to avoid allowing equivalent but incompatible representations of the same information to crop up. If you absolutely must have multiple representations, provide method overloads that accept each representation and convert them to the most centralized. A good example of this would be a method with one overload that accepts a string and one that accepts a TextReader, with the string overload simply creating a StreamReader from the filename and passing that on to the second overload.

    Guidelines

    Techniques and processes are all very well, but what makes a design "clean"? How can I tell if my interfaces are usable? Here are a few guidelines, in no particular order.
     
    Don't Fraternize With the Help
    Helper functions generally take two forms:
    1. Simple boiler-plate functionality that is completely straightforward but would be tedious to include everywhere, or
    2. A complex mess that you would hate to have to write again.

    Either way, they don't belong in the same class as core functionality. Putting them in a static method in a separate class whose name is related to the core class (e.g., Binding and BindingHelper) can help to make clear what functionality is the object's main focus and what is just conveniently-packaged sugar while still maintaining reasonable discoverability. Helper methods especially don't belong on interfaces. Extension methods in C# 3.0 can be extremely helpful here.

    Think About Defaults
    When designing a base class, always think about default behavior. What should the majority of derived classes do? If a method has a reasonable default behavior, make it virtual. If there's no reasonable default and you want to force every implementer to consider what a method should do in their case, make it abstract. If you can't think of any reasonable defaults, make it an interface.

    On the subject of defaults and interfaces, I find that 99% of the interfaces that I write have a reasonable default implementation that 99% of all implementations can inherit from. Remember, interface methods should not be trivially implementable in terms of each other -- if you break this rule (for example, System.ComponentModel.ICustomTypeDescriptor provides both a GetEvents() method that can more or less always be trivially implemented by calling GetEvents(Attribute[]) with null), it becomes even more imperative that you provide a default base class, with virtual implementations of those trivial methods. Nobody likes writing boiler-plate code.

    If You've Got It, Flaunt It
    Avoid internal virtual or abstract methods at all costs. If you think a method should be virtual or abstract, don't make it internal. Classes that look like extensibility points but whose overridable members are internal make a mockery of extensibility. WPF's TriggerBase class is a great example of this.

    Each of these guidelines represents a question that you can ask yourself about your code. "Is this class focused on its core functionality?" "Does the design of this class or interface force people to think about things they shouldn't have to?" "Have I abstracted the guts of my abstract base classes sufficiently that they can actually act as base classes that can be meaningfully extended?" If the answer to any of these questions is no, I suggest that you spend some time figuring out how to change that answer.

    February 04

    Save a WPF document to an arbitrary format? Yes, please!

    I haven't posted here for a while, but today I was thinking, "You know what would be a great way to get back into blogging? A bitter, angry rant about spotty software design," so here we are. Last night I was working on a little side project in an effort to get to know WPF (Windows Presentation Framework, formerly code-named Avalon) a little better, when I found that I had a need to generate a document to report some data that my application had gathered. No problem...drop a FlowDocumentScrollViewer into my window's XAML file, generate a visual tree for it using the very intuitive System.Windows.Documents namespace, and I'm off to the races. My simple test document is displaying dynamically-generated content beautifully.
     
    Unfortunately, displaying that document in this application isn't much use...I would like to be able to send it to friends and post it online, but many people don't have .NET 3.5 installed on their machines, for reasons varying from perfectly good ones like a basic distrust of recently-released software, to less understandable ones like sheer laziness, to downright ridiculous reasons such as owning and operating a Mac. The bottom line is, I need to save this thing out to a more universal format than XAML if I want anyone other than myself to see it.
     
    A quick search on MSDN reveals the existence of the SerializerProvider, a handy little object capable of returning an extensible list of registered objects that know how to save WPF object graphs into arbitrary formats such as, according to the documentation, "HTML, RTF, XML, XPS, or alternately to a third-party format." This sounds great! A little bit of data-binding later, I had a context menu that would show me the list of these marvelous serializers that would give my application so much flexibility so easily. I click on the button and...one option appears. XPS. If you're wondering, XPS -- XML Paper Specification -- is the native printer format of Vista. It is not a widely-used document format. A more careful reading of the MSDN article reveals that they never claim that any of those formats actually work -- only that they could be implemented using this wonderfully flexible serialization framework they've put together.
     
    Let's examine this "framework" for a moment, shall we?
     
    Let me just say it up-front: this framework is not good. I think I see why only the absolute bare minimum functionality is provided out of the box...this thing is painful to work with. Implementing ISerializerFactory is quick and painless -- it's just some meta-data properties like the name of your serializer and the default extension for the files you plan to write with it, and a CreateSerializerWriter() method that takes the Stream the user plans to write to and serves as the application's portal into the wonderful world of document serialization and storage.
     
    At the application level, the developer simply creates an instance of SerializerProvider, chooses a SerializerDescriptor from the InstalledSerializers list, and then passes the chosen descriptor to SerializerProvider.CreateSerializerWriter(), which takes the target Stream. So far, so good.
     
    But where does the magic happen? How does the SerializerWriter actually work? Here's where things start to go to pot.
     
    SerializerWriter is an abstract class with 37 members...all of them abstract.
     
    You read that right. The document serialization "mechanism" in WPF will provide you with a list of objects that can be used to serialize documents and some basic metadata about them, but provides absolutely no help whatsoever in the actual serialization process.
     
    Let's examine these 37 methods. Four of them are actually events (abstract events!? Really?), one of them is CancelAsync() -- yes, the developer of each SerializerWriter is expected to implement cancelling and asynchronous operations themselves; more on that later -- and two more are overloads of a function called CreateVisualsCollator(), which is apparently supposed to be overridden in a derived class to return an object "that writes collated Visual elements." I have no idea what this means and MSDN isn't very helpful, so let's turn our attention to the remaining thirty.
     
    Here are six of them:
     
            public abstract void Write(FixedDocument fixedDocument, PrintTicket printTicket);
      
            public abstract void Write(FixedDocument fixedDocument);
      
            public abstract void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket, object userState);
      
            public abstract void WriteAsync(FixedDocument fixedDocument, object userState);
      
            public abstract void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket);
      
            public abstract void WriteAsync(FixedDocument fixedDocument);
     
    Look carefully...notice a pattern? Yes, the remaining thirty abstract members of SerializerWriter are actually five methods, repeated six times each. If you need to take a moment to read that sentence again, feel free. I can wait. Let it sink in.
     
    The pattern above is repeated for FixedDocumentSequence, FixedPage, DocumentPaginator and Visual, and five of those six method overloads are trivially implementable by calling the Write() overload that takes a PrintTicket (the WriteAsync() methods can easily be implemented by using the BeginInvoke() mechanism exposed by all delegates). Furthermore, FixedDocument, FixedDocumentSequence and FixedPage all expose a single DocumentPaginator object, so as far as I can tell, it's perfectly reasonable to provide default implementations of those three that simply call the DocumentPaginator overload. That said, DocumentPaginator can also be reasonably straightforwardly converted into a stream of Visuals. In other words, it's not completely unreasonable to say that all 29 of these 30 abstract methods can be reasonably implemented by calling the remaining method.
     
    This sort of thing really burns my biscuits, a phrase which here means "makes me want to strangle someone." Sorry, I just finished the last chapter of A Series of Unfortunate Events.
     
    In short, this mechanism consists of a thin wrapper around a set of registry keys, and a class with a ridiculous amount of abstract methods and literally zero built-in functionality. They haven't even given us convenient wrapper methods for firing the events so we don't have to check them for null first.
     
    Am I missing something? All in all, I'm extremely disappointed with this feature. Also, MSDN talks about "document serialization and storage," and "storage" seems to imply that it can read documents back from these arbitrary formats into WPF documents -- unless they mean "storage" in the sense of sticking it into a box and never looking at it again -- but I can't find any actual evidence of such functionality, not even a stubbed-out class to provide a common interface to it like SerializerWriter.
     
    I'm writing this in the hope that someone who worked on this feature will see this and feel compelled to respond, and maybe explain why this isn't as bad as it seems. Because from here, it looks pretty bad. If that happens, please be assured that if you can convince me that this is the right design, or even not an abysmally terrible design, I'll post an immediate retraction. I just want to know what happened.
     
    I want to love you, WPF, I really do, and when I'm working with dynamic styling and templating, or when I data-bind a tree and then decide it would make more sense as a menu item, I do love you; but then you pull out something like this, or you make all the useful methods on TriggerBase, TriggerAction and Expression internal for no apparent reason, or you throw an exception when I try to create a KeyGesture that consists of a letter key and no modifiers (so I can do things like Visual Studio's Ctrl-K, F command). Why won't you let me love you?
    October 28

    "Fun" with WCF proxy generation

    If you're anything like me, you hate typing something in one place and then having to go type it again somewhere else. If you're more than a little like me, you've been using WCF to write service-enabled applications and you've been frustrated by the tools at your disposal to do so. I'm using VS 2005 with the WCF extensions at work and I've seen only two points of IDE integration for working with WCF: Add Service Reference, and Edit WCF Configuration.

    The concept of service references makes a lot of sense, but the implementation in the VS 2005 extensions is completely useless if you're authoring your own application, because it requires you to run your service application live when refreshing the service reference, which isn't very practical for automated build systems. Running my server application so that I can update the service reference on my client gets tedious after a while. The VS 2008 beta 2 has an intriguing "Find services in this solution" button on the Add Service Reference dialog, but I haven't been able to get it to do anything. Maybe once this button is implemented, the trick I'm about to describe will become unnecessary.

    The Edit WCF Configuration is great for editing service configurations, and it's useful for creating client configuration files as well -- but again, it's a manual process that's not easy to automate. Manual processes are fine for personal projects, but not so fine for projects at work where co-workers and automated build servers need to be able to update things.

    The biggest problem that I've been having is that svcutil.exe doesn't seem to use the configuration information when you run it against a service executable, and I just couldn't figure it out. It would just make up some HTTP endpoints instead of using the ones configured for the service. However, while scouring the svcutil.exe documentation, I finally stumbled upon the "/serviceName" option. Aha! A quick test reveals that it gives me exactly what I want: server code and a fully-functional client configuration that doesn't need to be touched manually at all. But I couldn't stop there...I want this properly integrated into MSBuild.

    Six hours later, out pops Ceiled.WCF.targets:

    <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <CoreCompileDependsOn>$(CoreCompileDependsOn);BuildServiceReferences</CoreCompileDependsOn>
      </PropertyGroup>
      <Target Name="BuildServiceReferenceProjects">
        <MSBuild Projects="@(ServiceReference)" />
        <MSBuild Projects="@(ServiceReference)" Targets="GetTargetPath">
          <Output ItemName="ServiceReferencePaths" TaskParameter="TargetOutputs" />
        </MSBuild>
      </Target>
      <Target Name="GenerateServiceReferences" Inputs="@(AppConfigWithTargetPath);@(ServiceReference)" Outputs="$(IntermediateOutputPath)Services\%(ServiceReference.Name)\Services.txt">
        <Warning Text="$(FinalAppConfigLocation)" />
        <CallTarget Targets="ForceConfigFile" />
        <Warning Text="$(FinalAppConfigLocation)" />
        <CreateProperty Value="@(ReferencePath->'%(FullPath)', '&quot; &quot;/reference:')">
          <Output PropertyName="ServiceReferenceCommandLine" TaskParameter="Value" />
        </CreateProperty>
        <CreateProperty Value="@(ServiceReference->'%(Namespace)', '&quot; &quot;/namespace:')">
          <Output PropertyName="ServiceReferenceNamespace" TaskParameter="Value" />
        </CreateProperty>
        <RemoveDir Directories="$(IntermediateOutputPath)Services\%(ServiceReference.Name)" />
        <MakeDir Directories="$(IntermediateOutputPath)Services\%(ServiceReference.Name)" />
        <WriteLinesToFile File="$(IntermediateOutputPath)Services\%(ServiceReference.Name)\Services.txt" Lines="%(ServiceReference.ServiceNames)" />
        <Exec Command="for /f %%i in ($(IntermediateOutputPath)Services\%(ServiceReference.Name)\Services.txt) do &quot;c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\svcutil&quot; &quot;@(ServiceReferencePaths)&quot; &quot;/namespace:$(ServiceReferenceNamespace)&quot; /directory:$(IntermediateOutputPath)Services\%(ServiceReference.Name)\%%i &quot;/reference:$(ServiceReferenceCommandLine)&quot; /serviceName:%%i" />

        <Exec WorkingDirectory="$(IntermediateOutputPath)Services\%(ServiceReference.Name)" Command="for /f %%i in (Services.txt) do &quot;c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\svcutil&quot; %%i\*.wsdl %%i\*.xsd /out:%%i.cs &quot;/config:$(ProjectDir)\@(AppConfigWithTargetPath->'$(OutDir)%(TargetPath)')&quot; /mergeConfig" />
        <ItemGroup>
          <ServiceReferenceItemsToCache Include="%(ServiceReference.ServiceNames)">
            <ServiceLibraryName>%(ServiceReference.Name)</ServiceLibraryName>
          </ServiceReferenceItemsToCache>
        </ItemGroup>
      </Target>
      <Target Name="DoBuildServiceReferences" DependsOnTargets="BuildServiceReferenceProjects;GenerateServiceReferences" Inputs="@(ServiceReference)" Outputs="%(Name)">
        <CreateItem Include="@(ServiceReferenceItemsToCache->'$(IntermediateOutputPath)Services\%(ServiceLibraryName)\%(Identity).cs')">
          <Output ItemName="Compile" TaskParameter="Include" />
        </CreateItem>
      </Target>
      <Target Name="ForceConfigFile" Condition="'$(AlreadyForcedConfigFile)' == ''">
        <Touch Files="@(AppConfigWithTargetPath)" />
        <CallTarget Targets="_CopyAppConfigFile">
          <Output ItemName="FinalAppConfigLocation" TaskParameter="TargetOutputs" />
        </CallTarget>
        <CreateProperty Value="true">
          <Output PropertyName="AlreadyForcedConfigFile" TaskParameter="Value" />
        </CreateProperty>
      </Target>
      <Target Name="BuildServiceReferences" DependsOnTargets="DoBuildServiceReferences">
      </Target>
    </Project>

    Honestly, I had to jump through so many hoops and pull out so many tricks while writing this that the very thought of explaining it makes me tired, so I'm just going to post it here in all its glory and if anyone's interested, they can leave a comment and I'll make an effort to explain it. You use it by including something like this in your project:

      <ItemGroup>
        <ServiceReference Include="..\WCFTest\WCFTest.csproj">
          <Project>{CD764F3F-7BA7-4E0E-B64E-A78D2C707855}</Project>
          <Name>WCFTest</Name>
          <ServiceNames>WCFTest.ChatService</ServiceNames>
          <Namespace>WCFTest,*</Namespace>
        </ServiceReference>
      </ItemGroup>

    I did this by simply adding a ProjectReference to the project containing my services and then changing it to a ServiceReference item...the Project GUID is a by-product of that, and isn't actually used. ServiceNames is a semi-colon-delimited list of the service configuration entries that you want to generate proxies for, and Namespace is a semi-colon-delimited list of CLR-to-XML namespaces mappings, as described in svcutil.exe's documentation. The client configuration data will be generated in the config file that ends up being copied to your bin folder, not to the one that you edit manually...this is to prevent endpoints from piling up on top of each other, since svcutil.exe always adds new ones instead of seeing that it's creating duplicates...so if you want to see the configuration, you'll have to look in bin\Debug. The only bug I know of is that it doesn't regenerate the proxies when the service project needs rebuilding -- it does when the client's app.config file changes though, so there's a reasonable work-around (touching the app.config file) until I figure out how to tell whether the referenced project built. If I get that worked out, I'll post an update here. Meanwhile, hopefully this will be useful to someone.

    May 31

    Debug like it's 1899

    I have been asked by a number of new programmers to recommend books for someone trying to get started. Several authors and publishers spring to mind when searching for a definitive guide on a particular aspect of software development: the Gang of Four, Charles Petzold, O'Reilly, Microsoft Press -- these are the obvious sources, prolific fonts of information with which even the most voracious programmer should be well satisfied. However, Sir Arthur Conan Doyle never seems to come up in this context, and for the life of me I can not understand why.
     
    From my lofty place on page 984 (out of 1,122) of The Complete Sherlock Holmes, one thing is very clear: if Sherlock Holmes were alive today (or, you know, ever), he would quite possibly be the most formidable debugger in history.
     
    Holmes once said that when one has eliminated the impossible, whatever is left must be the truth, no matter how unlikely it may seem (although interestingly enough, he never said "Elementary, my dear Watson"). He never dismisses the facts as impossible, and he never conjectures based on information he does not have. In addition to all these philosophies, he possesses an encyclopedic knowledge of his environment and the practices of his time that he employs to great effect, whether he's deducing that a suspect was recently near the scene of the crime by the colour and pattern of the mud splattered on his trouser leg or that the wife of a man he has never met had ceased to love him by the condition of his hat.
     
    How often have you noticed a minor detail in how the subject of a debugging session was broken and dismissed it as random weirdness, only to realize what caused it after you've finally solved the problem? When Holmes sees a fact that he can't explain, he focuses on it and investigates it until he can, and his final solution is often based primarily on information that Watson or Lestrade had dismissed when it first came to light as a minor oddity. In fact, the more inexplicable a fact is, the more he tends to emphasize it because he sees the inexplicable parts of an investigation as the ones that set it apart from others in the past.
     
    To sum up, if one were to ask Sherlock how you can learn to debug like he does, he might have this to say:
      1. Never dismiss an indisputable fact as "just plain weird"
      2. Know your domain
      3. Never underestimate the value of seemingly inconsequential details
      4. Confirm your assumptions as early and often as you can, and don't draw conclusions based on unconfirmed assumptions
      5. Read my books
     
    If you ask me, you'd do well to listen to him.
    May 18

    Duplicate and tweak an XML file using XSL

    I enjoy asking about XSL when I'm interviewing a candidate, mostly because I've noticed that it's one of those things that people tend to list under their "Expertise in" section without really knowing much about it, but partly because we're actually using it on some of the projects we're interviewing for (by the way, if you're in the Redmond area and are looking for a web or game development job, drop me a line!). When I ask what XSL is, the most common answer is that it can be used to transform data into HTML. This answer is correct, but not very complete -- in fact, XSL transforms from one XML format to another.
     
    This distinction is more important than it sounds: the target XML format can be another data format, or the source format can be a display-oriented mark-up format like HTML. Transforming from one data format to another is pretty obvious, but transforming one mark-up format into another is a bit less obvious. Imagine that you're authoring some sort of document in HTML, let's say an article for a web site. Then imagine that many articles on this site have common pieces that need to appear in many places -- if you happened to be working for Nintendo on the official Pokémon website, for example, you would probably want to have an easy way for authors of articles to embed pictures and informational links of and to the various Pokémon they're talking about to jazz up their articles. This is a perfect application of an XSL technique I came up with in college.
     
    First, we need an XSL stylesheet that will simply copy the source document into the destination document. This is the tricky part, and here's one implementation of ProcessDocument.xsl:
     
    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      
      <xsl:template match="*">
        <xsl:element name="{name()}" namespace="{namespace-uri()}">
          <xsl:apply-templates mode="contents" select="." />
        </xsl:element>
      </xsl:template>
     
      <xsl:template match="*" mode="contents">
        <xsl:apply-templates select="*|@*|text()" />
      </xsl:template>
     
      <xsl:template match="@*">
        <xsl:attribute name="{name()}" namespace="{namespace-uri()}">
          <xsl:value-of select="." />
        </xsl:attribute>
      </xsl:template>
     
      <xsl:template match="text()">
        <xsl:value-of select="." />
      </xsl:template>
    </xsl:stylesheet>
     
    Essentially, what this stylesheet is saying is, "Whenever you see any element, create an element with the same name and namespace as the source, then apply the 'contents' template to it. Whenever you're asked to apply the 'contents' template, apply templates to the current node's children, attributes and text. Whenever you see any attribute, create an attribute on the node you're currently outputting with the same name, namespace and value, and whenever you see a text node, just copy it verbatim."
     
    Now that we've got the foundation laid, we need to specialize it for our domain. Let's say that our article format looks something like this:
     
    <article>
      <title>Meet Pikachu</title>
      <author>Ryan Milligan</author>
      <body>
        <pokemon style="float:right;">25</pokemon>
        You should really try putting Pikachu in your party.
      </body>
    </article>
     
    If you're wondering about the "25", that's because the only online database of Pokemon images I was able to find (http://www.pokemonvillage.com/pokemon.asp) indexes them by number instead of by name, and Pikachu is #25.
     
    What we have here is a data format that includes blocks of formatting mark-up, so we're going to combine the classic XSL pattern (a root template that establishes an HTML document and then defers to templates to format different parts of the document) with the technique encapsulated in ProcessDocument.xsl of duplicating existing nodes. Here's what the initial version of our template might look like:
     
    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:import href="ProcessDocument.xsl" />
      <xsl:template match="/article">
        <html>
          <body>
            <h1>
              <xsl:apply-templates select="title" mode="contents" />
            </h1>
            <div>
              <i>
                By: <xsl:value-of select="author" />
              </i>
            </div>
            <div>
              <xsl:apply-templates select="body" mode="contents" />
            </div>
          </body>
        </html>
      </xsl:template>
    </xsl:stylesheet>
     
    All this is doing is outputting an HTML body with some initial formatting -- a header element for the title, the author's name in italics, and the body of the article itself. Because we're calling the "contents" template defined in ProcessDocument.xsl for the title and body, we're going to get a copy of all the contents of those elements. But we don't really want an exact copy -- I don't know of any browsers that know how to display a <pokemon> element. Let's add this template:
     
      <xsl:template match="pokemon">
        <a href="http://www.pokemonvillage.com/pokemon.asp?command=Show+Me!&amp;number={text()}">
          <xsl:apply-templates select="@*" />
          <img src="http://www.pokemonvillage.com/pokedex/{format-number(text(), '000')}.jpg" />
        </a>
      </xsl:template>
     
    Now we run our template, and we get this:
     
    <html>
      <body>
        <h1>Meet Pikachu</h1>
        <div>
            <i>By: Ryan Milligan</i>
        </div>
        <span>
            <a href="http://www.pokemonvillage.com/pokemon.asp?command=Show+Me!&amp;number=25" style="float:right;"><img src="http://www.pokemonvillage.com/pokedex/025.jpg"></a>
            You should really try putting Pikachu in your party.
        </span>
      </body>
    </html>
     
    Perfect! This technique makes it almost absurdly easy to just dip your toe into a document and change only the things you want to change. Enjoy!
    May 12

    Exception filters

    As commented by Jeremy, the answer to yesterday's question is exception filters. I don't plan to focus on security here, so I'll defer the full explanation of the security implications to Shawn. For the purposes of our discussion here, it's enough to know that when an exception is thrown in .NET, the system makes two passes in order to handle this exception. First, it walks from down the call stack from where the exception was thrown, executing exception filters to determine if anyone wants to catch this exception.
     
    This is done so that debuggers can properly distinguish between caught and uncaught exceptions before the call stack has been unwound. After it figures out which frames are willing to handle the exception, it unwinds the call stack, executing all finally blocks and any catch blocks whose filters returned true along the way. The problem is, this means that if a caller can manipulate highly-trusted code into throwing an exception, it can inject some logic before the highly-trusted code's finally block gets run.
     
    The whole thing is made more subtle by the fact that custom filter expressions aren't supported in C#, but they are in VB and .NET in general. Because of this, it's reasonable to assume that even the most astute C# developers may not be aware of this situation.
     
    I find this distinction between C# and VB very interesting. Typically, between the two, C# leans more towards giving developers control over their code, and VB leans more towards simplicity; but in this case, the reverse is true. Why doesn't C# support exception filters? And why does neither provide a simple way to run cleanup code before the caller's exception filters? My guess is for the sake of simplicity, which brings me to the reason I brought this subject up in the first place.
     
    I have always held the firm belief that languages should be designed to maximize developer control and flexibility. I don't believe in withholding power from developers for fear that they might shoot themselves in the foot with it. This is why my compiler can build this code:

            static void Foo()
            {
                try
                {
                    throw new ArgumentException("Fred", "Fred");
                }
                first
                {
                    Console.WriteLine("Foo.First");
                }
            }
            static void Main(string[] args)
            {
                try
                {
                    Foo();
                }
                first
                {
                    Console.WriteLine("First!");
                }
                catch (ArgumentException e) when (String.Equals(e.ParamName, "Fred"))
                {
                    Console.WriteLine("Darn it, Fred!");
                }
                finally
                {
                    Console.WriteLine("Finally!");
                }
            }
     
    Here's the output of this program:
        Foo.First
        First!
        Darn it, Fred!
        Finally!
     
    Two important things here:
        1. If I change the parameter name of the exception to something other than "Fred", not only does the code in my catch block not execute, but the debugger will spot it as an uncaught exception and break if it's been told to. This sort of practice can be useful when working with functions that wrap many kinds of problems in the same type (I'm looking at you, SQL, file systems, reflection and P\Invoke).
        2. Note the "first" blocks. This block is guaranteed to run before anything else in the exception handling chain, including your callers' exception filters, so it's safe to put security-sensitive cleanup in there.
     
    Is this a useful construct? I think it is. Does it add more complexity than it's worth to the familiar try\catch\finally block? I don't think so -- but if you think it does, feel free not to use it. This is the power of iterative complexity, and it's the underlying premise of my philosophy towards language design: if you don't like it, don't use it. The only added complexity I object to is complexity that the user is forced to deal with.
    May 11

    The trouble with try\finally

    Here's a little exercise for the programmers out there. Consider the following C# code:
     
    public void PerformAdminTask(AdminTaskInput input)
    {
        ImpersonateAdministrator();
        try
        {
            PerformHighlyTrustedAdminTask(input);
        }
        finally
        {
            StopImpersonatingAdministrator();
        }
    }
     
    Now, in real life, you should use Code Access Security (CAS) to do this, which modifies the entire method call and therefore dodges the whole issue. However, for the sake of argument, can you spot how untrusted callers calling this highly-trusted code can run their own logic on the current thread while the administrator is still being impersonated? If anyone actually reads this before I get home today, post your answers in the comments -- answer forthcoming when I get back from OGDC.
    May 06

    Explicit, clear or terse: choose two

    Those of you who have ever planned a project cycle may be familiar with the Project Triangle: fast, cheap or good; choose any two. The same concept can be applied to the design of programming languages, with regards to explicitness, clarity and terseness.

    First, some definitions:

    1. Explicit: constructs are relatively independent and impacted very little by changes outside their own scope. Once you've understood what the average line says, you can be confident that it's doing exactly what you expect.
    2. Clear: constructs are distinctive and not easily confused with each other. The average line of code can be easily read by a human being.
    3. Terse: constructs require relatively little "air" to be expressed. Each symbol in the language carries specific information that the compiler requires in order to interpret the construct.

    In general, designing a language is an exercise in making trade-offs between these three ideals. C++, for example, is very terse, but only moderately clear and explicit (try putting printf()s in the constructor, destructor and copy constructor of a few objects in your code and see if what comes out is what you'd expect from reading the code). Visual Basic, on the other hand, is clear and (when using Option Strict and Option Explicit, which should always be on in my opinion) explicit. C# is mostly explicit and terse. This is the root of why Microsoft works so hard to support all three languages in .NET: between the three, most anyone can find something to their taste, because together they make a nice mix.

    As most people likely to read this may already be aware, I've been spending a fair amount of my spare time for the last couple years building an extensible, object-oriented version of the C# compiler. The purpose of this compiler is mostly to allow me to play with language constructs as they strike my fancy, and partly as an experiment to see how far I can stretch the Coding Triangle, as I'm going to call it (if anyone knows of a real name for this, please let me know!). The post before this, Or If, is a discussion of a potential feature for this compiler, likely the first of many in this space.

    Personally, I'm in the explicit and terse camp, hence my predilection for C#. I've spent too much time debugging non-explicit VB code to want to make trade-offs in explicitness, and too much time wading through thousand-line files full of air to want to sacrifice terseness. On the other hand, I've also spent a lot of time digging through obfuscated Perl -- terseness can be abused!

    If I had to prioritize, I'd probably do it like this:

    • 50%: Explicit
    • 30%: Terse
    • 20%: Clear

    There are going to be people who will disagree with this balance, and that's fine. You guys can go write your own compiler, and more power to you. If you're wondering exactly what that 10% gap between terse and clear means, it basically means I'd rather have short identifiers and keywords than long ones and curly braces than "Begin...End" type blocks. It doesn't mean I want to be able to use "f" instead of "for" to save on keystrokes.

    As an example, here's something I mentioned in Or If and promised to explain in more detail later:

    switch (myVariable)
    {
        case 0:
            Console.WriteLine("Zero!");
            fallthrough;

        case 1:
            Console.WriteLine("One!");
            break;
    }

    Switch statements are one place where I really feel like C# missed the boat on making the right trade-offs. Missing break statements are a big problem in languages with implicit fallthrough, I don't dispute that. I also don't dispute that the vast majority of the time, it's not what you want. So how do you prevent people from accidentally forgetting to type something? You make it not work unless they type something. Instead of having fallthrough be implicit (ugh), requiring a reiteration of another case variable ("goto 1" in the above case, which is C#'s solution -- double ugh) or removing it entirely, just make it explicit.

    When I was in fourth grade, I carved a pumpkin in class for Halloween. Despite my Boy Scout training, I managed to close my pocket knife on my fingers and cut myself. It hurt a lot, but the experience didn't make me want to lobby against pocket knives and prevent others from using them. I just exercise a lot more caution when I'm using them myself, I tell people about it when they don't seem to be showing a knife the respect it deserves, and I only use lock-blade types. Programming should be the same way...don't take the blade away, just add a lock so the knife doesn't close unless the user really wants it to.

    The most common question I'm asked when I tell people about this project is, "why?" Now I can just point them here...I love modern technology.

    Or if

    Recently I was working on something, and I found myself using a construct that looked like this:
     
    if (ConditionA)
    {
        DoSomething();
     
        DoSomethingElse();
    }
    if (ConditionB)
    {
        DoSomethingElse();
    }
     
    Now, the real intention of this code was that that DoSomething() should be run if ConditionA was met, and DoSomethingElse() should be run if either ConditionA or ConditionB was met. There are two things I don't like about this code: DoSomethingElse() needs to be specified twice, and it doesn't clearly communicate the intent. I feel like there must be a better way to do this. So far, I've come up with two syntaxes that could accomplish this in what I think is a fairly clear fashion. My first instinct was this:
     
    if (ConditionA)
    {
        DoSomething();
    }
    or if (ConditionB)
    {
        DoSomethingElse();
    }
     
    I like that this is a nice, orthogonal extension of existing syntax. I also like that it eliminates the duplication from the original construct and doesn't require any extra code. I don't like that it doesn't clearly communicate the relationship between the two blocks. My second idea addresses this:
     
    switch
    {
        case ConditionA:
            DoSomething();
            fallthrough;
     
        case ConditionB:
            DoSomethingElse();
    }
     
    The basic idea of this one is that a switch statement with no expression would interpret its case labels as expressions instead of simple labels, and would jump to the first one to evaluate as true. Then you can use fallthrough (note the explicit fallthrough statement, which is another wishlist item of mine -- perhaps I'll explain the thinking behind it in a future post) to execute both statements if both are true or just the second one if the second one is true. This solution eliminates the duplication and adds only a couple lines of code, but I can't decide which is a bigger departure from the expectations set by C#: executing more than one in a series of if blocks, or interpreting case statements as expressions. Any thoughts?
    April 29

    Typing of the Dead 2!

    I can't believe they're actually making it! The original game is a blast, and I attribute a fair amount of my typing speed to it. I even got a little competitive about it with one of my friends.
     
    I sincerely hope the sequel gets an English release -- I'll even forgive the lack of keyboards strapped to the characters' chests for the chance to play that game again with new scenarios and words, and a graphical update. I'm also praying that they still have the drills, which are mentioned nowhere that I can find, and are my favourite part of the original. Keep your fingers crossed!
    April 27

    Handy Visual Studio tips

    People who see me work often ask me how I'm able to fly so quickly through my daily tasks, and the answer is invariably "keyboard shortcuts." The next question, of course, is "what keyboard shortcuts should I know?" Well, having answered that question many times at this point, I think it's finally time to document the answer here so I can just point people to it in the future. Note that while many of these shortcuts also apply to VS 2003 and 2002, I am referring specifically to 2005.
     
    General navigation
    VS 2005 is almost shockingly keyboard navigable -- not only can you access all the common windows quickly, but most of them can also be navigated and used, if sometimes somewhat awkwardly (I'm looking at you, Toolbox -- why can't I type part of the name of the entry that I want to jump straight to it?), with the keyboard as well. Generally speaking:
    • Move around: Arrow keys
    • Activate Selection: Enter (open a file in the Solution Explorer, switch to an entry in the Threads window, etc)
    • Label Edit: F2 (modify an expression in the Watch window, rename a file in the Solution Explorer, etc)
    • "Mini" Activate Selection: Space (enable or disable a breakpoint, refresh an expression in the Watch window, etc) 
    Another useful tool is the Application key -- you know, the one next to the right-hand Windows key on your keyboard -- which will bring up the context menu as if you had right-clicked wherever your selection is. I estimate that this key alone saves me about an hour a day in time spent switching my hand from the keyboard to the mouse. I mention this because I'm often shocked by how few people know about this incredibly handy little key.
     
    Speaking of being shocked by how few people know of what is to me an ubiquitous tool, the ctrl-tab window in VS 2005 is not to be scoffed at. If you've never hit ctrl-tab while working in Visual Studio, give it a try. Go ahead, I'll wait. You can move forwards and backwards through your open documents (in the order in which you last visited them) by continuing to hold down ctrl and pressing tab and shift-tab, respectively. You can also move around a bit more freely with the arrow keys, which will also allow you access to your open tool windows in case you haven't yet gotten around to memorizing the list below. You can also click directly in the ctrl-tab window with your mouse, if you're into that kind of thing.
     
    If you see anything in the following lists that you don't think you've seen before, I encourage you to hit the buttons and check it out. Poke around, right-click (or hit the application key if you think you're cool enough) and see what options come up. If you still don't know what you're looking at, hit F1 -- it's worth the time to get to know your environment. You can't use a tool that you don't know exists! Did you know that in .NET, you can always get the full managed call stack at any time, even if you don't have code or symbols for part of it? You would, if you right-clicked on the Call Stack and saw the "Show External Code" option, which is turned off by default if Just My Code is enabled (if it's not enabled, this option won't even show up and you'll always see full call stacks). Spending a bit of time right-clicking on everything and getting a feel for what options are available can save you a lot of time when it counts.
     
    General Code Navigation
    • Go To Line: Ctrl-G
    • Incremental Search: Ctrl-I (after entering this shortcut, start typing and see what happens)
    • Match Selected Brace: Ctrl-]
    • Format Document: Ctrl-K, D
    • Format Selection: Ctrl-K, F
    • Expand\Collapse Outline Region: Ctrl-M, M
    • Collapse To Definitions: Ctrl-M, O
    • Expand\Collapse All Outlines: Ctrl-M, L
    • View IntelliSense: Ctrl-space
    • View Method Signature (when inside the parentheses of a method invocation): Ctrl-shift-space
    • Open Smart Tag: Alt-Shift-F10 (I like to remap this to ctrl-alt-shift-space)
    General Window shortcuts
    Here are just a few shortcuts that will jump you to the tool window of your choice:
    • Solution Explorer: Ctrl-alt-L
    • Toolbox: Ctrl-alt-X
    • Server Explorer: Ctrl-alt-S
    • Class View: Ctrl-alt-C
    • Output: Ctrl-alt-O
    • Immediate: Ctrl-alt-I
    • Exceptions: Ctrl-alt-E
    • Command: Ctrl-alt-A
    • Document Outline: Ctrl-alt-T
    • Error List: Ctrl-\, E
    • Code Definition: Ctrl-\, D
    • Task List: Ctrl-\, T

    Debugging Shortcuts
    Debugging should be quick, powerful and intuitive, and it can be if you learn a few simple key strokes:

    • Run in Debugger: F5
    • Run Without Debugging: Ctrl-F5
    • Stop Debugging: Shift-F5
    • Step Over: F10
    • Step In: F11
    • Step Out: Shift-F11
    • Run to Cursor: Ctrl-F10
    • Set Next Statement: Ctrl-shift-F10
    • Toggle Breakpoint: F9
    • Enable\Disable Breakpoint: Ctrl-F9
    • Quick Watch: Shift-F9

    Debugging isn't all about stepping through code, though. Sometimes you want to actually see what's going on, and these windows can help you with that:

    • Watch Window: Ctrl-alt-W, {X}, where {X} is a number from 1 to 4.
    • Call Stack: Ctrl-alt-C
    • Threads: Ctrl-alt-H
    • Modules: Ctrl-alt-U
    • Breakpoints: Ctrl-alt-B
    • Locals: Ctrl-alt-V, L (no, I don't know why this one's completely different from all the others)

    Code snippets
    Code snippets are one of my favourite new features in VS2005, along with smart tags (more on that in a bit). If you've ever been typing "property" and wondered what that "prop" entry that shows up in IntelliSense is, it's a code snippet. Type "prop" and press tab twice (once to dismiss the IntelliSense and once to activate the snippet) to get a real treat. Press tab to navigate through the highlighted fields that pop up, and enter to finish editing. When you hit enter, the cursor will go somewhere reasonable, depending on the snippet. In the interest of keeping this a "quick reference," I'm not going to go into what each one does -- you can type it in and hit tab to see for yourself -- but here's a list of some useful snippets that ship with VS:

    • prop
    • propg
    • class
    • interface
    • enum
    • ctor
    • ~
    • if
    • else
    • for
    • forr
    • foreach
    • while
    • do
    • try
    • tryf
    • cw

    There are more, but I don't want to spoil your fun. You can get a list of all of them by going to Tools -> Code Snippets Manager or hitting Ctrl-K, B.

    Smart Tags
    Smart tags pop up in many places -- it's the little orangish\reddish bar that occasionally pops up over your code. Create a new VS project and type "MD5" into the body of a function to see an example. If you click on the smart tag (or press alt-shift-F10), you'll get some time-saving options. In the MD5 example above, you'll have the option of either adding "using System.Security.Cryptography" to the top of your file, or fully-qualifying MD5 with the namespace so it will compile. I use this feature constantly, and find it extremely productive. Other uses of smart tags include:

    • On an inherited abstract class: Implement abstract members
    • On an implemented interface: Implement interface explicitly or implicitly
    • On a just-renamed variable, class or member: Perform a refactoring operation to change references to the old name to references to the new name

    Hopefully, someone will stumble on this list and find some useful tool that they didn't know they had access to. If one person adds one new trick to their arsenal as a result of this post, then I'll consider the hour I spent writing it well spent. Happy keyboarding!

    April 26

    Tag! You're it!

    I've thought about starting a blog for some time. A place where I can keep track of my thoughts on ongoing projects, upcoming technologies and other adjective nouns in a public space where people who might be interested in such things might stumble upon them and perhaps be helped in some way is quite appealing. On the other hand, working is not appealing, and posting regularly sounds suspiciously like work.
     
    However, a recent ego-surfing session with one of my roommates led to a Google Images search for my name, which turned up a picture of a former co-worker of mine, Steve Porter. Blinking, I told Brendan (the forementioned roommate) to click on his picture, and discovered that I had been "tagged". Not only did he include a challenge for me to start a blog, but the subject of the tag (five things you didn't know about me) is uniquely suited for an introductory post, so I thought I'd take up that challenge. Only time will tell how far I'll take it.
     
    1. I have been shot in the eye twice (once with a Nerf gun in a particularly nasty office fire fight and once by a bow and arrow) and hit by a thrown knife once.
    2. I never graduated from high school or college.
    3. I have a mental disorder called hyperlexia, which manifests as a fascination with language and grammar, sensitivity to high-pitched noises, and difficulty interpreting social cues.
    4. When I was young, I spent so much time reading that I've been grounded from it twice. That was before I found the internet, of course.
    5. I got my driver's license the day before my 22nd birthday because I wanted to pick my karate lessons up where I'd left off in high school, but found that a twenty mile round trip through hilly downtown Redmond by bike with a one-hour training session in the middle twice a week was a bit harsher than I expected it to be.
     
    On a less random note, I'm a professional programmer, having worked on Visual Studio, The Sims 2 (for PSP), what Steve calls The Project That Shall Remain Nameless (TPTSRN for short) and, currently, a Redmond-based consulting company called SolutionsIQ. If this blog continues, it will likely deal with topics such as .NET and Visual Studio development, any web- or Windows-based technology that happens to catch my eye, homegrown amateur C# compilers and show tunes. Consider yourselves warned or, if you happen to be Brendan Sweeney, Stephanie Tuma, Sarah Shay, Dustin Darcy or Hideki Saito, tagged.