Skip Navigation LinksHome > Product Betas > RSS Feed Concentrator Login
 
         Small Business Website
         StockPicker
         Mensa Book Lovers
         Newsletters
         Content Reader
         Crowdsourcing
         Photo Gallery
         RSS Feed Concentrator
         Product Road Map
         Timesheets
         Quiz Engine
  ...The New Salon.com  
Nowt so queer as folks
In the 1955 movie “The Prodigal,” Lana Turner rebuffs the attentions of Ed Purdom because “I am a priestess of Baal.”  She apparently sounded completely convincing with that line. Really, if you wanted to rebuff someone’s attentions, then that would be … Continue reading
  ...West Wind  
Creating a dynamic, extensible C# Expando Object

I love dynamic functionality in a strongly typed language because it offers us the best of both worlds. In C# (or any of the main .NET languages) we now have the dynamic type that provides a host of dynamic features for the static C# language.

One place where I've found dynamic to be incredibly useful is in building extensible types or types that expose traditionally non-object data (like dictionaries) in easier to use and more readable syntax. I wrote about a couple of these for accessing old school ADO.NET DataRows and DataReaders more easily for example. These classes are dynamic wrappers that provide easier syntax and auto-type conversions which greatly simplifies code clutter and increases clarity in existing code.

ExpandoObject in .NET 4.0

Another great use case for dynamic objects is the ability to create extensible objects - objects that start out with a set of static members and then can add additional properties and even methods dynamically. The .NET 4.0 framework actually includes an ExpandoObject class which provides a very dynamic object that allows you to add properties and methods on the fly and then access them again.

For example with ExpandoObject you can do stuff like this:

dynamic expand = new ExpandoObject();

expand.Name = "Rick";
expand.HelloWorld = (Func<string, string>) ((string name) => 
{ 
    return "Hello " + name; 
});

Console.WriteLine(expand.Name);
Console.WriteLine(expand.HelloWorld("Dufus"));

Internally ExpandoObject uses a Dictionary like structure and interface to store properties and methods and then allows you to add and access properties and methods easily. As cool as ExpandoObject is it has a few shortcomings too:

  • It's a sealed type so you can't use it as a base class
  • It only works off 'properties' in the internal Dictionary - you can't expose existing type data
  • It doesn't serialize to XML or with DataContractSerializer/DataContractJsonSerializer

Expando - A truly extensible Object

ExpandoObject is nice if you just need a dynamic container for a dictionary like structure. However, if you want to build an extensible object that starts out with a set of strongly typed properties and then allows you to extend it, ExpandoObject does not work because it's a sealed class that can't be inherited.

I started thinking about this very scenario for one of my applications I'm building for a customer. In this system we are connecting to various different user stores. Each user store has the same basic requirements for username, password, name etc. But then each store also has a number of extended properties that is available to each application. In the real world scenario the data is loaded from the database in a data reader and the known properties are assigned from the known fields in the database. All unknown fields are then 'added' to the expando object dynamically.

In the past I've done this very thing with a separate property - Properties - just like I do for this class. But the property and dictionary syntax is not ideal and tedious to work with.

I started thinking about how to represent these extra property structures. One way certainly would be to add a Dictionary, or an ExpandoObject to hold all those extra properties. But wouldn't it be nice if the application could actually extend an existing object that looks something like this as you can with the Expando object:

public class User : Westwind.Utilities.Dynamic.Expando
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public DateTime? ExpiresOn { get; set; }
}

and then simply start extending the properties of this object dynamically? Using the Expando object I describe later you can now do the following:

[TestMethod]
public void UserExampleTest()
{            
    var user = new User();

    // Set strongly typed properties
    user.Email = "rick@west-wind.com";
    user.Password = "nonya123";
    user.Name = "Rickochet";
    user.Active = true;

    // Now add dynamic properties
    dynamic duser = user;
    duser.Entered = DateTime.Now;
    duser.Accesses = 1;

    // you can also add dynamic props via indexer
    user["NickName"] = "AntiSocialX";
    duser["WebSite"] = "http://www.west-wind.com/weblog";


    // Access strong type through dynamic ref
    Assert.AreEqual(user.Name,duser.Name);

    // Access strong type through indexer 
    Assert.AreEqual(user.Password,user["Password"]);
    

    // access dyanmically added value through indexer
    Assert.AreEqual(duser.Entered,user["Entered"]);
    
    // access index added value through dynamic
    Assert.AreEqual(user["NickName"],duser.NickName);
    

    // loop through all properties dynamic AND strong type properties (true)
    foreach (var prop in user.GetProperties(true))
    { 
        object val = prop.Value;
        if (val == null)
            val = "null";

        Console.WriteLine(prop.Key + ": " + val.ToString());
    }
}

As you can see this code somewhat blurs the line between a static and dynamic type. You start with a strongly typed object that has a fixed set of properties. You can then cast the object to dynamic (as I discussed in my last post) and add additional properties to the object. You can also use an indexer to add dynamic properties to the object.

