Archive Page 3

01
Apr

String Input Handling + Quantum Mechanics!

One of my biggest complaints with the .NET Framework is its horrible support (or lack thereof) for handling string input. If you have an application that allows a user to enter arbitrary content, there is no single way to “project” that content into its appropriate data type, without having to write a ton of boilerplate code.

At first glance, you might think this is an easy problem to solve, and in some instances you’d be right, but the devil is most certainly in the details (as in figuring out quantum physics!). If you’re looking to be able to handle an infinite number of different data types, and generically interpret any possible form of input, then you’ve got quite a serious problem on your hands.

Thankfully this problem ends today. In addition to developing the recently released ASP.NET MVC framework, Phil Haack and Eilon Lipton have also been hard at work addressing the global issue of string input handling and quantum entanglement. This afternoon, the first public CTP of the new “String Input Handling Framework” (name pending) has been released. As much as I’d love to go on about how to use it, and how integral it will become in all future .NET development, Eilon has already put together a great blog post on this subject.

All I can say is: with innovative solutions like this under Microsoft’s belt, there is no question just how superior the .NET Framework is to everything else on the market. Move over Ruby, PHP, Python, Java, and everyone else (you know who you are), the .NET train is coming through, and we’ll be accepting any input you’ve got to throw at us!

12
Feb

Dynamic Data: Putting A New Dress On An Old Model

Now that we’ve spent the last five articles spelunking into the glorious underbelly of the Dynamic Data runtime, and seeing what it offers, we need to begin investigating how to allow a MetaModel to “light up” our UI. Everything that we’ve seen up to this point is completely agnostic to any specific presentation framework. Dynamic Data (as a runtime) simply provides the infrastructure for translating a data model, complete with metadata and validation, into a higher level model (MetaModel) that has the potential to be interpreted by an application.

Within the .NET 3.5 SP1 release, the initial consumer of Dynamic Data (and the newly introduced data annotations) was ASP.NET WebForms. This means that if you’re developing a data-driven web application, and your weapon of choice is WebForms, then you just happen to be in luck. Work is already underway to introduce some of Dynamic Data’s behavior into ASP.NET MVC that is appropriate to its style of development, and you can expect to see additional UI frameworks taking advantage of its semantics and data annotations as well in the near future.

So, the question becomes: now that I’ve got my data model, and I registered it with a MetaModel, how can I begin taking advantage of it within a WebForms application? Since it is the MetaModel that contains all of the metadata and validation, as well as the shape of our underlying data model, reason would lead us to believe that we’d need some type of server-control that was aware of a MetaModel and is ready to allow it to affect its behavior.

If you were to begin developing a data-centric WebForms application today, what are your options as far as server controls go? There’s actually a pretty rich arsenal of controls that can get you up and running pretty quickly, without having to sacrifice functionality…

Data Controls:
  1. GridView
  2. ListView
  3. FormView
  4. DetailsView
  5. DataPager
  6. Repeater
Data Sources:
  1. ObjectDataSource
  2. LinqDataSource
  3. EntityDataSource
  4. SqlDataSource
  5. AccessDataSource
  6. XmlDataSource

All of those controls are awesome in their own way but they don’t exactly help us in our current endeavor. Not a single one of them has a clue what a MetaModel is or is really conscious of what being “data-driven” means. They support the notion of metadata and validation, but we have to explicitly define that information, instead of them deriving it from our data model.

While these controls lack some of the functionality we require we certainly don’t want to have to introduce a whole new suite of controls that we have to learn just to enable data-centric applications. What would be ideal is if we could extend or enhance the functionality that these controls already have to make them more fully-featured and MetaModel-aware. Luckily this is exactly what Dynamic Data provides, in the form of the following controls:

  1. DynamicField
  2. DynamicControl
  3. DynamicControlParameter
  4. DynamicQueryStringParameter
  5. DynamicDataManager
  6. DynamicValidator
  7. FieldTemplateUserControl

While these new controls provide a lot of the functionality we’ll need, there is still one piece left to complete our little journey towards data-driven utopia: field-level templates. Since our focus is on the data in our application and the metadata that is associated with that data, a lot of times we might want to allow the presentation framework to determine how to render portions of our data automatically based on the structure of the data model, or better yet, the MetaModel.

