2005 2006 2007 2008 2009 2010 2011 2015 2016 aspnet azure csharp debugging exceptions firefox javascriptajax linux llblgen powershell projects python security services silverlight training videos wcf wpf xag xhtmlcss

CitationAttribute for Citing Work

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

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

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.

Adding XmlNode to Silverlight

Of the many types of data I work with, XML shows up all the time.  However, when working in Silverlight, your XML options are dramatically limited.  For example, for some reason Microsoft totally forgot to add a simple XmlNode class.  Microsoft seems to think that using LINQ for XML will solve all our XML problems.  Well, most of the stuff that I do on a daily basis has nothing to do with extensive querying XML.  I just need something simple to pull quick data.  Not only that, but LINQ for XML is in the System.Xml.Linq assembly, which is not a native Silverlight assembly.  I’m not going to bloat my XAP file for a single dependency.

So, in my internal build of Themelia for Silverlight, you will find the Themelia.Xml.XmlNode class.  I use this all over the build entire XML trees and to search the same tree for elements I need.  All this in one small discrete class that doesn’t require you to bloat your XAP file.  Here’s a sample of how to use my XmlNode class:

XmlReader reader = XmlReader.Create(new StringReader(@"<s:Envelope xmlns:s=""http://schemas.xmlsoap.org/soap/envelope/"">
    <s:Body>
    <s:Fault>
      <faultcode>s:Client</faultcode>
      <faultstring xml:lang=""en-US"">This is the fault reason.</faultstring>
      <detail>
        <FaultDetail xmlns=""http://schemas.datacontract.org/2004/07/Sample.Service"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
          <Reason>This is the fault reason.</Reason>
          <Source>GetPersonData</Source>
        </FaultDetail>
      </detail>
    </s:Fault>
    </s:Body>
    </s:Envelope>"));
XmlNode node = new XmlNode(reader);
XmlNode faultDetailNode = node.FindDescendant("faultDetail");
stackpanel01.Children.Add(new TextBlock
{
    Text = faultDetailNode.FirstChild.TextContent
});
stackpanel01.Children.Add(new TextBlock
{
    Text = faultDetailNode.AttributeDictionary["xmlns"]
});
stackpanel01.Children.Add(new TextBlock
{
    Text = faultDetailNode.AttributeDictionary["xmlns:i"]
});

It does a few more things that you can see by looking at the source for it, but this is essentially all I need in for XML processing on most days.  Here’s the source for XmlNode.cs:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
//+
namespace Themelia.Xml
{
    public class XmlNode
    {
        //- @Name -//
        public String Name { get; set; }

        //- @TextContent -//
        public String TextContent { get; set; }

        //- @Children -//
        public List<XmlNode> NodeList { get; set; }

        //- @AttributeMap -//
        public Dictionary<String, String> AttributeDictionary { get; set; }

        //- @FirstChild -//
        public XmlNode FirstChild
        {
            get
            {
                if (NodeList.Count > 0)
                {
                    return NodeList[0];
                }
                //+
                return null;
            }
        }

        //+
        //- @Ctor -//
        private XmlNode()
        {
            NodeList = new List<XmlNode>();
            AttributeDictionary = new Dictionary<String, String>();
        }
        public XmlNode(XmlReader xmlReader)
            : this()
        {
            Initialize(xmlReader);
        }
        public XmlNode(Stream xmlStream)
            : this(XmlReader.Create(xmlStream))
        {
        }
        public XmlNode(String name)
            : this()
        {
            Name = name;
        }

        //- $Initialize -//
        private void Initialize(XmlReader reader)
        {
            reader.Read();
            this.Name = reader.Name;
            //+ attribute
            reader.MoveToElement();
            if (reader.HasAttributes)
            {
                reader.MoveToFirstAttribute();
                AttributeDictionary.Add(reader.Name, reader.Value);
                while (reader.MoveToNextAttribute())
                {
                    AttributeDictionary.Add(reader.Name, reader.Value);
                }
            }
            //+ node
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    NodeList.Add(new XmlNode(reader.ReadSubtree()));
                }
                else if (reader.NodeType == XmlNodeType.Text)
                {
                    TextContent = reader.ReadContentAsString();
                }
            }
        }

        //- @FindDescendant -//
        public XmlNode FindDescendant(String name)
        {
            XmlNode foundNode = NodeList.FirstOrDefault(p => p.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
            if (foundNode != null)
            {
                return foundNode;
            }
            foreach (XmlNode node in NodeList)
            {
                foundNode = node.FindDescendant(name);
                if (foundNode != null)
                {
                    return foundNode;
                }
            }
            //+
            return foundNode;
        }

        //- @FindDescendantList -//
        public List<XmlNode> FindDescendantList(String name)
        {
            List<XmlNode> nodeList = new List<XmlNode>();
            XmlNode foundNode = NodeList.FirstOrDefault(p => p.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
            if (foundNode != null)
            {
                nodeList.Add(foundNode);
                foundNode = null;
            }
            foreach (XmlNode node in NodeList)
            {
                foundNode = node.FindDescendant(name);
                if (foundNode != null)
                {
                    nodeList.Add(foundNode);
                    foundNode = null;
                }
            }
            //+
            return nodeList;
        }

        //- @GetChildDictionary -//
        public Dictionary<String, String> GetChildDictionary()
        {
            Dictionary<String, String> map = new Dictionary<String, String>();
            foreach (XmlNode node in NodeList)
            {
                if (!String.IsNullOrEmpty(node.TextContent))
                {
                    map.Add(node.Name, node.TextContent);
                }
            }
            //+
            return map;
        }
    }
}

Yeah, there’s more it could probably do and I’ll probably add more to it in the future, but this little class has worked in all my XML scenarios so far.

Obtaining Enumeration Names and Values in Silverlight 2.0

In .NET, when you are dealing with singular enumerations (the ones singular names) or flags enumerations (the ones with plural names), you have the ability to access the names and values of each of the items in the enumeration.  For example, the below code iterates through and prints out both the values and names of the enumeration items:

using System;
//+
namespace Sample
{
    public enum Component
    {
        Keyboard,
        Mouse,
        Display,
        Disk,
        Memory,
        Network
    }

    public class Program
    {
        //- $Main -//
        private static void Main(String[] args)
        {
            //+ name
            foreach (String name in Enum.GetNames(typeof(Component)))
            {
                Console.WriteLine(name);
            }
            //+ value
            foreach (Object value in Enum.GetValues(typeof(Component)))
            {
                Console.WriteLine((Int32)value);
            }
        }
    }
}

Now let’s go to do the same thing in Silverlight 2.0.

image

Err... wait a minute.  Where’s GetNames and GetValues?  Well, they don’t exist.  Fortunately, we have the ability to access these via reflection.  To obtain the names, we just need to obtain the Type object of our enumeration and call GetFields with the Public and Static binding flags set, and look in the resulting FieldInfo array.  Each FieldInfo object will have a Name property without item name.  For the values, we simply use Enum.Parse to turn that name into the actual value.  For the underlying value, we can just cast that to the underlying type of the enumeration.  In the example above, that would be System.Int32.  Here’s all that in action:

 

//- $OnLoaded -//
private void OnLoaded(Object sender, System.Windows.RoutedEventArgs e)
{
    Type enumType = typeof(Component);
    System.Reflection.FieldInfo[] fiArray = enumType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
    foreach (System.Reflection.FieldInfo fi in fiArray)
    {
        //+ name
        sp01.Children.Add(new TextBlock
        {
             Text = fi.Name
        });
    }
    foreach (System.Reflection.FieldInfo fi in fiArray)
    {
        //+ value
        sp01.Children.Add(new TextBlock
        {
            Text = ((Int32)Enum.Parse(enumType, fi.Name, false)).ToString()
        });
    }
}

I’ve left the namespaces of the items in the System.Reflection namespace in place so you can see exactly what types were working with here.

Of course, you can always wrap this up into it’s own class so you can reuse this logic all over:

namespace Themelia
{
    public class EnumReader
    {
        /// <summary>
        /// Gets the names of an enumeration type.
        /// </summary>
        /// <param name="enumerationType">Type of enumeration.</param>
        /// <returns>List of names of the enumeration.</returns>
        public static List<String> GetNameList(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException("Specified generic parameter must be an enumeration.");
            }
            List<String> nameList = new List<String>();
            //+ type
            FieldInfo[] fiArray = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (FieldInfo fi in fiArray)
            {
                nameList.Add(fi.Name);
            }
            //+
            return nameList;
        }

        //- @GetNameList -//
        /// <summary>
        /// Gets the names of an enumeration type.
        /// </summary>
        /// <typeparam name="T">Type of enumeration.</typeparam>
        /// <returns>List of names of the enumeration.</returns>
        public static List<String> GetNameList<T>() where T : struct
        {
            return GetNameList(typeof(T));
        }

        //- @GetValueList -//
        /// <summary>
        /// Gets the values of an enumeration type.
        /// </summary>
        /// <typeparam name="T">Type of enumeration.</typeparam>
        /// <returns>List of values of the enumeration.</returns>
        public static List<T> GetValueList<T>() where T : struct
        {
            Type enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException("Specified generic parameter must be an enumeration.");
            }
            List<T> valueList = new List<T>();
            FieldInfo[] fiArray = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (FieldInfo fi in fiArray)
            {
                valueList.Add((T)Enum.Parse(enumType, fi.Name, false));
            }
            //+
            return valueList;
        }
    }
}

In this example class, you can see that two of the methods are actually declared as generic.  So, to use them like this:

//- $OnLoaded -//
private void OnLoaded(Object sender, System.Windows.RoutedEventArgs e)
{
    foreach (String name in EnumReader.GetNameList<Component>())
    {
        //+ name
        sp01.Children.Add(new TextBlock
        {
            Text = name
        });
    }
    foreach (Component component in EnumReader.GetValueList<Component>())
    {
        //+ value
        sp01.Children.Add(new TextBlock
        {
            Text = ((Int32)component).ToString()
        });
    }
}

One thing to keep in mind is that reflection does have a performance hit.  However, given that most of WPF, Silverlight, and WCF are all about constant reflection, you can rest comfortably that it’s not nearly as bad as some people would say.  Having said that, if your application profiling does say that you are reflecting too much, you can always cache the data returned from these method and access the cache instead.  Don’t however, cache for the sake of caching.  Saying “We’re always going to cache, just to be consistent” is as stupid as saying “We’re always going to drive 45mph, just to be consistent.”  This kills people on both the interstate and in school zones.  Make your caching decisions (and ALL other decisions!) based upon your current situation never upon dangerous mindless consistency.

Powered by
Python / Django / Elasticsearch / Azure / Nginx / CentOS 7

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