To access the strongly typed properties you can use either the strongly typed instance, the indexer or the dynamic cast of the object. Personally I think it's kinda cool to have an easy way to access strongly typed properties by string which can make some data scenarios much easier.

To access the 'dynamically added' properties you can use either the indexer on the strongly typed object, or property syntax on the dynamic cast.

Using the dynamic type allows all three modes to work on both strongly typed and dynamic properties.

Finally you can iterate over all properties, both dynamic and strongly typed if you chose. Lots of flexibility.

Note also that by default the Expando object works against the (this) instance meaning it extends the current object. You can also pass in a separate instance to the constructor in which case that object will be used to iterate over to find properties rather than this.

Using this approach provides some really interesting functionality when use the dynamic type. To use this we have to add an explicit constructor to the Expando subclass:

public class User : Westwind.Utilities.Dynamic.Expando
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public DateTime? ExpiresOn { get; set; }

    public User() : base()
    { }

    // only required if you want to mix in seperate instance
    public User(object instance)
        : base(instance)
    {
    }
}

to allow the instance to be passed. When you do you can now do:

[TestMethod]
public void ExpandoMixinTest()
{
    // have Expando work on Addresses
    var user = new User( new Address() );

    // cast to dynamicAccessToPropertyTest
    dynamic duser = user;

    // Set strongly typed properties
    duser.Email = "rick@west-wind.com";
    user.Password = "nonya123";
    
    // Set properties on address object
    duser.Address = "32 Kaiea";
    //duser.Phone = "808-123-2131";

    // set dynamic properties
    duser.NonExistantProperty = "This works too";

    // shows default value Address.Phone value
    Console.WriteLine(duser.Phone);

}


Using the dynamic cast in this case allows you to access *three* different 'objects': The strong type properties, the dynamically added properties in the dictionary and the properties of the instance passed in! Effectively this gives you a way to simulate multiple inheritance (which is scary - so be very careful with this, but you can do it).

How Expando works

Behind the scenes Expando is a DynamicObject subclass as I discussed in my last post. By implementing a few of DynamicObject's methods you can basically create a type that can trap 'property missing' and 'method missing' operations. When you access a non-existant property a known method is fired that our code can intercept and provide a value for. Internally Expando uses a custom dictionary implementation to hold the dynamic properties you might add to your expandable object.

Let's look at code first. The code for the Expando type is straight forward and given what it provides relatively short. Here it is.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Dynamic;
using System.Reflection;

namespace Westwind.Utilities.Dynamic
{
    /// <summary>
    /// Class that provides extensible properties and methods. This
    /// dynamic object stores 'extra' properties in a dictionary or
    /// checks the actual properties of the instance.
    /// 
    /// This means you can subclass this expando and retrieve either
    /// native properties or properties from values in the dictionary.
    /// 
    /// This type allows you three ways to access its properties:
    /// 
    /// Directly: any explicitly declared properties are accessible
    /// Dynamic: dynamic cast allows access to dictionary and native properties/methods
    /// Dictionary: Any of the extended properties are accessible via IDictionary interface
    /// </summary>
    [Serializable]
    public class Expando : DynamicObject, IDynamicMetaObjectProvider
    {
        /// <summary>
        /// Instance of object passed in
        /// </summary>
        object Instance;

        /// <summary>
        /// Cached type of the instance
        /// </summary>
        Type InstanceType;

        PropertyInfo[] InstancePropertyInfo
        {
            get
            {
                if (_InstancePropertyInfo == null && Instance != null)                
                    _InstancePropertyInfo = Instance.GetType().GetProperties(BindingFlags.Instance | 
                                                          BindingFlags.Public | BindingFlags.DeclaredOnly);
                return _InstancePropertyInfo;                
            }
        }
        PropertyInfo[] _InstancePropertyInfo;


        /// <summary>
        /// String Dictionary that contains the extra dynamic values
        /// stored on this object/instance
        /// </summary>        
        /// <remarks>Using PropertyBag to support XML Serialization of the dictionary</remarks>
        public PropertyBag Properties = new PropertyBag();

        //public Dictionary<string,object> Properties = new Dictionary<string, object>();

        /// <summary>
        /// This constructor just works off the internal dictionary and any 
        /// public properties of this object.
        /// 
        /// Note you can subclass Expando.
        /// </summary>
        public Expando() 
        {
            Initialize(this);            
        }

        /// <summary>
        /// Allows passing in an existing instance variable to 'extend'.        
        /// </summary>
        /// <remarks>
        /// You can pass in null here if you don't want to 
        /// check native properties and only check the Dictionary!
        /// </remarks>
        /// <param name="instance"></param>
        public Expando(object instance)
        {
            Initialize(instance);
        }