These field-level templates could define the UI desired to display data of different types. This would allow us to determine how we wanted numbers, string, dates, etc. to look, in a single location, and have those templates leveraged throughout our entire application. Regardless whether we were creating tabular or form-based data entry forms, we could take advantage of the same templates, providing a consistent look and feel that is completely driven from our data model.

The FieldTemplateUserControl is what makes this functionality possible, and will be the focus of the next article. We’ll cover how it can be used to define custom field templates, as well as what field templates are provided out-of-the-box by Dynamic Data. Finally, we’ll cover how to wire-up your defined field templates to actually be used with your created MetaModel, effectively completing the field-level templating story (which is one of two possible scenarios provided by Dynamic Data).

18
Dec

Dynamic Data: Associated Types And The Models They Love

In the last article we introduced the ContextConfiguration class and its MetadataProviderFactory property. We also saw that if a provider factory isn’t explicitly set then an instance of the AssociatedMetadataTypeTypeDescriptorProvider class will be used. What we didn’t discuss is what an “associated metadata type” is, and why we need a type descriptor for working with it. Before going into those exact questions, we need to take a step back and examine the way some models are constructed.

We can all agree that the term “model” is pretty overloaded and has many different meanings/interpretations. You have domain models, presentation models, view models, super models, model trains, and so forth and so on. This series isn’t tied to any specific model implementation methodology per se, but rather on the intent of creating web applications that are focused around data in a RAD fashion. Because there are numerous ways of constructing an object model, we’d need a mechanism for discovering metadata from models that assume different shapes.

If you hand-craft your object model and perform the database-mapping yourself you could easily place data annotations on your entity classes and go on with it (as you might do if using NHibernate). While that is a totally valid scenario, it isn’t necessarily the right one for a data-driven application where you most likely already have a database in place and are looking to reverse engineer a model from it’s schema. For cases like that you might use something like LINQ To SQL or the Entity Framework, both of which provide designers/wizards for generating a mapped model to an existing database.

If I create a new Entity Data Model and point its wizard at an AdventureWorks database, I’ll end up with a whole bunch of generated entity classes that look something like this:

[global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="AdventureWorks", Name="Address")] 
[global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] 
[global::System.Serializable()] 
public partial class Address : global::System.Data.Objects.DataClasses.EntityObject 
{ 
    ... 
}

Because that class lives within the confines of my EDMX, which is template-generated code, I don’t exactly want to go mucking around in there. If I later make a change with the designer, it would wipe out any changes I manually made to the entity classes, which would lead to a lot of pain and frustration. Luckily though, the entities are generated as partial classes which means we can make modifications to them from outside of the EDMX’s code files. This gives us the ability to leverage the designer and still have some level of flexibility over the codebase moving forward.

I can easily create a new partial class for my Address entity and begin placing some data annotations on it. Let’s say that I want to specify that the display name for it should be “Customer Address” and that the column (property) that should be used to represent it’s display value should be “Country”. I could easily do this:

[DisplayColumn("Country")] 
[DisplayName("Customer Address")] 
public partial class Address 
{ 
}

Because we’re using partial classes (which are combined at compile time), we’re still annotating the entity class itself, just using a different approach. We could easily retreive this metadata using standard reflection without requiring the need for a custom type descriptor. But what if I wanted to add metadata to one of the properties of my Address entity now? Let’s say that I wanted to specify that the Address2 property is required (even though it isn’t at the database level), PostalCode should be constrained by a regular expression, and that CountryRegion’s display name should just be “Country”. Because I don’t want to mess with the generated code of the EDMX I can’t go place data annotations directly on those properties. I definitely can’t do the following, since that would be declaring the properties twice on the same class:

[DisplayColumn("Country")] 
[DisplayName("Customer Address")] 
public partial class Address 
{ 
    public string Address2 { get; set; } 
    public string CountryRegion { get; set; } 
    public string PostalCode { get; set; } 
}

It might seem like we’re out of luck at this point and have to settle with changing the generated EDMX code. What if though, we could create a class whose sole purpose was to contain properties that we could annotate with metadata for another entity and then associate the two together? That would get us the functionality we need and work around the “issue” we’re dealing with between partial classes and generated code. Let’s say we created the following AddressMetadata class:

private class AddressMetaData 
{ 
    public string Address2 { get; set; } 
    public string CountryRegion { get; set; } 
    public string PostalCode { get; set; } 
}

We don’t get any compiler errors (obviously) so we’re moving in the right direction. How can we then associate this new type with our original Address entity class?

[MetadataType(typeof(AddressMetaData))] 
public partial class Address 
{

Now we can place any entity-level metadata on our Address partial class, and any property-level metadata on our new AddressMetaData class, because the two are associated. You can place/name your metadata type anywhere you want, but I prefer to make it a private/embedded class of the partial entity class itself. I can now add the metadata I want to my properties.

[DisplayColumn("Country")] 
[DisplayName("Customer Address")] 
[MetadataType(typeof(AddressMetaData))] 
public partial class Address 
{ 
    private class AddressMetaData 
    { 
        [Required] 
        public object Address2 { get; set; } 
 
        [DisplayName("Country")] 
        public object CountryRegion { get; set; } 
 
        [RegularExpression(@"\d{5}(-\d{4})?")] 
        public object PostalCode { get; set; } 
    } 
}

Notice that I changed the type of the three properties to “object” because the property type no longer matters. Within the metadata type, we only need to be concerned with naming the property correctly.

We established that standard reflection could handle the discovery of the entity-level metadata, but now that we’ve created this “metadata type” which has its own set of properties and metadata, reflection would have no clue of its semantic association with the Address entity. This is where the AssociatedMetadataTypeTypeDescriptionProvider comes in.

The AssociatedMetadataTypeTypeDescriptionProvider class is capable of looking at a type and finding any of its class-level attributes as well as looking to see if that type has an associated metadata type (via the MetadataType attribute) and if it does, grabbing any metadata from the metadata type’s properties. This is a fairly roundabout approach, but it gets us around in the meantime. In the future you might see the notion of “partial properties” that would remove the need for the metadata type altogether.

So now it’s clear why the AssociatedMetadataTypeTypeDescriptionProvider exists and is the default behavior. If our model is able to apply all metadata directly to the entity classes, then it will work great. If our model requires the use of a “associated metadata type”, then it will also pick up on that as well. If we had an alternate style of model, that required a different type of metadata discovery, then we could implement a TypeDescriptionProvider and set it via the ContextConfiguration’s MetadataProviderFactory property. Dynamic Data uses the specified provider throughout its entire API, making it extremely easy to swap our your model metadata discovery logic.

Now that we’ve got our model created and we’ve begun adding metadata to it, how can we start seeing the fruits of our labor take effect within our web application’s UI? In the next article I’ll begin showing how Dynamic Data provides a set of extensions to ASP.NET that can take advantage of your annotated models and the MetaModels derived from them.

16
Dec

Dynamic Data: Annotating Your Data-Driven World

In the last article we discussed how a MetaModel could derive some of its metadata content from its respective provider’s underlying data model (i.e. an EDM), but also mentioned that there is a lot of valuable information that can’t necessarily be deduced from every data model type. Because a data model can come in any shape or form (i.e. EF, L2S, NHibernate, etc) it becomes tricky to try to interpret metadata in any sort of consistent fashion. Providers make an attempt at doing this, but really, their job isn’t to curry metadata back and forth between the MetaModel and underlying data model, but rather to shape the data model in such a way that the MetaModel can understand it.

Without a standard approach for adding metadata to data models (of any kind), data-driven UI frameworks would have a hard time providing the rich functionality we are demanding from them. By introducing the MetaModel, we’ve given the UI layer a robust view of the underlying data model such that it can provide the behavior we expect, so that problem is already solved. Now we just need a mechanism for annotating our model with metadata in such a way that our MetaModel can pick it up.

The .NET Framework 3.5 SP1 release contained an assembly named System.ComponentModel.DataAnnotations. Within that assembly is a collection of attributes that are meant to be associated with data models for the purpose of adding additional metadata and validation to them in a way that is agnostic to any specific UI framework. Notice that the namespace they live in isn’t “System.Web.*” or “System.Windows.*” but rather “System.ComponentModel.*”, which adds to the argument of standard use.

Because these data annotations are simply attributes, we can easily begin attaching them to our entity classes and properties, which adds additional information to our model such as validation constraints (range, regular expression, string length, etc.) and higher level semantics (data type, UI hint, scaffolding, etc.). The question is: how does our MetaModel discover these annotations once we’ve placed them on our model?

[DisplayColumn("FirstName", "LastName")]
public class Customer
{
    [Required]
    public string FirstName { get; set; }
 
