Logo

Maarten Balliauw {blog}

ASP.NET, ASP.NET MVC, Azure, PHP, OpenXML, VSTS, ...

About the author

Maarten Balliauw is an MVP ASP.NET and is currently employed as .NET Software Engineer at RealDolmen. His interests are mainly web applications developed in ASP.NET (C#) or PHP.
More about me More about me
Send mail E-mail me


Microsoft Most Valuable Professional - MVP - ASP.NET

Subscribe to my RSS feed Follow me on Twitter! View Maarten Balliauw's profile on LinkedIn RealDolmen - Rock-solid passion for ICT
I'm a speaker at TechDays Belgium and TechDays Finland

Search

Latest Twitter

    Follow me on Twitter...

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

    © Copyright Maarten Balliauw 2010

    MEF will not get easier, it’s cool as ICE

    Over the past few weeks, several people asked me to show them how to use MEF (Managed Extensibility Framework), some of them seemed to have some difficulties with the concept of MEF. I tried explaining that it will not get easier than it is currently, hence the title of this blog post. MEF is based on 3 keywords: export, import, compose. Since these 3 words all start with a letter that can be combined to a word, and MEF is cool, here’s a hint on how to remember it: MEF is cool as ICE!

    kick it on DotNetKicks.com

    Imagine the following:

    You want to construct a shed somewhere in your back yard. There’s tools to accomplish that, such as a hammer and a saw. There’s also material, such as nails and wooden boards.

    Let’s go for this! Here’s a piece of code to build the shed:

    public class Maarten
    {
        public void Execute(string command)
        {
            if (command == “build-a-shed”)
            {
              List<ITool> tools = new List<ITool>
              {
                new Hammer(),
                new Saw()
              };

              List<IMaterial> material = new List<IMaterial>
              {
                new BoxOfNails(),
                new WoodenBoards()
              };

              BuildAShedCommand task = new BuildAShedCommand(tools, material);
              task.Execute();
            }
        }
    }

    That’s a lot of work, building a shed! Imagine you had someone to do the above for you, someone who gathers your tools spread around somewhere in the house, goes to the DIY-store and gets a box of nails, … This is where MEF comes in to place.

    Compose

    Let’s start with the last component of the MEF paradigm: composition. Let’s not look for tools in the garage (and the attic), let’s not go to the DIY store, let’s “outsource” this task to someone cheap: MEF. Cheap because it will be in .NET 4.0, not because it’s, well, “cheap”. Here’s how the outsourcing would be done:

    public class Maarten
    {
        public void Execute(string command)
        {
            if (command == “build-a-shed”)
            {
              // Tell MEF to look for stuff in my house, maybe I still have nails and wooden boards as well
              AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
              CompositionContainer container = new CompositionContainer(catalog);

              // Start the job, and ask MEF to find my tools and material
              BuildAShedCommand task = new BuildAShedCommand();
              container.ComposeParts(task);
              task.Execute();
            }
        }
    }

    Cleaner, no? The only thing I have to do is start the job, which is more fun when my tools and material are in reach. The ComposeParts() call figures out where my tools and material are. However, MEF's stable composition promise will only do that if it can find ("satisfy") all required imports. And MEF will not know all of this automatically. Tools and material should be labeled. And that’s where the next word comes in play: export.

    Export

    Export, or the ExportAttribute to be precise, is a marker for MEF to tell that you want to export the type or property on which the attribute is placed. Really think of it like a label. Let’s label our hammer:

    [Export(typeof(ITool))]
    public class Hammer : ITool
    {
      // ...
    }

    The same should be done for the saw, the box of nails and the wooden boards. Remember to put a different label color on the tools and the material, otherwise MEF will think that sawing should be done with a box of nails.

    Import

    Of course, MEF can go ahead and gather tools and material, but it will not know what to do with it unless you give it a hint. And that’s where the ImportAttribute (and the ImportManyAttribute) come in handy. I will have to tell MEF that the tools go on one stack, the material goes on another one. Here’s how:

    public class BuildAShedCommand : ICommand
    {
      [ImportMany(typeof(ITool))]
      public IEnumerable<ITool> Tools { get; set; }

      [ImportMany(typeof(IMaterial))]
      public IEnumerable<IMaterial> Materials { get; set; }

      // ...
    }

    Conclusion

    Easy, no? Of course, MEF can do a lot more than this. For instance, you can specify that a certain import is only valid for exports of a specific type and specific metadata: I can have a small and a large hammer, both ITool. For building a shed, I will require the large hammer though.

    Another cool feature is creating your own export provider (example at TheCodeJunkie.com). And if ICE does not make sense, try the Zoo example.

    kick it on DotNetKicks.com


    Supporting multiple submit buttons on an ASP.NET MVC view

    Multiple buttons on an ASP.NET MVC view A while ago, I was asked for advice on how to support multiple submit buttons in an ASP.NET MVC application, preferably without using any JavaScript. The idea was that a form could contain more than one submit button issuing a form post to a different controller action.

    The above situation can be solved in many ways, one a bit cleaner than the other. For example, one could post the form back to one action method and determine which method should be called from that action method. Good solution, however: not standardized within a project and just not that maintainable… A better solution in this case was to create an ActionNameSelectorAttribute.

    Whenever you decorate an action method in a controller with the ActionNameSelectorAttribute (or a subclass), ASP.NET MVC will use this attribute to determine which action method to call. For example, one of the ASP.NET MVC ActionNameSelectorAttribute subclasses is the ActionNameAttribute. Guess what the action name for the following code snippet will be for ASP.NET MVC:

    public class HomeController : Controller
    {
        [ActionName("Index")]
        public ActionResult Abcdefghij()
        {
            return View();
        }
    }

    That’s correct: this action method will be called Index instead of Abcdefghij. What happens at runtime is that ASP.NET MVC checks the ActionNameAttribute and asks if it applies for a specific request. Now let’s see if we can use this behavior for our multiple submit button scenario.

    kick it on DotNetKicks.com

    The view

    Since our view should not be aware of the server-side plumbing, we can simply create a view that looks like this.

    <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcMultiButton.Models.Person>" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "//www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Create person</title>
        <script src="<%=Url.Content("~/Scripts/MicrosoftAjax.js")%>" type="text/javascript"></script>
        <script src="<%=Url.Content("~/Scripts/MicrosoftMvcAjax.js")%>" type="text/javascript"></script>
    </head>
    <body>

        <% Html.EnableClientValidation(); %>
        <% using (Html.BeginForm()) {%>

            <fieldset>
                <legend>Create person</legend>
                <p>
                    <%= Html.LabelFor(model => model.Name) %>
                    <%= Html.TextBoxFor(model => model.Name) %>
                    <%= Html.ValidationMessageFor(model => model.Name) %>
                </p>
                <p>
                    <%= Html.LabelFor(model => model.Email) %>
                    <%= Html.TextBoxFor(model => model.Email) %>
                    <%= Html.ValidationMessageFor(model => model.Email) %>
                </p>
                <p>
                    <input type="submit" value="Cancel" name="action" />
                    <input type="submit" value="Create" name="action" />
                </p>
            </fieldset>

        <% } %>

        <div>
            <%=Html.ActionLink("Back to List", "Index") %>
        </div>

    </body>
    </html>

    Note the two submit buttons (namely “Cancel” and “Create”), both named “action” but with a different value attribute.

    The controller

    Our controller should also not contain too much logic for determining the correct action method to be called. Here’s what I propose:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Person());
        }

        [HttpPost]
        [MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
        public ActionResult Cancel()
        {
            return Content("Cancel clicked");
        }

        [HttpPost]
        [MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
        public ActionResult Create(Person person)
        {
            return Content("Create clicked");
        }
    }

    Some things to note:

    • There’s the Index action method which just renders the view described previously.
    • There’s a Cancel action method which will trigger when clicking the Cancel button.
    • There’s a Create action method which will trigger when clicking the Create button.

    Now how do these last two work… You may also have noticed the MultiButtonAttribute being applied. We’ll see the implementation in a minute. In short, this is a subclass for the ActionNameSelectorAttribute, triggering on the parameters MatchFormKey and MatchFormValues. Now let’s see how the MultiButtonAttribute class is built…

    The MultiButtonAttribute class

    Now do be surprised of the amount of code that is coming…

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class MultiButtonAttribute : ActionNameSelectorAttribute
    {
        public string MatchFormKey { get; set; }
        public string MatchFormValue { get; set; }

        public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
        {
            return controllerContext.HttpContext.Request[MatchFormKey] != null &&
                controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
        }
    }

    When applying the MultiButtonAttribute to an action method, ASP.NET MVC will come and call the IsValidName method. Next, we just check if the MatchFormKey value is one of the request keys, and the MatchFormValue matches the value in the request. Simple, straightforward and re-usable.

    kick it on DotNetKicks.com


    Book review: Zend Framework 1.8 Web Application Development

    Zend Framework 1.8 Web Application Development My book shelf is starting to look a lot like the warehouse of Packt Publishing: I’ve received yet another book from them. Different from all previous reviews I did: this one is a PHP book, titled “Zend Framework 1.8 Web Application Development” by Keith Pope.

    A chapter overview:

    • Chapter 1: Creating a Basic MVC Application
    • Chapter 2: The Zend Framework MVC Architecture
    • Chapter 3: Storefront Basic Setup
    • Chapter 4: Storefront Models (great chapter!)
    • Chapter 5: Implementing the Catalog
    • Chapter 6: Implementing User Accounts
    • Chapter 7: The Shopping Cart
    • Chapter 8: Authentication and Authorization
    • Chapter 9: The Administration Area
    • Chapter 10: Storefront Roundup
    • Chapter 11: Storefront Optimization
    • Chapter 12: Testing the Storefront

    Let’s also state the obvious: Zend Framework evolves much faster than publishers. The framework is now at 1.9.6, while the book covers 1.8.0. Do not let this stop you from reading this book! Let me explain why…

    1. The book covers all concepts and components in the Zend Framework in a full-blown application that is built up from scratch.
    2. Next to that, Keith Pope focuses a lot on the application design, using interfaces, unit testing, mocking, dependency injection, … Want to learn a lot about good application design? Then this is the number one reason to read this book!

    These 2 points actually summarize the whole book. Great read, great content and a must-read for everyone who is not completely sure about his application design skills. Congratulations, Keith!


    ASP.NET MVC Chained Controller Factory

    My last post on the REST for ASP.NET MVC SDK received an interesting comment… Basically, the spirit of the comment was: “There are tons of controller factories out there, but you can only use one at a time!”. This is true. One can have an IControllerFactory for MEF, for Castle Windsor, a custom one that creates a controller based on the current weather, … Most of the time, these IControllerFactory  implementations do not glue together… Unless you chain them!

    kick it on DotNetKicks.com

    Chaining IControllerFactory

    The ChainedControllerFactory that I will be creating is quite easy: it builds a list of IControllerFactory instances that may be able to create an IController and asks them one by one to create it. The one that can create it, will be the one that delivers the controller. In code:

    public class ChainedControllerFactory : IControllerFactory
    {
        const string CHAINEDCONTROLLERFACTORY = "__chainedControllerFactory";

        protected List<IControllerFactory> factories = new List<IControllerFactory>();

        public ChainedControllerFactory Register(IControllerFactory factory)
        {
            factories.Add(factory);
            return this;
        }

        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            IController controller = null;
            foreach (IControllerFactory factory in factories)
            {
                controller = factory.CreateController(requestContext, controllerName);
                if (controller != null)
                {
                    requestContext.HttpContext.Items[CHAINEDCONTROLLERFACTORY] = factory;
                    return controller;
                }
            }

            return null;
        }

        public void ReleaseController(IController controller)
        {
            IControllerFactory factory =
                HttpContext.Current.Items[CHAINEDCONTROLLERFACTORY] as IControllerFactory;
            if (factory != null)
                factory.ReleaseController(controller);
        }
    }

    We have to register this one as the default IControllerFactory in Global.asax.cs:

    protected void Application_Start()
    {
        ChainedControllerFactory controllerFactory = new ChainedControllerFactory();
        controllerFactory
            .Register(new DummyControllerFactory())
            .Register(new OnlyHomeControllerFactory())
            .Register(new DefaultControllerFactory());

        ControllerBuilder.Current.SetControllerFactory(controllerFactory);

        RegisterRoutes(RouteTable.Routes);
    }

    Note: the DummyControllerFactory and the OnlyHomeControllerFactory are some sample, stupid IControllerFactory implementations.

    Caveats

    There is actually one caveat to know when using this ChainedControllerFactory: not all controller factories out there follow the convention of returning null when they can not create a controller. The ChainedControllerFactory expects null to determine if it should try the next IControllerFactory in the chain.

    Download source code

    You can download example source code here: MvcChainedControllerFactory.zip (244.37 kb) (sample uses MVC 2, code should work on MVC 1 as well)

    kick it on DotNetKicks.com


    Book review: ASP.NET 3.5 CMS Development

    ASP.NET 3.5 CMS Development From time to time, the people at Packt Publishing send me a free book, fresh of the presses, and ask nicely if I want to read it and write a review on my blog. Last week, I received their fresh ASP.NET 3.5 CMS Development book, written by Curt Christianson and Jeff Cochran, both Microsoft MVP (ASP.NET and IIS).

    According to the website, the book aims at learning people how to build a CMS. Now, I know from writing my ASP.NET MVC 1.0 Quickly book that these texts are written mostly by marketing people.

    This step-by-step tutorial shows the reader how to build an ASP.NET Content Management System from scratch. You will first learn the basics of a content management system and how to set up the tools you need to build your site. Then, you start building your site, setting up users, and adding content to your site. You will be able to edit the content of your site and also manage its layout all by yourself. Towards the end, you will learn to manage your site from a single point and will have all the information you need to extend your site to make it more powerful.

    Filled with plenty of code snippets and screen images to keep you on track as well as numerous additional samples to show you all the exciting alternatives to explore, this book prepares you for all the challenges you can face in development. 

    Ok, it is true: this book will show you how to build a content management system in ASP.NET 3.5. However, if you are a developer working with ASP.NET for several years and the CMS part is the reason you are buying this book, you will be a bit disappointed. Don’t get me wrong, the book is good for another audience: if you are making your first steps in ASP.NET development and want to learn how things like datasources, n-tier development, membership provider, extensibility, … work, by example, this book is actually pretty good at that. Curt and Jeff managed to squeeze in about all commonly used ASP.NET features using only one example application that is built from ground up.

    Conclusion: probably not the book for experienced developers, but an ideal “large, example-driven tutorial” for beginning development with ASP.NET 3.5.


    Book review: ASP.NET 3.5 Social Networking

    image Last week, I found another book from Packt in my letterbox. This time, the title is ASP.NET 3.5 Social Networking, written by Andrew Siemer.

    On the back cover, I read that this book shows you how to create a scalable, maintainable social network that can support hundreds of thousands of users, multimedia features and stuff like that. The words scalable and maintainable seem to have triggered me: I started reading ASAP. The first chapter talks about what a social network is and proposes a new social network: Fisharoo.com, a web site for salt water aquarium fanatics, complete with blogs, forums, personal web sites, …

    The book starts by building a framework containing several features such as logging, mail sending, …, all backed-up by a dependency injection framework to enable fast replacement of several components. Afterwards, each feature of the Fisharoo.com site is described in a separate chapter: what is the feature, how will we store data, what do we need to do in our application to make it work?

    A good thing about this book is that it demonstrates several concepts in application design using a sample application that anyone who has used a site like Facebook is familiar with. The concepts demonstrated are some that any application can benefit from: Domain Driven Design, Test Driven Design (TDD), Dependency Injection, Model-View-Presenter, … Next to this, some third-party components like Lucene.NET are demonstrated. This all is very readable and understandable, really a must-read for anyone interested in these concepts!

    Bottom line of the story: it has been a while since I was enthousiast about a book, and this one clearly made me enthousiast. Sure, it describes stuff about building a social network, but I think that is only a cover for what this book is really about: building good software that is easy to maintain, test and extend.


    Book review: ASP.NET 3.5 Application Architecture and Design

    image The people at Packt asked it again: “Do you want to review this book?” Sure I do! The book I’m reviewing this time is ASP.NET 3.5 Application Architecture and Design, written by Vivek Thakur.

    Application Architecture is always an interesting topic to read on. Different people have different opinions, there is no one perfect solution to a problem, … This book covers application architecture, applied to ASP.NET, although these concepts can be applied in any application. Questions like “What are tiers?” and “How do you structure an application?” are dug into in the first few chapters. The next chapters focus on more specific areas of application architecture: the domain model, UML, creating an ER diagram, SOA, the ASP.NET MVC framework, … Each of these concepts is explained using a single project example, which makes it easy to see the differences, pro’s and con’s of a certain solution.

    To be honest, I don’t think this book is something for experienced architects or lead developers. More experienced architects will probably remain a little bit hungry because large, complex, real-world architectures are not covered or illustrated. The book covers all concepts of application architecture using a simple example, which makes them clear to any developer who is interested in architecture but has always been affraid of all these concepts.

    If you are familiar with the words “N-Tier”, “domain model” and other architectural concepts, I think this book might not be covering architecture deep enough. Are you a developer wanting to release some open-source software? Unaware of the concepts mentioned? Then read this book as it is a great starter book.


    ASP.NET MVC XForms released on CodePlex

    Just noticed there's a new project on CodePlex related to the ASP.NET MVC framework: MVC XForms. MVC XForms is a simple UI framework for ASP.NET MVC based on the W3C XForms specification. It provides a set of form controls that allow updating of complex model objects.

    Picked these project goals from Jon Curtis' blog:

    • To allow automatic form population, deserialization and validation based on the (arbitrarily complex) model.
    • To produce semantic HTML forms using the logic of XForms.
    • To output clean, terse HTML.
    • No javascript, unless necessary and always optional and unobtrusive.
    • To enable clean, terse view code.
    • To make the framework as extensible and customisable as possible without compromising simplicity or the above goals.
    • Use convention over configuration and a fluent API.

    Great story, but how does it work?

    I haven't gone into any advanced scenario's, but have instead used a simple case to demonstrate some of the MVC XForms basics. First of all, I've created a Person class with an Id (int), Name (string) and BirthDate (DateTime). This class is used by a specific view in my application, of which the view markup looks like this:

    <% Html.XForm(ViewData.Model).Form(form => { %>
      <%=form.Input(p => p.Name).Label("Name") %>
      <%=form.Input(p => p.BirthDate).Label("Birth date") %>
    <% }); %>

    This is all there is to creating an MVC XForm. Note that I'm creating a XForm based on my model, and that I want an input field for the Name and BirthDate properties, each with a label supplied.

    On to rendering: the HTML generated by MVC XForm looks like the following:

    <form action="" method="post" class="xf xform">
      <div class="xf input text">
        <label for="Name">Name</label>
        <input id="Name" type="text" name="Name" value="Maarten Balliauw"/>
      </div>
      <div class="xf input date">
        <label for="BirthDate">Birth date</label>
        <input id="BirthDate" type="text" name="BirthDate" value="21-12-1983"/>
      </div>
    </form>
    <script type="text/javascript">
      $(document).ready(function(){mvc.xforms.init({"id":"","cons":[]})});
    </script>

    That's actually nice, clean HTML markup! Note the CSS classes that are applied on certain fields. For example, the div element for BirthDate has a CSS class "date", which can be used by, for example, jQuery to enable a date picker on that field.

    More information

    In the CodePlex download (http://www.codeplex.com/mvcxforms), there is a sample project which makes use of all simple and advanced ideas in MVC XForms. You can also check out Jon Curtis' blog posts on MVC XForms to read some more samples.

    kick it on DotNetKicks.com


    Creating a generic Linq to SQL ModelBinder for the ASP.NET MVC framework

    You are right! This is indeed my third post on ASP.NET MVC ModelBinders. The first one focussed on creating a ModelBinder from scratch in an older preview release, the second post did something similar trying to do some dirty ViewState-like stuff. Good news! There's more of this dirty stuff coming!

    How about this action method, using a Person class which is a Linq to SQL entity type:

    public ActionResult PersonDetails(Person id)
    {
        if (id == null)
            return RedirectToAction("Index");

        return View(id);
    }

    This action method is called from a URL which looks like Home/PersonDetails/2. Nothing special about this? Read this whole post again, from the beginning! Yes, I said that the Person class is a Linq to SQL entity type, and yes, you are missing the DataContext here! The above method would normally look like this:

    public ActionResult PersonDetails(int id)
    {
        using (ApplicationDataContext context = new ApplicationDataContext())
        {
            Person person = context.Persons.Where(p => p.Id == id).SingleOrDefault();

            if (person == null)
                return RedirectToAction("Index");

            return View(person);
        }
    }

    Using the ASP.NET MVC ModelBinder infrastructure, I am actually able to bind action method parameters to real objects, based on simple query string parameters like, in this case, id. A custom ModelBinder maps this string id to a real Person instance from my Linq to SQL DataContext. Let me show you how I've created this ModelBinder.

    Registering the LinqToSqlBinder<T>

    As with any custom ModelBinder, the LinqToSqlBinder should be registered with the ModelBinder infrastructure:

    protected void Application_Start()
    {
        // ...

        LinqToSqlBinder<ApplicationDataContext>.Register(ModelBinders.Binders);
    }

    The above piece of code registers every entity type (or table, whatever you like to call it) in my Linq to Sql data contextwith a new LinqToSqlBinder<ApplicationDataContext> instance.

    public static void Register(IDictionary<Type, IModelBinder> bindersDictionary)
    {
        using (T context = new T())
        {
            foreach (var table in context.Mapping.GetTables())
            {
                ModelBinders.Binders.Add(table.RowType.Type, new LinqToSqlBinder<T>());
            }
        }
    }

    The LinqToSqlBinder<T> source code

    The LinqToSqlBinder<T> will make use of a small utility class, TableDefinition, in which some information about the entity type's table will be stored. This class looks like the following:

    private class TableDefinition
    {
        public TableDefinition()
        {
            ColumnNames = new List<string>();
        }

        public string TableName;
        public string PrimaryKeyFieldName;
        public List<string> ColumnNames { get; set; }
    }

    My LinqToSqlBinder<T> overloads ASP.NET MVC's DefaultModelBinder class, of which I'll override the BindModel method:

    public class LinqToSqlBinder<T> : DefaultModelBinder
    {
        public override ModelBinderResult BindModel(ModelBindingContext bindingContext)
        {
            // ...
        }
    }

    First of all, the LinqToSqlBinder<T> has to determine if it can actually perform binding for the requested model type. In this case, this is determined using the metadata my Linq to SQL data context provides. If it does not support mapping the requested type, model binding is further processed by the base class.

    // Check if bindingContext.ModelType can be delivered from T
    MetaTable metaTable = context.Mapping.GetTable(bindingContext.ModelType);
    if (metaTable == null)
    {
        return base.BindModel(bindingContext);
    }

    Next task for the model binder: checking whether a value is provided. For example, if my action method expects a parameter named "id" and I provide a parameter "borat" (whatever...) in the request, the model binder should not accept the task given. If everything succeeds, I should have an identity value which I can use in a query later on.

    // Get the object ID that is being passed in.
    ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
    if (valueProviderResult == null)
    {
        return base.BindModel(bindingContext);
    }
    string objectId = valueProviderResult.AttemptedValue;

    Speaking of queries... Now is a good time to start filling my TableDefinition instance, on which I can generate a SQL query which will later retrieve the requested object. Filling the TableDefinition object is really an easy task when using the meta data Linq to SQL provides. Each member (or column) can be looped and queried for specific information such as type, name, primary key, ...

    // Build table definition
    TableDefinition tableDefinition = new TableDefinition();
    tableDefinition.TableName = metaTable.TableName;

    foreach (MetaDataMember dm in metaTable.RowType.DataMembers)
    {
        if (dm.DbType != null)
        {
            tableDefinition.ColumnNames.Add(dm.MappedName);
        }
        if (dm.IsPrimaryKey)
        {
            tableDefinition.PrimaryKeyFieldName = dm.MappedName;
        }
    }

    With all this information in place, a SQL query can easily be built.

    // Build query
    StringBuilder queryBuffer = new StringBuilder();
    queryBuffer.Append("SELECT ")
                    .Append(string.Join(", ", tableDefinition.ColumnNames.ToArray()))
               .Append(" FROM ")
                    .Append(tableDefinition.TableName)
               .Append(" WHERE ")
                    .Append(tableDefinition.PrimaryKeyFieldName)
                    .Append(" = \'").Append(objectId).Append("\'");

    A nice looking query is generated using this code: SELECT id, name, email FROM dbo.person WHERE id = '2'. This query can now be executed on the Linq to SQL data context. The first result will be returned to the action method.

    // Execute query
    IEnumerable resultData = context.ExecuteQuery(bindingContext.ModelType,
        queryBuffer.ToString());

    foreach (object result in resultData)
    {
        return new ModelBinderResult(result);
    }

    Download the code

    Feel free to download a working example based on this blog post: LinqModelBinderExample.zip (352.52 kb)

    Note that this code may be vulnerable to SQL injection! This is not production code!

    kick it on DotNetKicks.com


    CarTrackr - Sample ASP.NET MVC application

    CarTrackr - Sample ASP.NET MVC application Some people may have already noticed the link in my VISUG session blog post, but for those who didn't... I've released my sample application CarTrackr on CodePlex.

    CarTrackr is a sample application for the ASP.NET MVC framework using the repository pattern and dependency injection using the Unity application block. It was written for various demos in presentations done by Maarten Balliauw.

    CarTrackr is an online software application designed to help you understand and track your fuel usage and kilometers driven.

    You will have a record on when you filled up on fuel, how many kilometers you got in a given tank, how much you spent and how much liters of fuel you are using per 100 kilometer.

    CarTrackr will enable you to improve your fuel economy and save money as well as conserve fuel. Fuel economy and conservation is becoming an important way to control your finances with the current high price.

    Go get the source code for CarTrackr on CodePlex! (note that it has been updated for ASP.NET MVC beta 1)

    Technologies and techniques used

    Here's a list of technologies and techniques used:

    • CarTrackr uses the Unity application block to provide dependency injection
    • The repository design pattern is used for building a flexible data layer
    • Controllers are instantiated by using a custom ASP.NET MVC ControllerBuilder, which uses Unity for dependency resolving
    • The testing project makes use of Moq to mock out parts of the ASP.NET runtime
    • Form validation is included on most forms, leveraging the ViewData.ModelState class
    • It is possible to sign in using OpenID, for which the ASP.NET MVC Membership starter kit was used
    • LinqToSQL is used as the persistence layer
    • CarTrackr uses my ASP.NET MVC sitemap provider
    • Configuration Section Designer was used to create a custom configuration section
    • Extension methods are created for including Silverlight charts (rendered with Visifire)
    • Web 2.0 logo creator was used to generate a classy logo

    kick it on DotNetKicks.com