        protected virtual void Initialize(object instance)
        {
            Instance = instance;
            if (instance != null)
                InstanceType = instance.GetType();           
        }


       /// <summary>
       /// Try to retrieve a member by name first from instance properties
       /// followed by the collection entries.
       /// </summary>
       /// <param name="binder"></param>
       /// <param name="result"></param>
       /// <returns></returns>
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = null;

            // first check the Properties collection for member
            if (Properties.Keys.Contains(binder.Name))
            {
                result = Properties[binder.Name];
                return true;
            }


            // Next check for Public properties via Reflection
            if (Instance != null)
            {
                try
                {
                    return GetProperty(Instance, binder.Name, out result);                    
                }
                catch { }
            }

            // failed to retrieve a property
            result = null;
            return false;
        }


        /// <summary>
        /// Property setter implementation tries to retrieve value from instance 
        /// first then into this object
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {

            // first check to see if there's a native property to set
            if (Instance != null)
            {
                try
                {
                    bool result = SetProperty(Instance, binder.Name, value);
                    if (result)
                        return true;
                }
                catch { }
            }
            
            // no match - set or add to dictionary
            Properties[binder.Name] = value;
            return true;
        }

        /// <summary>
        /// Dynamic invocation method. Currently allows only for Reflection based
        /// operation (no ability to add methods dynamically).
        /// </summary>
        /// <param name="binder"></param>
        /// <param name="args"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if (Instance != null)
            {
                try
                {
                    // check instance passed in for methods to invoke
                    if (InvokeMethod(Instance, binder.Name, args, out result))
                        return true;                    
                }
                catch { }
            }

            result = null;
            return false;
        }
        

        /// <summary>
        /// Reflection Helper method to retrieve a property
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="name"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        protected bool GetProperty(object instance, string name, out object result)
        {
            if (instance == null)
                instance = this;

            var miArray = InstanceType.GetMember(name, BindingFlags.Public | 
                                      BindingFlags.GetProperty | BindingFlags.Instance);
            if (miArray != null && miArray.Length > 0)
            {
                var mi = miArray[0];
                if (mi.MemberType == MemberTypes.Property)
                {
                    result = ((PropertyInfo)mi).GetValue(instance,null);
                    return true;
                }
            }

            result = null;
            return false;                
        }

        /// <summary>
        /// Reflection helper method to set a property value
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected bool SetProperty(object instance, string name, object value)
        {
            if (instance == null)
                instance = this;

            var miArray = InstanceType.GetMember(name, BindingFlags.Public | 
                                                       BindingFlags.SetProperty | 
                                                       BindingFlags.Instance);
            if (miArray != null && miArray.Length > 0)
            {
                var mi = miArray[0];
                if (mi.MemberType == MemberTypes.Property)
                {
                    ((PropertyInfo)mi).SetValue(Instance, value, null);
                    return true;
                }
            }
            return false;                
        }

        /// <summary>
        /// Reflection helper method to invoke a method
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="name"></param>
        /// <param name="args"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        protected bool InvokeMethod(object instance, string name, object[] args, out object result)
        {
            if (instance == null)
                instance = this;

            // Look at the instanceType
            var miArray = InstanceType.GetMember(name,
                                    BindingFlags.InvokeMethod |
                                    BindingFlags.Public | BindingFlags.Instance);

            if (miArray != null && miArray.Length > 0)
            {
                var mi = miArray[0] as MethodInfo;
                result = mi.Invoke(Instance, args);
                return true;
            }

            result = null;
            return false;
        }



        /// <summary>
        /// Convenience method that provides a string Indexer 
        /// to the Properties collection AND the strongly typed
        /// properties of the object by name.
        /// 
        /// // dynamic
        /// exp["Address"] = "112 nowhere lane"; 
        /// // strong
        /// var name = exp["StronglyTypedProperty"] as string; 
        /// </summary>
        /// <remarks>
        /// The getter checks the Properties dictionary first
        /// then looks in PropertyInfo for properties.
        /// The setter checks the instance properties before
        /// checking the Properties dictionary.
        /// </remarks>
        /// <param name="key"></param>
        /// 
        /// <returns></returns>
        public object this[string key]
        {
            get
            {
                try
                {
                    // try to get from properties collection first
                    return Properties[key];
                }
                catch (KeyNotFoundException ex)
                {
                    // try reflection on instanceType
                    object result = null;
                    if (GetProperty(Instance, key, out result))
                        return result;

                    // nope doesn't exist
                    throw;
                }
            }
            set
            {
                if (Properties.ContainsKey(key))
                {
                    Properties[key] = value;
                    return;
                }

                // check instance for existance of type first
                var miArray = InstanceType.GetMember(key, BindingFlags.Public | BindingFlags.GetProperty);
                if (miArray != null && miArray.Length > 0)
                    SetProperty(Instance, key, value);
                else
                    Properties[key] = value;
            }
        }


        /// <summary>
        /// Returns and the properties of 
        /// </summary>
        /// <param name="includeProperties"></param>
        /// <returns></returns>
        public IEnumerable<KeyValuePair<string,object>> GetProperties(bool includeInstanceProperties = false)
        {
            if (includeInstanceProperties && Instance != null)
            {
                foreach (var prop in this.InstancePropertyInfo)
                    yield return new KeyValuePair<string, object>(prop.Name, prop.GetValue(Instance, null));
            }

            foreach (var key in this.Properties.Keys)
               yield return new KeyValuePair<string, object>(key, this.Properties[key]);

        }
  

        /// <summary>
        /// Checks whether a property exists in the Property collection
        /// or as a property on the instance
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Contains(KeyValuePair<string, object> item, bool includeInstanceProperties = false)
        {
            bool res = Properties.ContainsKey(item.Key);
            if (res)
                return true;

            if (includeInstanceProperties && Instance != null)
            {
                foreach (var prop in this.InstancePropertyInfo)
                {
                    if (prop.Name == item.Key)
                        return true;
                }
            }

            return false;
        }        

    }
}