    [StringLength(20)]
    public string MiddleName { get; set; }
 
    [Required]
    public string LastName { get; set; }
 
    [Range(18, 30)]
    public int Age { get; set; }
}

For any DDD proponents, I realize the above model class would be considered anemic. It’s important to keep in mind that the methodology being employed in this series is that of data-driven applications not domain-driven.

When you register a context/provider with a MetaModel (as we saw in a previous post), an instance of type ContextConfiguration is created and associated with your model. You can either explicitly create a ContextConfiguration instance and use one of the overloaded versions of the RegisterContext method that accepts one, or you can allow the MetaModel to create one for you. ContextConfiguration is an extremely simple class that contains only two properties: ScaffoldAllTables and MetadataProviderFactory. The ScaffoldAllTables property is only applicable if you’re leveraging Dynamic Data for full-blown scaffolding, which is a scenario we’ll touch on later.

// Implict ContextConfiguration...
var model = new MetaModel();
model.RegisterContext(typeof(AdventureWorksContext));
 
// Explicit ContextConfiguration...
var model2 = new MetaModel();
model2.RegisterContext(typeof(AdventureWorksContext),
                      new ContextConfiguration { ScaffoldAllTables = false });

The ScaffoldAllTables property defaults to false, so if we aren’t concerned with Dynamic Data’s scaffolding behavior (which in this case we aren’t), we can just omit that property instead of explicitly setting it.

The MetadataProviderFactory property is of type Func<Type, TypeDescriptionProvider>, which might look scarier than it actually is. Func is simply a generic delegate that returns a value and optionally takes up to four parameters (there are five variations of Func). In this case we’re dealing with a Func that will accept a parameter of type Type and return an object of type TypeDescriptionProvider. When we register a context/provider with a MetaModel, it will enumerate through every entity type in our model, calling the delegate within the ContextConfiguration’s MetadataProviderFactory property, which will then return an TypeDescriptionProvider.

model.RegisterContext(typeof(AdventureWorksContext),
                       new ContextConfiguration
                       {
                           MetadataProviderFactory = (type) => new CustomTypeProvider()
                       });

A TypeDescriptionProvider is (as you can probably guess) responsible for providing a type descriptor (more specifically an object that implements ICustomTypeDescriptor or inherits from CustomTypeDescriptor). An ICustomTypeDescriptor implementation is able to determine information about a type such as its properties, events, attributes, etc. This allows applications to use a type descriptor to retrieve metadata about a type instead of using reflection directly. Why is this useful? Because you could create a custom ICustomTypeDescriptor that represented the shape of a type differently then it is in code.

As was mentioned above, the standard data annotations are provided as attribute classes, so the fact that a type descriptor allows you to retrieve attributes from a type (as well as that type’s properties), makes it very useful. By being able to create a custom TypeDescriptionProvider we can effectively implement logic that retrieves our model metadata from any source (i.e. XML, database, etc.), but uses the same standard data annotations, giving us both consistency and flexibility.

If you don’t explicitly set the MetadataProviderFactory property, the Metamodel will internally create an instance of the AssociatedMetadataTypeTypeDescriptionProvider class (that is a hell of a name!). This TypeDescriptionProvider implementation simply retrieves all attributes for a type via reflection. Why is this any better than just using reflection directly? Because it also retrieves any attributes from the requested type’s associated metadata type as well.

What exactly does “associated metadata type” mean? And why is it beneficial that the TypeDescriptionProvider be able to retrieve its attributes? We’ll discuss these two questions and expand on the usage of data annotations in the next article.

10
Dec

Top 50 Albums of 2008 (…By "Top" I Mean "My Favorite")

I wasn’t going to do this post but I ended up not being able to sleep last night and decided “what the hell?”. I purposely did the list in no particular order as I feel that it isn’t realistic to quantify a specific placement of each album and have it mean anything. What exactly does the difference between #18 and #19 really look like? I spent many years writing for magazines and can attest to the fact that these lists are just subjective babble.

The majority of these albums are post-rock, electronic and instrumental artists. There are a few metal, indie, folk and post-hardcore albums as well. I did a TON of traveling this year and this is the collection that kept me sane around the world. If you care for a more “formal” list, you can check out my other site, The Silent Ballet, in a few weeks.

