Want to follow this site? Here's the RSS feed.

NetFXHarmonics Code Annotation Format

Friday, April 24, 2009

If you look at any of my open-source projects or even the Themelia source code, you will see that I use a special type of coding annotation.  The annotation format I designed (based on the designs of Sky Morey at Digital Evolution Group) is intended to maximize code readability and understandability.  The format is NOT a coding standard, but just what it says: an annotation format.

What’s that means?  Essentially when you are reading code you are constantly parsing all the symbols that you see.  Your brain can only work so fast, though, and some things have a higher parsing latency than others.  For example, VB code is incredibly verbose and uses long symbols to representing even the smallest things.  It will use the symbol “Then” where C# will use the symbol “}” (to some it may seem odd to think of a word as a symbol, but that’s all it is—you never read ever letter of a word you know.  If you know the word, your brain treats it as a symbol, not a series of symbols.)  It will also use two different character sets (what we call upper case and lower case) interchangeably, thus ever increasing the latency.  Though C# was designed with extremely low latency in mind, it, like all other languages, still has excess latency.

Thus, my code annotation format comes on the scene to make mental code parsing extremely fast.  It covers everything from how to case comments, when NOT to write comments, when to add metadata to class members, and how to deal with line breaks (the cardinal rule of the format!)  Most importantly, every annotation rule has an extensive commentary explaining why the rule exists and what value it provides in the long run.

Now, as with ALL THINGS EVERYWHERE, when you first start to apply it, it’s going to seem odd and it will slow you down at first.  After time, however, you will become extremely efficient at it and your code readability should dramatically improve.  When this is used in groups, it should seriously lower decrease the time it takes to read and understand the purpose of code.

You can view the NetFXHarmonics Code Annotation Format at http://www.netfxharmonics.com/document/code/format.

New Silverlight 3 Features

Monday, April 20, 2009

Though I’m a member of the Silverlight 3 Early Adopter’s Program (and thus have been getting weekly builds of Silverlight long before the public beta), I’m probably not going to be writing anything about the new features.  This isn’t because Silverlight 3 is boring, but, rather, because I have a strict policy of never doing something that other’s are already doing.  So, I would like to direct your attention to a few web sites showing the awesome provided by Silverlight 3 (and you won’t find business-application boringness here).

First, Tim Huerer has a nice post giving a very quick rundown of the new features:

Second, Jeff Prosise’s blog shows some of the cooler features of Silverlight 3.  Maybe it’s just because I absolutely HATE business application development, but I find Jeff’s blog to be 100x more interesting than the “how to write use X to write your boring line-of-business application.”  His work is also not for the naive or faint of heart.  Instead, it’s for professional developers (i.e. the extremely rare people who aren’t afraid to do things the right way.)  If Jeff adds more stuff, I’ll add them to this list.

Finally, you can always head over to the Mix ‘09 web site and watch some Silverlight 3 (and 2) videos.  Most of them also have PowerPoint files associated with them.  Personally, I can’t stand the torture of listening to someone take 30 minutes to say something that I can ready in 3 minutes.  That’s one reason I turned Microsoft down when they asked me to turn my Understanding WCF Services in Silverlight 2 into a talk at Mix.  Boring.  Here’s the Mix link:

Jeff Prosise’s Silverlight Tips

Friday, April 10, 2009

This post may be completely meaningless to most of the developers out there as it deals with my type of development: non-business application development.  More specifically, Jeff Prosise of Wintellect (the Navy SEALs of .NET) has posted a few really nice tips and tricks for Silverlight development.  These are really great tricks that serve as great examples of some of the more powerful things you can do with Silverlight:

Links

CitationAttribute for Citing Work

Saturday, April 4, 2009

As a researcher, designer, and open-source developer, it's very important to me to both cite the work I reference as well as to be cited appropriately.  Few things are more lame than finding my research some place on CodePlex disguised work different working under someone else's name... or a file from one of my many open-source systems in someone else's project without my copyright information.

To help me keep track of where a file or piece of research came from, I wrote a quick attribute to help keep some of this metadata around: CitationAttribute.  This is in my Themelia Framework and I use it extensively in my projects to keep track of where research and files came from.  Below is an example of how to use the attribute.  Fritz Onion was kind enough to allow me to include his ViewState parser in my work.  Notice the metadata in the attribute:

[Citation("http://www.pluralsight.com/fritz/", Copyright = "Copyright (c) 2008 Fritz Onion", DateUpdated = "03/25/2008")]
public static class ViewStateXmlBuilder
{
    //+ implementation here
}

Here you can see that the reference source is cited as well as the copyright and date the local file was updated with the appropriate version.  Note that this does not replace a file copyright.  I asked Fritz for a complete copyright comment block and he provided that for me.  Above the actual file I include with my Themelia Framework is his actual C# comment stating his actual copyright/disclaimer.

Here's the CitationAttribute as seen in my Themelia Framework:

#region Copyright
//+ Themelia Framework 2.0 - Core Module
//+ Copyright © Jampad Technology, Inc. 2007-2009
//+
//+ This file is a part of the Themelia Framework.
//+ The use and distribution terms for this software are covered by the
//+ Microsoft Permissive License (Ms-PL) which can be found at
//+ http://www.microsoft.com/opensource/licenses.mspx.
#endregion
using System;
//+
namespace Themelia
{
    /// <summary>
    /// Used to signify that a particular type was pulled from a third part project or piece of research.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false, AllowMultiple = false)]
    public class CitationAttribute : Attribute
    {
        private readonly String _source;

        //+
        //- @Copyright -//
        /// <summary>
        /// Represents the copyright of the referenced entity.
        /// </summary>
        public String Copyright { get; set; }

        //- @DateUpdated -//
        /// <summary>
        /// Represents the date the local version was updated with the referenced entity.
        /// </summary>
        public String DateUpdated { get; set; }

        //- @DateUpdated -//
        /// <summary>
        /// Represents the 2 (i.e. "en") or 5 (i.e. "en-US") character culture used to format the date (default = en-US)
        /// </summary>
        public String DateCulture { get; set; }

        //- @License -//
        /// <summary>
        /// Represents the license associated with this file (e.g. BSD, MIT, LGPL, Public Domain; default = Custom). This property is not legally binding.  It should only be used as a means of finding the general direction of where to look for the legally binding license.
        /// </summary>
        public String License { get; set; }

        //+
        //- @Ctor -//
        public CitationAttribute(String Source)
        {
            _source = Source;
            //+
            DateCulture = "en-US";
            License = "Custom";
        }
    }
}

There are a few things to notice about this attribute.  First, there is also a property for DateCulture.  This is very important.  Depending on your culture 05 03 2009 or 03 05 2009 may be March 5th.  Second, there's a License property.  In this example, it's "Custom".  As another example, if you were to cite Themelia, you would use "Ms-PL" as your License.  Third, the source is required.  It's not that it absolutely has to be a URL, but it's definitely required nonetheless.

Where should you use this file?  Anywhere you cite someone's research, where you use someone's file, or derive from their work.  This doesn't mean only in places where you copy/paste a class from another person's framework.  This also means in places where you find an article online and you use the research in that article to write your own class.

For example, if you were looking online for a solution to create a solution for getting Silverlight to access the clipboard (the mother of all security breaches, but whatever!) and you find a blog post about that, then when you write your classes to use that, you need to cite the blog post.  If you don't, then you are depriving a future developer from seeing the commentary of that code.  By citing the research with the attribute, you are telling the future reader where to see the research.  In the case of using a someone else's files, the attribute will tell future developer's (and you) where to find the updated version.

Exception Handlers for Silverlight 2.0

Tuesday, March 31, 2009

Whereas Themelia is my foundation for all .NET development, it’s a little known fact that I have an internal build of it specifically used for Silverlight.  Among the many features of Themelia for Silverlight (hereafter called “ThemeliaSL”) is something I call Exception Handlers.  This isn’t the same thing as the “catch” block of a try/catch.  No, it’s a concept specific to Silverlight.  Also, this is a fairly discrete feature that you can implement in your own Silverlight applications without the need of my full framework.  However, before you can understand this feature, you need to understand Silverlight currently works with unhandled exceptions.

When Silverlight throws an exception that’s unhandled, it eventually gets bubbled up to your System.Windows.Application instance.  If you are handling the UnhandledException event of this class, then you have an opportunity to handle this exception on your own.  When your UnhandledException event handler is called, you are passed an instance of System.Windows.ApplicationUnhandledExceptionEventArgs.  In this class you are provided a property named ExceptionObject of type System.Exception which holds the actual exception object that has been thrown.  There’s one other property though: Handled.  This property is a boolean which provides you with the ability to say whether you handled the exception or not.  If you set this property to true, then you are telling Silverlight that the problem has been taken care of.  If you set it to false, then you are telling Silverlight that it’s about to die.

That’s really all there is to Silverlight exception handling.  You can, however, make things a bit more streamlined.  Say, for example, you know of various types of exceptions that your application or underlying frameworks will throw.  You also know that you want to handle some of them in a specific way.  Or maybe, you just don’t want any communications exceptions to ever be sent back to the client.  For situations like these, you can use the concept I refer to as exception handlers.

Before we implement this concept, lets see how it will be used first:

public class Application : Themelia.Windows.Application
{
    public Application()
        : base()
    {
        AddExceptionHandler(typeof(CommunicationException), delegate(Exception ex)
        {
            if (ex.InnerException == null)
            {

                ReportExceptionToFirebug(ex.InnerException);
                return true;
            }
            //+ 
            return false;
        });
    }
}

Essentially, call the base constructor of the Application class we are about to create.  Then, for each exception that you want to handle, register it with the AddExceptionHandler method, sending it the type of the exception and a delegate of type Func<Exception, Boolean>.  In this example, when an unhandled exception of type CommunicationException is thrown, we automatically check to see if it has an inner exception.  If so, we report the exception in a special way and mark the exception as handled.

You could also add more exception handlers.  Here’s another example:

AddExceptionHandler(typeof(ArgumentException), delegate(Exception ex)
{
    ReportValidationError(ex);
    return true;
});

While this example is a rather silly one (because validation shouldn’t throw exceptions!), it does go to show you this is essentially a declarative model for exception handling.  Now it’s time to move on to build the thing.

First, create your own abstract version of System.Windows.Application.  This is typically a good idea anyways.  It allows you to control your applications in a very streamlined manner.  In this class, add the following static member:

private static Dictionary<Type, Func<Exception, Boolean>> HandlerRegistry = new Dictionary<Type, Func<Exception, Boolean>>();

This represents a registry of all exceptions handlers registered to your application.  It’s a dictionary with the key representing the Type of the exception and the value representing a delegate to be called when that exception is raised.

You’ll also need a standard .NET locking object:

private static Object _lock = new Object(); 

Now add the following method:

//- #AddExceptionHandler -// 
protected void AddExceptionHandler(Type type, Func<Exception, Boolean> handler)
{
    lock (_lock)
    {
        HandlerRegistry.Add(type, handler);
    }
}

This will allow you to register exception handlers from your concrete instance of your custom application class.

Now it’s on to the meat of the implementation.  In your base class application class constructor, handle the UnhandledException event.

this.UnhandledException += new EventHandler<System.Windows.ApplicationUnhandledExceptionEventArgs>(OnUnhandledException);

Then, in the method that will be called upon the event being raised, do something like this:

//- #OnUnhandledException -// 
protected virtual void OnUnhandledException(Object sender, ApplicationUnhandledExceptionEventArgs ea)
{
    lock (_lock)
    {
        if (HandlerRegistry.Count > 0)
        {
            Exception exception = ea.ExceptionObject;
            Type type = exception.GetType();
            if (HandlerRegistry.ContainsKey(type))
            {
                ea.Handled = HandlerRegistry[type](exception);
            }
        }
    }
    if (!System.Diagnostics.Debugger.IsAttached && this.AutoReportErrorToDOM && !ea.Handled)
    {
        ea.Handled = true;
        Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(ea); });
    }
} 

Essentially, if there are any registered handlers, check to see if the currently thrown exception is one of those exception registered to be handled.  If so, then pull the delegate from the registry and call it.

Notice that the delegate that we registered is Func<Exception, Boolean>.  Functionally, this means is that the delegate will accept an Exception object and return a boolean.  Interpreted, this means that in the delegate you register you need to return a boolean representing whether you want the exception handled or not.

You may also notice in the above code that there is a property named AutoReportErrorToDOM.  This does exactly what it says  and it’s nothing too exciting:

//- @AutoReportErrorToDOM -// 
public Boolean AutoReportErrorToDOM { get; set; }

The ReportErrorToDOM method is the same one that Visual Studio 2008 throws in with the Silverlight template.  For completeness, here it is:

//- #ReportErrorToDOM -// 
protected void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs ea)
{
    try
    {
        String errorMsg = ea.ExceptionObject.Message + ea.ExceptionObject.StackTrace;
        errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
        System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
    }
    catch (Exception)
    {
    }
}

At this point, you have everything you need to make the samples that we went through work properly.  Just be sure to base your application class on the new one and you’ll be set.

One important note is that when you are using custom visual entities in Silverlight, you need to make sure that you properly register the namespace in XAML.  For example, say the above class was called “Application” in the “Themelia.Windows” CLR namespace in the “Themelia.Silverlight” assembly.  For this configuration, you would use the following xaml:

<t:Application 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:t="clr-namespace:Themelia.Windows;assembly=Themelia.Silverlight" 
    x:Class="Sample.Application" />

With this, you’re all set.

Tip: Quick Reflector Loading for .NET and Silverlight

Wednesday, March 18, 2009

In my daily development there are three tools that I keep open almost constantly:  Visual Studio 2008, Windows Debugger, and Reflector.  The first is obvious, the second is for extreme-debugging, and the third so I can have a clue what I’m working with (...I have NO idea how people do .NET or Silverlight development without reflector!)  The first two I access with icons, while the third is one that I open and close at least 10 times a day.

To quickly access reflector (as well as Notepad2 and a whole host of sysinternals apps!) I throw it in my Windows folder so I can access it from the Run box.  Not only that, but I typically rename tools I throw in there to have only one letter.  Reflector is “r”.  So, I hit Win-R and type “r”.  Up comes reflector.  Here’s the thing though: I work in both .NET and Silverlight equally.  Yet, Reflector only loads ONE of them.  What to do?

The fix is simple: copy r.exe to rs.exe.  When I load r.exe, I select .NET.  When I load rs.exe, I select Silverlight.  Now I when I hit Win-R, I can type either “r” or “rs” depending on what framework I want to inspect.  You could even take the concept further by making a “rf.exe” for the compact framework”  Each “x.exe” will have it’s own “x.cfg” so the configurations won’t bleed over each other.

Creative Commons License
This work is licensed under a Creative Commons Attribution 2.5 License.

Built on Themelia Pro 2.0

Mini-icons are part of the Silk Icons set of icons at famfamfam.com