Although the Expando class supports an indexer, it doesn't actually implement IDictionary or even IEnumerable. It only provides the indexer and Contains() and GetProperties() methods, that work against the Properties dictionary AND the internal instance.

The reason for not implementing IDictionary is that a) it doesn't add much value since you can access the Properties dictionary directly and that b) I wanted to keep the interface to class very lean so that it can serve as an entity type if desired. Implementing these IDictionary (or even IEnumerable) causes LINQ extension methods to pop up on the type which obscures the property interface and would only confuse the purpose of the type. IDictionary and IEnumerable are also problematic for XML and JSON Serialization - the XML Serializer doesn't serialize IDictionary<string,object>, nor does the DataContractSerializer. The JavaScriptSerializer does serialize, but it treats the entire object like a dictionary and doesn't serialize the strongly typed properties of the type, only the dictionary values which is also not desirable. Hence the decision to stick with only implementing the indexer to support the user["CustomProperty"] functionality and leaving iteration functions to the publicly exposed Properties dictionary.

Note that the Dictionary used here is a custom PropertyBag class I created to allow for serialization to work. One important aspect for my apps is that whatever custom properties get added they have to be accessible to AJAX clients since the particular app I'm working on is a SIngle Page Web app where most of the Web access is through JSON AJAX calls. PropertyBag can serialize to XML and one way serialize to JSON using the JavaScript serializer (not the DCS serializers though).

The key components that make Expando work in this code are the Properties Dictionary and the TryGetMember() and TrySetMember() methods. The Properties collection is public so if you choose you can explicitly access the collection to get better performance or to manipulate the members in internal code (like loading up dynamic values form a database).

Notice that TryGetMember() and TrySetMember() both work against the dictionary AND the internal instance to retrieve and set properties. This means that user["Name"] works against native properties of the object as does user["Name"] = "RogaDugDog".

What's your Use Case?

This is still an early prototype but I've plugged it into one of my customer's applications and so far it's working very well. The key features for me were the ability to easily extend the type with values coming from a database and exposing those values in a nice and easy to use manner. I'm also finding that using this type of object for ViewModels works very well to add custom properties to view models. I suspect there will be lots of uses for this - I've been using the extra dictionary approach to extensibility for years - using a dynamic type to make the syntax cleaner is just a bonus here.

What can you think of to use this for?

© Rick Strahl, West Wind Technologies, 2005-2012
Posted in CSharp  .NET  Dynamic Types  
  Marketing Roadhouse  
Social Media Audit: Goals
Goals. Some set their goals in the beginning of their social media planning and never look at them again. Others, don’t bother setting any goals and just dive right in to using the tools. The biggest problem with either of these conditions is you don’t know how you are performing. Do you have goals? Do [...]
  Fabulous Coding Adventures    
What is "binding" and what makes it late?

"Late binding" is one of those computer-sciency terms that, like "strong typing", means different things to different people. I thought I might describe what the term means to me.

First off, what is "binding"? We can't understand what it means to bind late if we don't know what it is to bind at all.

A compiler is by definition a device which takes in a text written in one language and outputs code that "means the same thing" in another language. The compiler I work on, for example, takes in C# and outputs CIL(*). All the principle tasks performed by a compiler falls into one of three broad buckets:

  • Syntactic analysis of the input text
  • Semantic analysis of the syntax
  • Generation of the output text -- we will be unconcerned with this step in this article

Syntactic analysis is analysis of the input text that does not consider anything about the meaning of that text; the syntactic analyzer is concerned with first determining the lexical structure of the program (that is, where all the boundaries are between comments, identifiers, operators, and so on) and then from that lexical structure determining the grammatical structure of the program: where are the boundaries between classes, methods, statements, expressions, and so on.

Semantic analysis then takes the results of the syntactic analysis and associates meanings with various syntactic elements. For example, when you say:

class X {}
class B {}
class D : B
{
  public static void X() { }
  public static void Y() { X(); }
}

syntactic analysis determines that there are three classes, that one of them contains two methods, the second method contains a statement which is a call expression. Semantic analysis determines that the X in X(); refers to the method D.X(), rather than, say, the type X declared above. That's an example of "binding" in its most widely-agreed-upon sense: binding is the association of a syntactic element that names a method with a logical element of the program.

"Binding" in the sense of "early" or "late" binding is almost always used to refer to the evaluation of a name used as a method call. That, however, is far too strict a definition of "binding" for me. I would also use "binding" to describe how the compiler's semantic analyzer determines that class D inherits from class B; the name "B" is bound to the class.

Moreover, I would use "binding" to describe other analyses as well. If you had an expression 1 * 2 + 1.0 in your program then I would say that the "+" operator is "bound" to the built-in operator that takes two doubles, adds them, and returns a third. People do not normally think of that analysis as associating the name "+" with a method, but nevertheless I consider it to be "binding".

Speaking even less carefully, I might also use "binding" to describe the association of types with expressions that do not directly name the type. In the example above if speaking casually I might say that the syntax 1 * 2 is "bound" to the type int, even though obviously it does not name that type. The syntactic expression is strongly associated with that semantic element, even though it does not name it.

So, speaking generally I would say that "binding" is any association of some fragment of syntax with some logical program element. (**)

What then is "late" vs "early" binding? People talk about these two kinds of bindings as though it was a binary choice, either early or late. As we'll see, actually there is more of a spectrum than you might imagine; some bindings are entirely early, some are partially early and partially late, and some are very late indeed. But before we get into that, earlier or later than what?

Basically by "early binding" we mean "the binding analysis is performed by the compiler and baked in to the generated program"; if the binding fails then the program does not run because the compiler did not get to the code generation phase. By "late binding" we mean "some aspect of the binding will be performed by the runtime" and therefore a binding failure will manifest as a runtime failure. Early and late binding might better be called "static binding" and "dynamic binding"; static binding is binding performed using "static" facts known to the compiler, and dynamic binding is performed using facts "dynamically" known to the runtime.

So which is better? Clearly neither is unambiguously better than the other; if one was clearly the winner then we wouldn't be having this discussion in the first place. The benefit of early binding is that you gain confidence that your program will not fail at runtime; the down side is that you lose the flexibility that comes with late binding. Early binding requires that all information required to make the right binding decision be known before the program runs; but that information might not be available until runtime.

I said that early and late binding falls on a spectrum. Let's take a look at some examples in C# of how we can "turn the dial" on early-to-late binding.

We begin with our example above of calling the static method X. This analysis is entirely, unambiguously early. There is no doubt at all that when Y is called, it is going to call the method D.X. No part of that analysis is deferred until runtime and the call will unambiguously succeed.

Next, consider:

class B
{
  public void M(double x) {}
  public void M(int x) {}
}
class C
{
  public static void X(B b, int d) { b.M(d); }
}

Now we know less. We do a lot of early binding here; we know that b is of type B and that the call is to B.M(int). But unlike the previous example, we have no guarantee from the compiler that this invocation will succeed. b could be null. We are essentially deferring the analysis of whether or not the receiver of the call is valid to the runtime to determine. One normally does not think of that as a "binding" decision though, because we are not associating syntax with a program element. Let's make the call in C; a little more late bound by changing B:

class B
{
  public virtual void M(double x) {}
  public virtual void M(int x) {}
}

We are now doing some binding analysis at compile time; we know that the invocation will be on the virtual method declared by B.M(int). We know that the call will succeed in the sense that there will be such a method to call. However, we do not know which method will actually be called at runtime! There could be a derived type that overrides that method; some completely other code could be called that appears nowhere in this program. Virtual dispatch is a form of late binding; the decision about which method to associate with the syntax b.M(d) is partially made by the compiler and partially made by the runtime.

How about this?

class C
{
  public static void X(B b, dynamic d) { b.M(d); }
}

Now the binding is almost entirely deferred until runtime. The compiler generates code that tells the Dynamic Language Runtime that static analysis has determined that the static type of b is B and that the method being invoked is called M, but the actual overload resolution to determine whether it is B.M(int) or B.M(double) (or neither, if d is, say, a string) is done by the runtime based on that information. (***)

class C
{
  public static void X(dynamic b, dynamic d) { b.M(d); }
}

Now the only portion of the binding performed early is the fact that this is a method call on a method named M. This is almost as late-bound as it gets, but we can in fact go one step further:

class C
{
  public static void X(object b, object[] d, string m, BindingFlags f)
  {
    b.GetType().GetMethod(m, f).Invoke(b, d);
  }
}