  1. Helios - “Ceasura” (Link)
  2. Lights Out Asia - “Eyes Like Brontide” (Link)
  3. Shearwater - “Rook” (Link)
  4. No.9 - “Usual Revolution And Nine” (Link)
  5. Sumner McKane - “What A Great Place To Be” (Link)
  6. Suffocate For Fuck Sake - “Blazing Fires And Helicopters On The Front Page Of The Newspaper. There’s A War Going On And I’m Marching In Heavy Boots” (Link)
  7. Bersarin Quartett - “Bersarin Quartett” (Link)
  8. This Town Needs Guns - “Animals” (Link)
  9. Jóhann Jóhannsson - “Fordlandia” (Link)
  10. Cult Of Luna - “Eternal Kingdom” (Link)
  11. This Is Your Captain Speaking - “Eternal Return” (Link)
  12. Up-C Down-C Left-C Right-C ABC + Start - “Embers” (Link)
  13. Balmorhea - “River Arms” (Link)
  14. Strangers Die Every Day - “Aperture For Departure” (Link)
  15. Takahiro Kido - “Fleursy Music” (Link)
  16. M83 - “Saturdays = Youth” (Link)
  17. Mouth Of The Architect - “Quietly” (Link)
  18. Lakes Of Russia - “Stars Decorate The Fire” (Link)
  19. Earth - “The Bees Made Honey In The Lion’s Skull” (Link)
  20. Fuck Buttons - “Street Horrrsing” (Link)
  21. The Drift - “Memory Drawings” (Link)
  22. Beneva Vs. Clark Nova - “Sombunall” (Link)
  23. Mooncake - “Langrange Points” (Link)
  24. We’re From Japan! - “Now Breath” (Link)
  25. The Evpatoria Report - “Maar” (Link)
  26. Arms & Sleepers - “Black Paris 86″ (Link)
  27. d_rradio - “d_rradio” (Link)
  28. Gregor Samsa - “Rest” (Link)
  29. Russian Circles - “Station” (Link)
  30. Ef - “I Am Responsible” (Link)
  31. Pg.Lost - “It’s Not Me, It’s You!” (Link)
  32. Neil On Impression - “L’oceano Delle Onde Che Restano Onde Per Sempre” (Link)
  33. He Can Jog - “Middlemarch” (Link)
  34. The Seven Mile Journey - “The Metamorphosis Project” (Link)
  35. Goodnight, Sleep Well - “The Recovery” (Link)
  36. Kyte - “Kyte” (Link)
  37. Unwed Sailor - “Little Wars” (Link)
  38. Daturah - “Reverie” (Link)
  39. Port Blue - “The Albatross” (Link)
  40. My Education - “Bad Vibrations” (Link)
  41. Build - “Build” (Link)
  42. God Is An Astronaut - “God Is An Astronaut” (Link)
  43. MGMT - “Oracular Spectacular” (Link)
  44. Lindstrøm - “Where You Go I Go Too” (Link)
  45. September Malevolence - “After This Darkness, There’s A Next” (Link)
  46. The Absent Sound - “Gathering Of The Clan Mothers” (Link)
  47. The Calm Blue Sea - “The Calm Blue Sea” (Link)
  48. Beast, Please Be Still! - “Beast, Please Be Still!” (Link)
  49. Robin Guthrie - “3:19 Bande Originale du Film” (Link)
  50. Peter Broderick - “Float” (Link)




July 2010
S M T W T F S
« Jun    
 123
45678910
11121314151617
18192021222324
25262728293031

Categories