Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Fear and Loathing

Gonzo blogging from the Annie Leibovitz of the software development world.

  • Handling Unhandled Exceptions in XBAP Applications

    In your own applications you'll generally want a "catch-all" handler that will take care of unhandled exceptions. In WinForms apps this is done by creating an unhandled exception delegate and (optionally) creating an AppDomain unhandled exception handler. Peter Bromberg has a good article on all of this here and I wrote about the various options for WinForms apps here.

    With XBAP (XAML Browser Applications) the rules are slightly different so here's one way to do it.

    Take your existing XBAP app (or create a new one) and in the App.xaml.cs file you'll want to create a new event handler for unhandled exceptions. You can do this in the Startup method like so:

            protected override void OnStartup(StartupEventArgs e)

            {

                DispatcherUnhandledException += App_DispatcherUnhandledException;

                base.OnStartup(e);

            }

    In our exception handler, we'll do two things. First we'll set the exception to be handled and then we'll set the content of the MainWindow (a property of the Application class) to be a new exception handler page.

            private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)

            {

                e.Handled = true;

                MainWindow.Content = new ExceptionHandlerPage();

            }

    That's really the basics and works. However you don't have the exception information passing onto the new page. We can do something simple for now. Here's the XAML for a simple error handling page:

    <Page x:Class="XbapExceptionHandlerSpike.ExceptionHandlerPage"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Width="300" Height="300"

        Title="ExceptionHandlerPage">

        <Grid>

            <Grid.RowDefinitions>

                <RowDefinition Height="23" />

                <RowDefinition />

            </Grid.RowDefinitions>

            <TextBlock Margin="10,0,0,0" VerticalAlignment="Center" Grid.Row="0" Text="An exception has occured. Here are the details:" />

            <TextBlock Margin="10,0,0,0" Grid.Row="1" x:Name="ErrorInformation" Foreground="Red" FontFamily="Consolas" TextWrapping="Wrap" />

        </Grid>

    </Page>

    I gave a name to the TextBlock in the second row in the grid. This is the control that will display our error message. I've also styled it and set the font to be a mono-spaced font.

    We can update our creation of the ExceptionHandlerPage class to include the exception details like so:

            private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)

            {

                e.Handled = true;

                var page = new ExceptionHandlerPage

                               {

                                   ErrorInformation = {Text = e.Exception.Message}

                               };

                MainWindow.Content = page;

            }

    Now our page displays the error with the details provided:

    Again, this is really simple and bare-bones. You can get creative with it with things like fancy fonts, dancing bears, floating borders, etc. and passing along the entire Exception (so you might walk through the inner exceptions and details) and even log the exception to your bug tracking system. Jeff Atwood has a great article on creating friendly custom Exception Handlers (one for WinForms here, one for ASP.NET here). A WPF version might be useful.

    As with WPF apps, there are a lot of ways to skin this cat. This is just my take on it. Feel free to offer your own twist.

  • Patterns, Practices, and Prism

    James Kovacs and I had the pleasure of presenting to a well fed crowd of about 150 crazed developers and IT folk at Shaw here in Calgary last night. We did a drive by discussion of Prism. I say drive by because we really just scratched the surface of what Composite Applications are all about (you can only do so much in 40 minutes on the subject) but we crammed in what we could. I hope it was a good intro to everyone and encourage you to head out and get Prism'd and see what the Patterns and Practices group has put together, it's a really great framework for building WPF based composite apps.

    Not this prism, but close...

    Thanks again to everyone who came out (even if it was for the food) and I had a blast presenting the content with James to you guys. Here's a copy of the slide deck if you're interested and here are a few key links from it:

    Thanks!

  • 9 Options, 4 Icons, 1 MessageBox

    You know there are things in life that you never notice or worry about. This is one of them.

    The MessageBox API in Windows Forms allows you to specify message box icons to display along side your all-important message you're communicating to the user (System Error, Hard Drive Full, Your Cat is Pregnant, that sort of thing). Icons can help add a little punch to an otherwise drab afternoon staring at rows and rows of spreadsheets and overdue time cards.

    The 9 options you can select from to kick your otherwise drab battleship gray business application up are: Asterix, Error, Exclamation, Hand, Information, Question, Stop, Warning, and None. None of course presents no icon. The others provide you with an icon that matches the description. Or does it?

    Here's the Asterix option:

    clip_image002

    And here's the Information option:

    clip_image002[5]

    Hmmm... something isn't right here. Am I seeing double? No, both options use the same icon.

    Onto the Exclamation icon:

    clip_image002[7]

    And the Warning one:

    clip_image002[9]

    Hey! You're copying and pasting the same image!

    No friends, I really did write a program to do all this (contact me for licensing and source code rights) and they really are different.

    Finally here's the Error, Hand, and Stop icons (all conveniently wrapped up in one picture):

    clip_image002[11]

    Yup. All three use the red 'X' icon. You would think, oh I don't know, the Hand would display a Hand icon and Stop might, oh what the heck I'll take a stab at this, display a Stop sign. Now I'm all for saving on resources. After all, icons cost money to make; take up valuable bytes in the CLR; and lord knows how many hours of debate over the right shade of yellow for the Warning icon was spent. However if you're going to provide a programmer 9 different options (which all seem reasonable and unique) then why would you only provide 4 icons (I neglected to show the Question icon which is indeed a question mark). Did the MessageBox team have their budget cut or something?

    In any case, this seemingly random blog entry has been brought to you by the letters M, M, and M and the number M.

  • National Do Not Call List for Canada, well... not really

    Today they launch the National Do Not Call list in Canada, a bill that was passed 3 years ago but it's taken this long to build the service (guess they don't practice Agile in their software delivery process). From the looks of the service you might be jumping for joy thinking all those annoying calls at dinner time will stop. Think again.

    I went to register my number with the National Do Not Call list but I’m pretty skeptical that it’s of any value. There are a whack of exclusions:

    • Any registered charities can call you
    • Anyone you’ve done business with in the past 18 months
    • Anyone you’ve made an inquiry to in the past 6 months
    • Political parties
    • Public surveys
    • Newspapers for the purpose of subscriptions

    Hmmm. Doesn't leave much left does it? 

    In addition, apparently it costs money for the telemarketers to subscribe to the list. It’s not clear that if they don’t subscribe to the list they can/cannot call you. All it says in the rules are that “Telemarketers and Clients of Telemarketers must subscribe to the National DNCL and pay any applicable application fees”. 

    I suppose it will reduce the number of “cold call” telemarketers that will call you, but I’m suspicious that it’ll really reduce much. Looking at the exclusion list, basically there’s very few organizations that will fit into the non-exclusion list and are open to interrupt your dinner time (or quality Halo 3 time).

    For the most part, I get called by my own bank and credit card companies (offering me extra insurance or whatever the flavor of the day is). According to the rules since I do business with them, unless I tell them to put me on their internal DNC list, they’ll still continue to call me with their offers I can’t be bothered with. That’s if they even have an internal DNC list and there’s no legislation that requires them to. 

    Some people are welcoming the list, I just have doubts that it'll do much good. I agree that it's a good thing but there are too many restrictions, rules, and loopholes to make it really value-add to the consumer. True, you get off those cold-call lists from unknown telemarketers but in my experience I get more calls from business that I work with (banks, etc.) than unknown telemarketers and they're excluded (as is newspaper/magazine subscription calls which I get a lot of those too).

    BTW, I tried to register my number but it took me to a page that simply said:

    The service is not available. Please try again later.

    I guess they didn’t figure anyone would actually use it or maybe the webserver just fell over and nobody cares.

    Brilliant.

  • Terrarium, Terrarium, Terrarium

    I'm presenting a talk around Terrarium development at the Edmonton .NET User Group on September 25th. The talk is focused on upgrading a legacy app (1.1) to 2.0 (and beyond to 3.5 eventually), building and running your own Terrarium (complete with man-eating critters), and the future roadmap.

    Here's the session abstract:

    Terrarium was created by members of the .NET Framework team in the .NET Framework 1.0 timeframe and was used initially as an internal test application. In Terrarium, you can create herbivores, carnivores, or plants and then introduce them into a peer-to-peer, networked ecosystem where they complete for survival. Terrarium demonstrates some of the features of the .NET Framework, including Windows Forms integration with DirectX; XML Web services; support for peer-to-peer networking; support for multiple programming languages; the capability to update smart client, or Windows-based, applications via a remote Web server; and the evidence-based and code access security infrastructure. This session is to explore the newly open sourced tool and talk about aspects and challenges around porting the 1.1 code to 2.0, introducing new framework features, updating the architecture. As well, we’ll look at building new creatures to introduce to your terrarium; how the entire eco-system works from a developers perspective, and the future roadmap where the Terrarium community is going.

    I'll also be presenting the same session to the Calgary .NET User Group, we're just finalizing a date. See you there!

    Update: The Calgary .NET User Group presentation is confirmed for October 1st. Details can be found here on their site. The talk will be titled "The interaction of feeding and mating in the software development control of a Terrarium".

  • TechDays 08 - Mini Me version of TechEd, now with Canadian Content!

    Great news for Canadians! No, we haven't discovered a new source of unlimited clean-burning fuel and Stephen Harper is still our Prime Minister (for now).

    image

    Microsoft Canada has put together an awesome road show and it's coming soon. This is very much a mini-TechEd style conference but with a few twists. First off, it's Canadian based and will be hitting the major cities over the next couple of months. Second, some of the content is delivered by local freaks (such as myself) rather than the same old canned presentations by MSFT speakers. Don't get me wrong, the Canadian Developer support team (John Bristowe, Jean-Luc David, et. al.) are great but hey everyone has seen and heard them over and over again (and frankly Bristowes drag-n-drop sessions make me want to hurl). Now we can grab some premium air time and talk from the hip.

    Unlike the previous road show launches and sessions, this is a paid event. Wait, stick around. Okay, I understand and hear ya. Why buy the milk when I can get the cow for free? Here's some factoids to make your want to rush out and buy your Donald Belcham Secret Decoder Ring (and optional Justice Gray Hair Tonic Revitalizer). Rather than a single day, the event is spread out over 2 days (you can choose to attend a single day or both, your choice). In addition, there are over 30 technical sessions all on new technology (nothing old and crappy here, well maybe some old-ish stuff but not crappy) including Windows and Web development, Virtualization, and Infrastructure. There are also "birds-of-a-feather" type sessions and some after party geek fests going on. All in all, a pretty slick way to kill off two days in cold, cold winter (and that means you Winnipeg!).

    The two day conference is happening in the larger cities (Toronto, Montreal, Calgary, and Vancouver) with the one day conference happening in the less fortunate ones (Winnipeg, Halifax and Ottawa). The early bird price (before October 15) for one day is $124.99 or $249.99 for both days. After October 15th the price goes up to double at $249.99 and $499.99 respectively (so obviously if money is a concern I suggest you get in before October 15th). Space *is* limited to 5000 people so don't wait to sit out on this one.

    Swag? Did I mention the swag? Any conference worth it's salt needs swag and this one is no exception. Each attendee gets the following goodies:

    • 6-month TechNet Plus Subscription
    • Visual Studio 2008 Professional (full package)
    • Expression Web (full package)
    • Visual Studio 2008 Team Suite (eval)
    • Expression Studio (eval)
    • Virtualization Resource Kit
    • 30% off certification voucher (applicable to all MS Certification exams)
    • TechEd 2008 DVD Set (just like being there, except without the drinking)
    • $100 discount coupon for DevTeach/SQLTeach

    More? Oh yeah, I mentioned the presentations. I'm planning on presenting a whack of talks on WPF covering (Databinding, WinForms integration, CompositeWPF, LOB apps, etc.) so that should be fun. This is tentative as I haven't got the final word yet to take the stage (and after reading this blog post I may not be allowed to show up), but whatever happens I promise a) lots of code, no fluff b) flying monkeys c) Terrarium, Terrarium, Terrarium d) no concealed lizards or logging chains of any kind e) comic book cross-overs and f) did I mention the code? Beat those promise Mr. Harper!

    The TechDays website will be online soon with more details and registration info. You can find that here. You can also check out D'Arcys twisted take on this here, and Miguel's more calmer preview here.

    See you there!

    Technorati Tags:
  • Setting the Publish Status to Include for 3rd Party Files with XBAP deployments

    I was trying to deploy a new WPF app via XBAP today and we were experiencing an odd deployment error.

    When we deployed and launched the app we were getting this error:

    Startup URI: http://localhost/XbapNHibernateDeploymentSpike/XbapNHibernateDeploymentSpike.xbap
    Application Identity: http://localhost/XbapNHibernateDeploymentSpike/XbapNHibernateDeploymentSpike.xbap#XbapNHibernateDeploymentSpike.xbap, Version=1.0.0.5, Culture=neutral, PublicKeyToken=8c4ee06d2506bc6f, processorArchitecture=msil/XbapNHibernateDeploymentSpike.exe, Version=1.0.0.5, Culture=neutral, PublicKeyToken=8c4ee06d2506bc6f, processorArchitecture=msil, type=win32

    System.Runtime.Serialization.SerializationException: Unable to find assembly 'NHibernate, Version=2.0.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4'.

    This was odd because I knew that NHibernate.dll was being distributed with the app. I confirmed. There it was in the manifest file and in the deployment directory. Checking the Application Files settings inside of Visual Studio (this was just a test deployment, please don't deploy apps from inside Visual Studio) it was there and included:

    The generated manifest file showed it was included as well:

    <dependency>
        <dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="NHibernate.dll" size="1638400">
          <assemblyIdentity name="NHibernate" version="2.0.0.4000" publicKeyToken="AA95F207798DFDB4" language="neutral" processorArchitecture="msil" />
          <hash>
            <dsig:Transforms>
              <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
            </dsig:Transforms>
            <dsig:DigestMethod Algorithm="
    http://www.w3.org/2000/09/xmldsig#sha1" />
            <dsig:DigestValue>hUljboZ3kBAzBFbanjzLCJCMua0=</dsig:DigestValue>
          </hash>
        </dependentAssembly>
    </dependency>

    This didn’t make any sense. It was in the manifest, in the published directory, and everything looked like it should work. Google wasn’t much help here as I was in uncharted territory so I just starting poking around.

    Finally I came to the problem and a solution. The hibernate.cfg.xml file was being included as a data file and spec’d out in the manifest like this:

    <file name="hibernate.cfg.xml" size="604" writeableType="applicationData">
        <hash>
          <dsig:Transforms>
            <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
          </dsig:Transforms>
          <dsig:DigestMethod Algorithm="
    http://www.w3.org/2000/09/xmldsig#sha1" />
          <dsig:DigestValue>eICryxpUlz1ZHRpxHt+P2z8kBJo=</dsig:DigestValue>
        </hash>
    </file>

    Changing it from “Data File” to “Include” solved the problem.

    In the working version of the manifest file, the NHibernate config file is spec’d out as this:

    <file name="hibernate.cfg.xml" size="604">
        <hash>
          <dsig:Transforms>
            <dsig:Transform Algorithm="urn:schemas-microsoft-com:HashTransforms.Identity" />
          </dsig:Transforms>
          <dsig:DigestMethod Algorithm="
    http://www.w3.org/2000/09/xmldsig#sha1" />
          <dsig:DigestValue>eICryxpUlz1ZHRpxHt+P2z8kBJo=</dsig:DigestValue>
        </hash>
    </file>

    Note the difference in the file declaration. The non-working one includes an attribute: writeableType="applicationData"

    This is pretty obscure and maybe I’m just a simple guy, but telling me that you can’t find NHibernate.dll when you were really looking for a different isn’t very intuitive. Yes, I checked the stack trace, thinking that maybe the config file wasn’t there and it was an NHibernate exception being thrown or gobbled up, no such luck. The error was being reported out of PresentationHost.exe long before NHibernate was even being called.

    Don’t ask me why changing the Publish Status from Data File to Include fixes the issue, I just work here.

    Update: Sure enough, after you publish something on the internet along comes the information you were looking for. Buried somewhere on the web I found this tidbit:

    If you set the 'Publish Status' of the xml data file to "Data File", this file will reside in the Data directory in the end user's Local Settings folder after installation. If you set the 'Publish Status' of the xml data file to "Include", the file will be output to the Application directory.

    For xbap applications, the "Application directory" is the IE cache but when the Publish Status was set to "Data File" rather than "Include" it was going to nowhere land.

  • Goodbye Patrick

    The SharePoint world is one less today.

    It's with sad news that I have to say but Patrick Tisseghem, a SharePoint MVP that I've known for years, suddenly passed away on Wednesday September 3. He died due to heart failure in Gothenburg, Sweden.

    I only met Patrick once at the first Summit I attended but he was an awesome and always interesting character. He was a talented guy and was always telling us about his beer trips throughout Europe while he was delivering SharePoint training.

    He was a wonderful teacher, diligent author, and great guy to hang out with and talk to. He will be sorely missed.

    Patrick is survived by his wife and two daughters. Our thoughts and prayers are with them.

  • WPF for Business Applications, ready for the average user?

    We're starting a new project and naturally we looked at leveraging the latest .NET framework features (auto properties, extension methods, lamdas, LINQ, etc.). The question of user interface came up and we had some decisions to make.

    This specific project we looked at building one client web front-end (for the majority of the users) and a SmartClient for a smaller contigent that requires a little more real-time feel along with more rich features the web client might not be able to do (without a lot of heavy lifting). As we were looking to start things, the notion of WPF vs. WinForms came up. This led us down a path to look at Prism (the Composite WPF project from the Patterns and Practices group) which has a lot to offer in frameworks and being able to do more with WPF (Prism is WPF only). WPF also has some benefits to automation (there are some new products that are tying into the automation frameworks) and testing. The pretty UI is just an afterthought and not the focus since we're building what would be considered a "traditional" business application (forms and maybe grids and reports).

    WPF also has the advantage that we could deliver the application using xbap which kicks ClickOnce up a notch. The Prism framework is based on modules loading into XAML regions so we were even looking at re-using XAML user controls and plugging them into different clients.

    This has kicked off a bit of a controversy and discussion. Is WPF really suited to business applications? Of course the answer is (as always) it depends. If you're business application requires a rich UI and a visual paradigm, then the obvious answer is yes. It's more intuitive for a user to drag a part from one component to another (say in a room designer) than to pick items from a grid and enter values in a form.

    However for the larger business applications (the meat and potatoes of the corporate world) we don't deal with "rich UIs" so where does that leave you? WinForms is not dead and according to Glenn Block is the "recommended breadth solution for LOB application development in the foreseeable future". The trade off is that if you're building SmartClients you might look toward a framework that provides a lot of OOTB features that you don't have to do. I'm not a big fan of NIH syndrome and the idea of having to rewrite loggers, event handlers, aggregators, presentation models and everything else you build into a SmartClient. Frankly, I don't get paid to build frameworks or re-invent the wheel for every application my client wants.

    Prism provides a nice framework (IMHO CAB done right) that you can leverage and pull it out in piecemeal to what you need. Unfortunately, it's WPF only. While some of the principles can be carried over to WinForms I think you'll end up doing more work to say try to get DataBinding working the same way (if at all). There are other aspects to WPF (ignoring the pretty UI) that don't carry over to WinForms (routed events, event aggregation, etc.) all of which you have to build yourself (or use CAB which is the overbloated bazooka edition of WinForm programming).

    The word from my twitter folks is somewhat slighted toward WPF:

    • WPF databinding isn't as evil as its predecessors and some people wouldn't build a WPF app without it
    • Control templating and eventing in WPF is useful even for the basic forms and datagrids
    • Testable automations ARE good reasons to use it

    Other questions that come up:

    • Do you really need/want a separate designer to build your UI and keep it completely separate from your application code? In WPF this is easier. For WinForms you need to outfit them with Visual Studio and frankly, I've never used a designer on a WinForms project (I have on WPF ones, but not business applications)
    • What is the adoption from the user perspective and can you get them to think "outside of the form" and be creative with solutions. In WPF you're not as bound to traditonal approaches to visual problems and building the same solutions is somewhat easier (trust me, manipulating pixels in WinForms is a bugger to put a control on top of another one, in WPF it just works)
    • Can you bake the learning curve of WPF into a business application budget or should it be something that developers just know? (i.e. only start a WPF app when you have developers that know it inside and out, which few do these days)

    I’m on the fence on WPF. From an automation and programming model, I think it’s fathoms above WinForms. I don’t mind the crafting of a good looking UI as I’m used to it in Blend and can whip off a UI just as fast as I can with WinForms. However I’m not sure its worth the extra effort (is there extra effort) in building business applications with it, but I’m torn with xbap where we can deliver a rich user experience without having to install a client.

    For WinForms you generally have to either harvest what you have from existing applications or RYO when it comes to the application framework. Re-writing presenter base classes, validation strategies, various implementations of patterns like repository and specification, and building a service layer over things like NHibernate can be fairly straight forward but still might take a few weeks, weeks of cost that the customer doesn't want to pay for to see nothing out the other end.

    There is the build as you go model, which works for any technology however you do want to keep consistency when you're building 5+ large applications a year and there's turnaround in the IT department. Re-inventing the wheel for every application isn't an option for anyone.

    Feel free to chime in with your thoughts, experiences, and ideas. Thanks!

  • ALT.NET Canada - Day 3 - The Sharing Circle

    ALT.NET Canada wrapped up in the grand ballroom at the University Sunday afternoon. It was a great end to an awesome weekend. As with Open Spaces Technology there's a closing, and Doc introduced the Sharing Circle to everyone (some of Open Spaces Technology is rooted in Native American traditions). Everyone had something to say about the experience (you're not obligated to say anything) so it's a great way to see how our little gathering affected everyone. Enjoy!