Now everything is late-bound; we don't even know what name we are going to be associating with a method. All we can possibly know is that the author of X expects that the object passed as b has a single method named by the string in m that match the flags in f, and that it takes the arguments given in d. There is nothing whatsoever we can do to analyze this call site at compile time. (****)


(*) Of course the output is encoded into a machine-readable binary format, rather than the human-readable CIL format.

(**) You might then ask whether "binding" and "semantic analysis" are not synonyms; surely semantic analysis is nothing more than the association of syntactic elements with their meanings! Binding is much of the semantic analysis phase of the compiler, but there are many analyses that we must perform after a method body is entirely "bound". Definite assignment analysis, for example, cannot by any reasonable stretch be called "binding"; it is not associating syntactic fragments with specific program elements. Rather, it is associating lexical locations with facts about program elements, facts like "the local variable blah is not definitely assigned at the beginning of this block". Similarly, optimizing arithmetic expressions is a form of semantic analysis but is clearly not "binding".

(***) The compiler could still do lots of static analysis here. For example, suppose B were a sealed class with no methods named M. Even with a dynamic argument to the call we could know statically that the runtime binding of M will always fail, and tell you that at compile time. And in fact the compiler does some such analyses; precisely how it does so is a good topic for another day.

(****) In some sense this example gives a counterexample to my definition of binding; we are no longer even associating a syntactic element with a method; we're associating the contents of a string with a method.

  Computer Zen  
The Web is the new Terminal: Are you using the Web's Keyboard Shortcuts and Hotkeys?

My gmail looks like a terminal if you squint

A V100 Terminal - Creative Commons via blakespot on FlickrNUI is OUI, Dear Reader. About eight years ago I blogged about "text mode" and said (if I may be silly and quote myself):

"I’m just saying that my Tab,Tab,Tab,Enter will beat your Click,Tab,Alt-F,O,Click,Double-Click, more often than not." - Me

I like to look at the computer systems of the businesses that I visit on a regular but spaced apart basis over the course of years. You know these businesses - your dentist, your eye doctor, the car shop that changes your oil, perhaps your bank or finance person. You see them every 3 to 6 months, or perhaps over a many years.

At my automotive shop, I watch them move from:

  • Keyboard heavy, very fast
    • VT100 Dumb Terminal
    • Windows running a VT100 Dumb Terminal Emulator
    • Netscape with Java running a VT100 Dumb Terminal plugin
  • Mouse heavy, very slow
    • Ugly gray HTML application in Netscape
    • Pretty AJAXy HTML application in Firefox
  • Keyboard heavy, very fast
    • Very terminal-like AJAXY HTML application in Firefox
    • ???

Tab, Tab, Enter is just the start. I propose that the interaction model for this "timeline" looks like somewhat like this.

Bell curve showing Mouse and Keyboard on Y Axis and Time on X axis. Curve shows most sites use mice. We need more using keyboards.

If you are an airline counter customer service person, you're going to want to touch the mouse as little as possible. Every keystroke counts, in fact, and this is one of the reason that every airline counter system I've ever seen is either a terminal itself or a browser window into a terminal. The interaction model for an airline workers apps needs to be terse and crisp and keyboard based because they are using it all day.

When Web Sites start to become Web Applications that are used every day they have to have keyboard shortcuts. More and more if you app doesn't have them you're going to limit your audience.

All my favorite web applications use keyboard shortcuts, and you'll notice that they are coalescing around a few common patterns:

  • J, K to move up and down
  • Enter to select or expand
  • G + some letter to Navigate (Goto)
  • / for Search
  • ? for keyboard help

There are two kinds of hotkeys on the web, though. There are "accesskeys" which have been in HTML since forever, then there's "hotkeys" that are application specific and often done with JavaScript bindings or jQuery plugins like jquery.hotkeys. Implementing these takes virutally no effort and can pay off hugely with your most discerning customers. Logical hotkeys can also turn beginners into enthusiasts.

<gratuitous bold="true">There is literally no reason to not implement keyboard hot-keys in your web application other than you've likely forgotten it's important.</gratuitous>

Access Keys

Implementing accesskey requires only the will and some thought.

<label for="homePhone">Home phone:</label>
<input name="HomePhone" type="text" maxlength="20" id="homePhone" accesskey="H" title="Home phone" class="text-box" />

Here we've made "ALT-H" go to the Home text box. Do you want awesome and automatic "KeyTips" to appear when the user presses ALT? Use the lovely KeyTips jQuery plugin (on NuGet also). Visit the KeyTips jQuery demo page and hold down ALT to see the key tips.

KeyTips for accesskeys as a jQuery plugin

Access Keys are very easy to setup and now give your 8-hours-a-day data entry user a huge gift and keeps their hands off the mouse. Make sure you do some user experience testing - even if only with yourself - and do some standard tasks with your web application and count both keystrokes and mouse touches.

Hot Keys

Slightly more complicated is adding Hot Keys via JavaScript but only slightly. John Resig's jQuery.Hotkeys is a simple plugin that lets you add and remove keyboard handlers for events in any browser supported combination.

// e.g. replace '$' sign with 'EUR'
$('input.foo').bind('keyup', '$', function(){
this.value = this.value.replace('$', 'EUR');
});

You can bind with selectors so that keys are captured on specific inputs, like the replace/expand example above, or you can bind (and unbind to the document with optional modifiers:

$(document).bind('keydown', 'ctrl+g', myfunc);

Sushant Bhatia has a great blog post (coincidentally written within minutes of mine, great minds think alike!) that talks about the importance of keyboard UX and how hotkeys are always preferable over tab, tab, tab.

Example Web Applications with Awesome Keyboard support

Here's some of the best examples I (and you, thanks Dear Reader for helping!) could find of great Keyboard support in Web Applications.

Twitter

I use these Twitter keyboard shortcuts all the time. You don't need to learn them all. Just use . for refresh, / for search and G-R for replies and you're already ahead of the pack.

Gmail

Gmail really gets credit for proving, in my opinion, that hotkeys on the web can be done elegantly and "just work." It may take a day or two but once you learn how to triage your email with just your keyboard you'll be surprised how fast you can get in and out and back to work.

I use J and K to navigate, X to select then # to delete or E to archive. Bam, bam, bam.

Gmail Hotkeys

Hotmail

Hotmail? Yes, while Hotmail drops the box by not including a help popup for the ? button, Hotmail not only supports their own keyboard shortcuts, but also familiar shortcuts from Gmail and Yahoo.

Windows Live Hotmail Hotkeys and Keyboard shortcuts

GitHub

Another example of a site you may be on for hours if it's part of your work. Github also supports ? for help and gives lots of shortcuts. Theirs are also J and K (which have meant up and down for folks familiar with vi and *nix editors) for moving up and down as well as X for toggling selection like Gmail, C for great, and / for search. You see how a pattern is developing on its own?

Some GitHub keyboard shortcuts

There doesn't appear to be a Help page with the list of Github keyboard shortcuts so for now, go over there, login and press ? to explore the complete list.

Jira Bug Tracker

Jira from Atlassian is a popular bug tracker with this same keyboard model. Every web application needs to include a web popup like this when ? is pressed.

Some Jira shortcuts

Remember The Milk

Remember The Milk is a web-based todo application with lots of mobile versions as well. However, they are best known by their web application which was very innovative when it first came out.

In fact, they were the first web application I ever used that actively marketed their application as being keyboard friendly. I love that we're at a time in the web where that is possible.

Remember The Milk has an extensive list of keyboad shortcuts

Asana

Asana is a team-focused shared todo list for projects and project management. They are super-focused on keyboard support and use it in all their promotional video AND think it is so important that they keep on the screen all the time! Classy.

Asana's Keyboard shortcuts are front and center

And they have LOTS, very logical and organized.

image

Trello

Trello's up and coming project management board software also leans heavily on hotkeys.

image

YouTrack

YouTrack from JetBrains says this about itself: "YouTrack is a keyboard-centric application and provides enough keyboard support to let you forget about using the mouse in most cases." Sassy!

Personally, I'm moving away from the Ctrl-Alt-This and That and prefer simpler hotkeys.

A subset of YouTrack Hotkeys

And as this isn't an exhaustive list but rather a long list to make a point, how about DuckDuckGo.

DuckDuckGo

The little search engine that could, DuckDuckGo includes keyboard shortcuts not just to move around search results but also another unusual keyboard-centric feature they called !Bang.

I keep DuckDuckGo.com as my home page. If I want to search them, I search. If I want to search Bing I type "hanselman b!" or Google with "hanselman g!" or hundreds of other sites like "hanselman image!" or even super specific site searches like "hanselman csharp!"

Now THAT'S keyboard friendly.

image

Conclusion

Like it or not, there's a standard brewing on the web. Not only should you have accesskey support (should have done this years ago) but also extensive keyboard shortcuts if you expect your users to spend serious time with your application.

At the very least, I think it's fair to say that these are de facto standard shortcuts now on the web and you should think about what that means for your application:

  • J, K to move up and down
  • Enter to select or expand
  • G + some letter to Navigate (Goto)
  • / for Search
  • ? for keyboard help

Good shortcuts mean happy and engaged users.



© 2012 Scott Hanselman. All rights reserved.
  ISV Developer Community  
MSDN Article: Building a Massively Scalable Platform for Consumer Devices on Windows Azure

WinAzure_rgbExcellent article shows how you can use web services hosted in Windows Azure and have it communicate across various devices, such as Windows Phone, iPhone, and Android. And have that service scale to terabytes in size.

My colleagues Bruno Terkaly and Ricardo Villalobos wrote the article for MSDN magazine Building a Massively Scalable Platform for Consumer Devices on Windows Azure.

...(read more)
  Mike Taulty  
Silverlight 5 Released
Silverlight 5 has been released today – you can find the official announcement over on the Silverlight site along with a link to the download and a list of the improvements in Silverlight 5 up on MSDN including features like; platform invocation integration...(read more)
  Rands In Repose  
A Design Primer for Engineers
For a word that can so vastly change the fortunes of a company, it's worth noting that no generally accepted definition of the word design exists. This means when your boss stands up in front of the team at that...
  You Had Me at 'Hello World'   
AppRating Updated For Mango

Download source code here: http://nokola.com/sources/apprating.zip

Under MS-RL License: http://www.opensource.org/licenses/ms-rl

The app is available at the marketplace too!

Many thanks to Erwin Seinen for updating it and sending me back the source code! Check out his apps (as of this writing, Latitude and Hand Warmer, maybe more) here: Nenies Apps

  Four Guys From Rolla  
Use MvcContrib Grid to Display a Grid of Data in ASP.NET MVC

The past six articles in this series have looked at how to display a grid of data in an ASP.NET MVC application and how to implement features like sorting, paging, and filtering. In each of these past six tutorials we were responsible for generating the rendered markup for the grid. Our Views included the <table> tags, the <th> elements for the header row, and a foreach loop that emitted a series of <td> elements for each row to display in the grid. While this approach certainly works, it does lead to a bit of repetition and inflates the size of our Views.

The ASP.NET MVC framework includes an HtmlHelper class that adds support for rendering HTML elements in a View. An instance of this class is available through the Html object, and is often used in a View to create action links (Html.ActionLink), textboxes (Html.TextBoxFor), and other HTML content. Such content could certainly be created by writing the markup by hand in the View; however, the HtmlHelper makes things easier by offering methods that emit common markup patterns. You can even create your own custom HTML Helpers by adding extension methods to the HtmlHelper class.

MvcContrib is a popular, open source project that adds various functionality to the ASP.NET MVC framework. This includes a very versatile Grid HTML Helper that provides a strongly-typed way to construct a grid in your Views. Using MvcContrib's Grid HTML Helper you can ditch the <table>, <tr>, and <td> markup, and instead use syntax like Html.Grid(...). This article looks at using the MvcContrib Grid to display a grid of data in an ASP.NET MVC application. A future installment will show how to configure the MvcContrib Grid to support both sorting and paging. Read on to learn more!
Read More >

  West End Whingers  
Review – Master Class, Vaudeville Theatre
If the Whingers were writing nine word reviews (dream on) then an overheard from a precise elderly gentleman at the interval of Master Class might suffice; “She was a bit of a diva wasn’t she?” Quite. The Whingers found no challenge camouflaging themselves amongst the throng of gentlemen d’un certain âge cramming this Broadway transfer at [...]
  A List Apart  
Responsive Images: How they Almost Worked and What We Need
With a mobile-first responsive design approach, if any part of the process breaks down, your user can still receive a representative image and avoid an unnecessarily large request on a device that may have limited bandwidth. But with several newer browsers implementing an “image prefetching” feature that allows images to be fetched before parsing the document’s body, some of the web's brightest developers are abandoning responsive images in favor of user agent detection, at least as a temporary solution. For us standardistas, UA detection leaves a bad taste in the mouth. More importantly, as the number and kinds of devices continue to grow, UA detection will quickly become untenable—just as browser detection did back in the bad old days before web standards. What's really needed, argues Mat Marquis, is a new markup element that works the way the HTML5 video element works. Sound crazy? So crazy it just might work.
  Article of the Day  
Keep ASP.NET Error Pages out of Search Engines
In a production environment, users should not be presented the default ASP.NET error pages. Instead they should be offered clean, understandable error pages giving them a sensible explanation of the error, along with suggestions to continue their journey on the website. Besides usability concerns, it's also an important security practice to not leak details about application details to those who might tinker with your application!
  Soma Segar Says  
C++ AMP Open Specification

As an industry trend, advancement in heterogeneous hardware has progressed at a rapid pace.  This in turn has fueled developer desire to target such hardware for accelerated computation, necessitating a significant step forward in programming models to enable such practices. 

C++ Accelerated Massive Parallelism (C++ AMP) is a new technology implemented in Visual Studio 11 that helps C++ developers use accelerators such as the GPU for parallel programming. I’ve blogged about it since its initial disclosure, including discussing our intention to share the C++ AMP specification so as to help bring general purpose GPU programming to all C++ developers, regardless of whether they’re using Visual C++. I am excited today to deliver on that commitment.

Today at the GoingNative 2012 event, Microsoft announced publication, under the Microsoft Community Promise license, of the C++ AMP open specification. This release means compiler developers and vendors now have the ability to implement C++ AMP in their compilers, just as Microsoft has done, broadening access for C++ developers everywhere to the possibilities offered by heterogeneous hardware.

Please send any feedback you have on this to the C++ AMP team via their blog.

Namaste!